diff --git a/OWNERS b/OWNERS index 97d0ffecea..1e07f88543 100644 --- a/OWNERS +++ b/OWNERS @@ -16,6 +16,7 @@ reviewers: - deads2k - jpbetz - liggitt + - skitt - soltysh - sttts - yliaog diff --git a/README.md b/README.md index 1e6be434aa..e866c6721e 100644 --- a/README.md +++ b/README.md @@ -75,14 +75,14 @@ We will backport bugfixes--but not new features--into older versions of #### Compatibility matrix -| | Kubernetes 1.23 | Kubernetes 1.24 | Kubernetes 1.25 | Kubernetes 1.26 | Kubernetes 1.27 | Kubernetes 1.28 | +| | Kubernetes 1.27 | Kubernetes 1.28 | Kubernetes 1.29 | Kubernetes 1.30 | Kubernetes 1.31 | Kubernetes 1.32 | | ----------------------------- | --------------- | --------------- | --------------- | --------------- | --------------- | --------------- | -| `kubernetes-1.23.0`/`v0.23.0` | ✓ | +- | +- | +- | +- | +- | -| `kubernetes-1.24.0`/`v0.24.0` | +- | ✓ | +- | +- | +- | +- | -| `kubernetes-1.25.0`/`v0.25.0` | +- | +- | ✓ | +- | +- | +- | -| `kubernetes-1.26.0`/`v0.26.0` | +- | +- | +- | ✓ | +- | +- | -| `kubernetes-1.27.0`/`v0.27.0` | +- | +- | +- | +- | ✓ | +- | -| `kubernetes-1.28.0`/`v0.28.0` | +- | +- | +- | +- | +- | ✓ | +| `kubernetes-1.27.0`/`v0.27.0` | ✓ | +- | +- | +- | +- | +- | +| `kubernetes-1.28.0`/`v0.28.0` | +- | ✓ | +- | +- | +- | +- | +| `kubernetes-1.29.0`/`v0.29.0` | +- | +- | ✓ | +- | +- | +- | +| `kubernetes-1.30.0`/`v0.30.0` | +- | +- | +- | ✓ | +- | +- | +| `kubernetes-1.31.0`/`v0.31.0` | +- | +- | +- | +- | ✓ | +- | +| `kubernetes-1.32.0`/`v0.32.0` | +- | +- | +- | +- | +- | ✓ | | `HEAD` | +- | +- | +- | +- | +- | +- | Key: @@ -104,16 +104,16 @@ between client-go versions. | Branch | Canonical source code location | Maintenance status | | -------------- | ----------------------------------- | ------------------ | -| `release-1.19` | Kubernetes main repo, 1.19 branch | =- | -| `release-1.20` | Kubernetes main repo, 1.20 branch | =- | -| `release-1.21` | Kubernetes main repo, 1.21 branch | =- | -| `release-1.22` | Kubernetes main repo, 1.22 branch | =- | | `release-1.23` | Kubernetes main repo, 1.23 branch | =- | | `release-1.24` | Kubernetes main repo, 1.24 branch | =- | -| `release-1.25` | Kubernetes main repo, 1.25 branch | ✓ | -| `release-1.26` | Kubernetes main repo, 1.26 branch | ✓ | -| `release-1.27` | Kubernetes main repo, 1.27 branch | ✓ | -| `release-1.28` | Kubernetes main repo, 1.28 branch | ✓ | +| `release-1.25` | Kubernetes main repo, 1.25 branch | =- | +| `release-1.26` | Kubernetes main repo, 1.26 branch | =- | +| `release-1.27` | Kubernetes main repo, 1.27 branch | =- | +| `release-1.28` | Kubernetes main repo, 1.28 branch | =- | +| `release-1.29` | Kubernetes main repo, 1.29 branch | ✓ | +| `release-1.30` | Kubernetes main repo, 1.30 branch | ✓ | +| `release-1.31` | Kubernetes main repo, 1.31 branch | ✓ | +| `release-1.32` | Kubernetes main repo, 1.32 branch | ✓ | | client-go HEAD | Kubernetes main repo, master branch | ✓ | Key: diff --git a/applyconfigurations/OWNERS b/applyconfigurations/OWNERS index ea0928429d..de4067fd35 100644 --- a/applyconfigurations/OWNERS +++ b/applyconfigurations/OWNERS @@ -3,3 +3,4 @@ approvers: - apelisse - jpbetz + - api-approvers diff --git a/applyconfigurations/apps/v1/deploymentstatus.go b/applyconfigurations/apps/v1/deploymentstatus.go index 747813ade8..8d9e6cca28 100644 --- a/applyconfigurations/apps/v1/deploymentstatus.go +++ b/applyconfigurations/apps/v1/deploymentstatus.go @@ -27,6 +27,7 @@ type DeploymentStatusApplyConfiguration struct { ReadyReplicas *int32 `json:"readyReplicas,omitempty"` AvailableReplicas *int32 `json:"availableReplicas,omitempty"` UnavailableReplicas *int32 `json:"unavailableReplicas,omitempty"` + TerminatingReplicas *int32 `json:"terminatingReplicas,omitempty"` Conditions []DeploymentConditionApplyConfiguration `json:"conditions,omitempty"` CollisionCount *int32 `json:"collisionCount,omitempty"` } @@ -85,6 +86,14 @@ func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32 return b } +// WithTerminatingReplicas sets the TerminatingReplicas field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TerminatingReplicas field is set to the value of the last call. +func (b *DeploymentStatusApplyConfiguration) WithTerminatingReplicas(value int32) *DeploymentStatusApplyConfiguration { + b.TerminatingReplicas = &value + return b +} + // WithConditions adds the given value to the Conditions field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the Conditions field. diff --git a/applyconfigurations/apps/v1/replicasetstatus.go b/applyconfigurations/apps/v1/replicasetstatus.go index a1408ae25e..d11526d60a 100644 --- a/applyconfigurations/apps/v1/replicasetstatus.go +++ b/applyconfigurations/apps/v1/replicasetstatus.go @@ -25,6 +25,7 @@ type ReplicaSetStatusApplyConfiguration struct { FullyLabeledReplicas *int32 `json:"fullyLabeledReplicas,omitempty"` ReadyReplicas *int32 `json:"readyReplicas,omitempty"` AvailableReplicas *int32 `json:"availableReplicas,omitempty"` + TerminatingReplicas *int32 `json:"terminatingReplicas,omitempty"` ObservedGeneration *int64 `json:"observedGeneration,omitempty"` Conditions []ReplicaSetConditionApplyConfiguration `json:"conditions,omitempty"` } @@ -67,6 +68,14 @@ func (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) return b } +// WithTerminatingReplicas sets the TerminatingReplicas field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TerminatingReplicas field is set to the value of the last call. +func (b *ReplicaSetStatusApplyConfiguration) WithTerminatingReplicas(value int32) *ReplicaSetStatusApplyConfiguration { + b.TerminatingReplicas = &value + return b +} + // WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ObservedGeneration field is set to the value of the last call. diff --git a/applyconfigurations/apps/v1beta1/deploymentstatus.go b/applyconfigurations/apps/v1beta1/deploymentstatus.go index adc023a34d..36b4fd42b6 100644 --- a/applyconfigurations/apps/v1beta1/deploymentstatus.go +++ b/applyconfigurations/apps/v1beta1/deploymentstatus.go @@ -27,6 +27,7 @@ type DeploymentStatusApplyConfiguration struct { ReadyReplicas *int32 `json:"readyReplicas,omitempty"` AvailableReplicas *int32 `json:"availableReplicas,omitempty"` UnavailableReplicas *int32 `json:"unavailableReplicas,omitempty"` + TerminatingReplicas *int32 `json:"terminatingReplicas,omitempty"` Conditions []DeploymentConditionApplyConfiguration `json:"conditions,omitempty"` CollisionCount *int32 `json:"collisionCount,omitempty"` } @@ -85,6 +86,14 @@ func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32 return b } +// WithTerminatingReplicas sets the TerminatingReplicas field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TerminatingReplicas field is set to the value of the last call. +func (b *DeploymentStatusApplyConfiguration) WithTerminatingReplicas(value int32) *DeploymentStatusApplyConfiguration { + b.TerminatingReplicas = &value + return b +} + // WithConditions adds the given value to the Conditions field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the Conditions field. diff --git a/applyconfigurations/apps/v1beta2/deploymentstatus.go b/applyconfigurations/apps/v1beta2/deploymentstatus.go index 5fa9122332..554be024d9 100644 --- a/applyconfigurations/apps/v1beta2/deploymentstatus.go +++ b/applyconfigurations/apps/v1beta2/deploymentstatus.go @@ -27,6 +27,7 @@ type DeploymentStatusApplyConfiguration struct { ReadyReplicas *int32 `json:"readyReplicas,omitempty"` AvailableReplicas *int32 `json:"availableReplicas,omitempty"` UnavailableReplicas *int32 `json:"unavailableReplicas,omitempty"` + TerminatingReplicas *int32 `json:"terminatingReplicas,omitempty"` Conditions []DeploymentConditionApplyConfiguration `json:"conditions,omitempty"` CollisionCount *int32 `json:"collisionCount,omitempty"` } @@ -85,6 +86,14 @@ func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32 return b } +// WithTerminatingReplicas sets the TerminatingReplicas field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TerminatingReplicas field is set to the value of the last call. +func (b *DeploymentStatusApplyConfiguration) WithTerminatingReplicas(value int32) *DeploymentStatusApplyConfiguration { + b.TerminatingReplicas = &value + return b +} + // WithConditions adds the given value to the Conditions field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the Conditions field. diff --git a/applyconfigurations/apps/v1beta2/replicasetstatus.go b/applyconfigurations/apps/v1beta2/replicasetstatus.go index d3c92e274d..13004fde38 100644 --- a/applyconfigurations/apps/v1beta2/replicasetstatus.go +++ b/applyconfigurations/apps/v1beta2/replicasetstatus.go @@ -25,6 +25,7 @@ type ReplicaSetStatusApplyConfiguration struct { FullyLabeledReplicas *int32 `json:"fullyLabeledReplicas,omitempty"` ReadyReplicas *int32 `json:"readyReplicas,omitempty"` AvailableReplicas *int32 `json:"availableReplicas,omitempty"` + TerminatingReplicas *int32 `json:"terminatingReplicas,omitempty"` ObservedGeneration *int64 `json:"observedGeneration,omitempty"` Conditions []ReplicaSetConditionApplyConfiguration `json:"conditions,omitempty"` } @@ -67,6 +68,14 @@ func (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) return b } +// WithTerminatingReplicas sets the TerminatingReplicas field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TerminatingReplicas field is set to the value of the last call. +func (b *ReplicaSetStatusApplyConfiguration) WithTerminatingReplicas(value int32) *ReplicaSetStatusApplyConfiguration { + b.TerminatingReplicas = &value + return b +} + // WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ObservedGeneration field is set to the value of the last call. diff --git a/applyconfigurations/autoscaling/v2/hpascalingrules.go b/applyconfigurations/autoscaling/v2/hpascalingrules.go index 6a6a2655f5..6fd0f25cc1 100644 --- a/applyconfigurations/autoscaling/v2/hpascalingrules.go +++ b/applyconfigurations/autoscaling/v2/hpascalingrules.go @@ -20,6 +20,7 @@ package v2 import ( autoscalingv2 "k8s.io/api/autoscaling/v2" + resource "k8s.io/apimachinery/pkg/api/resource" ) // HPAScalingRulesApplyConfiguration represents a declarative configuration of the HPAScalingRules type for use @@ -28,6 +29,7 @@ type HPAScalingRulesApplyConfiguration struct { StabilizationWindowSeconds *int32 `json:"stabilizationWindowSeconds,omitempty"` SelectPolicy *autoscalingv2.ScalingPolicySelect `json:"selectPolicy,omitempty"` Policies []HPAScalingPolicyApplyConfiguration `json:"policies,omitempty"` + Tolerance *resource.Quantity `json:"tolerance,omitempty"` } // HPAScalingRulesApplyConfiguration constructs a declarative configuration of the HPAScalingRules type for use with @@ -64,3 +66,11 @@ func (b *HPAScalingRulesApplyConfiguration) WithPolicies(values ...*HPAScalingPo } return b } + +// WithTolerance sets the Tolerance field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Tolerance field is set to the value of the last call. +func (b *HPAScalingRulesApplyConfiguration) WithTolerance(value resource.Quantity) *HPAScalingRulesApplyConfiguration { + b.Tolerance = &value + return b +} diff --git a/applyconfigurations/certificates/v1beta1/clustertrustbundle.go b/applyconfigurations/certificates/v1beta1/clustertrustbundle.go new file mode 100644 index 0000000000..365fb9b0e0 --- /dev/null +++ b/applyconfigurations/certificates/v1beta1/clustertrustbundle.go @@ -0,0 +1,253 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + certificatesv1beta1 "k8s.io/api/certificates/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ClusterTrustBundleApplyConfiguration represents a declarative configuration of the ClusterTrustBundle type for use +// with apply. +type ClusterTrustBundleApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *ClusterTrustBundleSpecApplyConfiguration `json:"spec,omitempty"` +} + +// ClusterTrustBundle constructs a declarative configuration of the ClusterTrustBundle type for use with +// apply. +func ClusterTrustBundle(name string) *ClusterTrustBundleApplyConfiguration { + b := &ClusterTrustBundleApplyConfiguration{} + b.WithName(name) + b.WithKind("ClusterTrustBundle") + b.WithAPIVersion("certificates.k8s.io/v1beta1") + return b +} + +// ExtractClusterTrustBundle extracts the applied configuration owned by fieldManager from +// clusterTrustBundle. If no managedFields are found in clusterTrustBundle for fieldManager, a +// ClusterTrustBundleApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// clusterTrustBundle must be a unmodified ClusterTrustBundle API object that was retrieved from the Kubernetes API. +// ExtractClusterTrustBundle provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractClusterTrustBundle(clusterTrustBundle *certificatesv1beta1.ClusterTrustBundle, fieldManager string) (*ClusterTrustBundleApplyConfiguration, error) { + return extractClusterTrustBundle(clusterTrustBundle, fieldManager, "") +} + +// ExtractClusterTrustBundleStatus is the same as ExtractClusterTrustBundle except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractClusterTrustBundleStatus(clusterTrustBundle *certificatesv1beta1.ClusterTrustBundle, fieldManager string) (*ClusterTrustBundleApplyConfiguration, error) { + return extractClusterTrustBundle(clusterTrustBundle, fieldManager, "status") +} + +func extractClusterTrustBundle(clusterTrustBundle *certificatesv1beta1.ClusterTrustBundle, fieldManager string, subresource string) (*ClusterTrustBundleApplyConfiguration, error) { + b := &ClusterTrustBundleApplyConfiguration{} + err := managedfields.ExtractInto(clusterTrustBundle, internal.Parser().Type("io.k8s.api.certificates.v1beta1.ClusterTrustBundle"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(clusterTrustBundle.Name) + + b.WithKind("ClusterTrustBundle") + b.WithAPIVersion("certificates.k8s.io/v1beta1") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithKind(value string) *ClusterTrustBundleApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithAPIVersion(value string) *ClusterTrustBundleApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithName(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithGenerateName(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithNamespace(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithUID(value types.UID) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithResourceVersion(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithGeneration(value int64) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ClusterTrustBundleApplyConfiguration) WithLabels(entries map[string]string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ClusterTrustBundleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ClusterTrustBundleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ClusterTrustBundleApplyConfiguration) WithFinalizers(values ...string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ClusterTrustBundleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithSpec(value *ClusterTrustBundleSpecApplyConfiguration) *ClusterTrustBundleApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ClusterTrustBundleApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/certificates/v1beta1/clustertrustbundlespec.go b/applyconfigurations/certificates/v1beta1/clustertrustbundlespec.go new file mode 100644 index 0000000000..157a9efa84 --- /dev/null +++ b/applyconfigurations/certificates/v1beta1/clustertrustbundlespec.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// ClusterTrustBundleSpecApplyConfiguration represents a declarative configuration of the ClusterTrustBundleSpec type for use +// with apply. +type ClusterTrustBundleSpecApplyConfiguration struct { + SignerName *string `json:"signerName,omitempty"` + TrustBundle *string `json:"trustBundle,omitempty"` +} + +// ClusterTrustBundleSpecApplyConfiguration constructs a declarative configuration of the ClusterTrustBundleSpec type for use with +// apply. +func ClusterTrustBundleSpec() *ClusterTrustBundleSpecApplyConfiguration { + return &ClusterTrustBundleSpecApplyConfiguration{} +} + +// WithSignerName sets the SignerName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the SignerName field is set to the value of the last call. +func (b *ClusterTrustBundleSpecApplyConfiguration) WithSignerName(value string) *ClusterTrustBundleSpecApplyConfiguration { + b.SignerName = &value + return b +} + +// WithTrustBundle sets the TrustBundle field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TrustBundle field is set to the value of the last call. +func (b *ClusterTrustBundleSpecApplyConfiguration) WithTrustBundle(value string) *ClusterTrustBundleSpecApplyConfiguration { + b.TrustBundle = &value + return b +} diff --git a/applyconfigurations/coordination/v1beta1/leasecandidate.go b/applyconfigurations/coordination/v1beta1/leasecandidate.go new file mode 100644 index 0000000000..2e1c812191 --- /dev/null +++ b/applyconfigurations/coordination/v1beta1/leasecandidate.go @@ -0,0 +1,255 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + coordinationv1beta1 "k8s.io/api/coordination/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// LeaseCandidateApplyConfiguration represents a declarative configuration of the LeaseCandidate type for use +// with apply. +type LeaseCandidateApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *LeaseCandidateSpecApplyConfiguration `json:"spec,omitempty"` +} + +// LeaseCandidate constructs a declarative configuration of the LeaseCandidate type for use with +// apply. +func LeaseCandidate(name, namespace string) *LeaseCandidateApplyConfiguration { + b := &LeaseCandidateApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("LeaseCandidate") + b.WithAPIVersion("coordination.k8s.io/v1beta1") + return b +} + +// ExtractLeaseCandidate extracts the applied configuration owned by fieldManager from +// leaseCandidate. If no managedFields are found in leaseCandidate for fieldManager, a +// LeaseCandidateApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// leaseCandidate must be a unmodified LeaseCandidate API object that was retrieved from the Kubernetes API. +// ExtractLeaseCandidate provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractLeaseCandidate(leaseCandidate *coordinationv1beta1.LeaseCandidate, fieldManager string) (*LeaseCandidateApplyConfiguration, error) { + return extractLeaseCandidate(leaseCandidate, fieldManager, "") +} + +// ExtractLeaseCandidateStatus is the same as ExtractLeaseCandidate except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractLeaseCandidateStatus(leaseCandidate *coordinationv1beta1.LeaseCandidate, fieldManager string) (*LeaseCandidateApplyConfiguration, error) { + return extractLeaseCandidate(leaseCandidate, fieldManager, "status") +} + +func extractLeaseCandidate(leaseCandidate *coordinationv1beta1.LeaseCandidate, fieldManager string, subresource string) (*LeaseCandidateApplyConfiguration, error) { + b := &LeaseCandidateApplyConfiguration{} + err := managedfields.ExtractInto(leaseCandidate, internal.Parser().Type("io.k8s.api.coordination.v1beta1.LeaseCandidate"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(leaseCandidate.Name) + b.WithNamespace(leaseCandidate.Namespace) + + b.WithKind("LeaseCandidate") + b.WithAPIVersion("coordination.k8s.io/v1beta1") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithKind(value string) *LeaseCandidateApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithAPIVersion(value string) *LeaseCandidateApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithName(value string) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithGenerateName(value string) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithNamespace(value string) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithUID(value types.UID) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithResourceVersion(value string) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithGeneration(value int64) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *LeaseCandidateApplyConfiguration) WithLabels(entries map[string]string) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *LeaseCandidateApplyConfiguration) WithAnnotations(entries map[string]string) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *LeaseCandidateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *LeaseCandidateApplyConfiguration) WithFinalizers(values ...string) *LeaseCandidateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *LeaseCandidateApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *LeaseCandidateApplyConfiguration) WithSpec(value *LeaseCandidateSpecApplyConfiguration) *LeaseCandidateApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *LeaseCandidateApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/coordination/v1beta1/leasecandidatespec.go b/applyconfigurations/coordination/v1beta1/leasecandidatespec.go new file mode 100644 index 0000000000..c3ea12c813 --- /dev/null +++ b/applyconfigurations/coordination/v1beta1/leasecandidatespec.go @@ -0,0 +1,89 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + coordinationv1 "k8s.io/api/coordination/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// LeaseCandidateSpecApplyConfiguration represents a declarative configuration of the LeaseCandidateSpec type for use +// with apply. +type LeaseCandidateSpecApplyConfiguration struct { + LeaseName *string `json:"leaseName,omitempty"` + PingTime *v1.MicroTime `json:"pingTime,omitempty"` + RenewTime *v1.MicroTime `json:"renewTime,omitempty"` + BinaryVersion *string `json:"binaryVersion,omitempty"` + EmulationVersion *string `json:"emulationVersion,omitempty"` + Strategy *coordinationv1.CoordinatedLeaseStrategy `json:"strategy,omitempty"` +} + +// LeaseCandidateSpecApplyConfiguration constructs a declarative configuration of the LeaseCandidateSpec type for use with +// apply. +func LeaseCandidateSpec() *LeaseCandidateSpecApplyConfiguration { + return &LeaseCandidateSpecApplyConfiguration{} +} + +// WithLeaseName sets the LeaseName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the LeaseName field is set to the value of the last call. +func (b *LeaseCandidateSpecApplyConfiguration) WithLeaseName(value string) *LeaseCandidateSpecApplyConfiguration { + b.LeaseName = &value + return b +} + +// WithPingTime sets the PingTime field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PingTime field is set to the value of the last call. +func (b *LeaseCandidateSpecApplyConfiguration) WithPingTime(value v1.MicroTime) *LeaseCandidateSpecApplyConfiguration { + b.PingTime = &value + return b +} + +// WithRenewTime sets the RenewTime field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the RenewTime field is set to the value of the last call. +func (b *LeaseCandidateSpecApplyConfiguration) WithRenewTime(value v1.MicroTime) *LeaseCandidateSpecApplyConfiguration { + b.RenewTime = &value + return b +} + +// WithBinaryVersion sets the BinaryVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BinaryVersion field is set to the value of the last call. +func (b *LeaseCandidateSpecApplyConfiguration) WithBinaryVersion(value string) *LeaseCandidateSpecApplyConfiguration { + b.BinaryVersion = &value + return b +} + +// WithEmulationVersion sets the EmulationVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EmulationVersion field is set to the value of the last call. +func (b *LeaseCandidateSpecApplyConfiguration) WithEmulationVersion(value string) *LeaseCandidateSpecApplyConfiguration { + b.EmulationVersion = &value + return b +} + +// WithStrategy sets the Strategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Strategy field is set to the value of the last call. +func (b *LeaseCandidateSpecApplyConfiguration) WithStrategy(value coordinationv1.CoordinatedLeaseStrategy) *LeaseCandidateSpecApplyConfiguration { + b.Strategy = &value + return b +} diff --git a/applyconfigurations/core/v1/containerstatus.go b/applyconfigurations/core/v1/containerstatus.go index 6a28939c2f..8f64501bb1 100644 --- a/applyconfigurations/core/v1/containerstatus.go +++ b/applyconfigurations/core/v1/containerstatus.go @@ -39,6 +39,7 @@ type ContainerStatusApplyConfiguration struct { VolumeMounts []VolumeMountStatusApplyConfiguration `json:"volumeMounts,omitempty"` User *ContainerUserApplyConfiguration `json:"user,omitempty"` AllocatedResourcesStatus []ResourceStatusApplyConfiguration `json:"allocatedResourcesStatus,omitempty"` + StopSignal *corev1.Signal `json:"stopSignal,omitempty"` } // ContainerStatusApplyConfiguration constructs a declarative configuration of the ContainerStatus type for use with @@ -168,3 +169,11 @@ func (b *ContainerStatusApplyConfiguration) WithAllocatedResourcesStatus(values } return b } + +// WithStopSignal sets the StopSignal field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the StopSignal field is set to the value of the last call. +func (b *ContainerStatusApplyConfiguration) WithStopSignal(value corev1.Signal) *ContainerStatusApplyConfiguration { + b.StopSignal = &value + return b +} diff --git a/applyconfigurations/core/v1/lifecycle.go b/applyconfigurations/core/v1/lifecycle.go index e37a30f597..f8c18a7502 100644 --- a/applyconfigurations/core/v1/lifecycle.go +++ b/applyconfigurations/core/v1/lifecycle.go @@ -18,11 +18,16 @@ limitations under the License. package v1 +import ( + corev1 "k8s.io/api/core/v1" +) + // LifecycleApplyConfiguration represents a declarative configuration of the Lifecycle type for use // with apply. type LifecycleApplyConfiguration struct { - PostStart *LifecycleHandlerApplyConfiguration `json:"postStart,omitempty"` - PreStop *LifecycleHandlerApplyConfiguration `json:"preStop,omitempty"` + PostStart *LifecycleHandlerApplyConfiguration `json:"postStart,omitempty"` + PreStop *LifecycleHandlerApplyConfiguration `json:"preStop,omitempty"` + StopSignal *corev1.Signal `json:"stopSignal,omitempty"` } // LifecycleApplyConfiguration constructs a declarative configuration of the Lifecycle type for use with @@ -46,3 +51,11 @@ func (b *LifecycleApplyConfiguration) WithPreStop(value *LifecycleHandlerApplyCo b.PreStop = value return b } + +// WithStopSignal sets the StopSignal field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the StopSignal field is set to the value of the last call. +func (b *LifecycleApplyConfiguration) WithStopSignal(value corev1.Signal) *LifecycleApplyConfiguration { + b.StopSignal = &value + return b +} diff --git a/applyconfigurations/core/v1/nodeswapstatus.go b/applyconfigurations/core/v1/nodeswapstatus.go new file mode 100644 index 0000000000..2a7a2e685d --- /dev/null +++ b/applyconfigurations/core/v1/nodeswapstatus.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// NodeSwapStatusApplyConfiguration represents a declarative configuration of the NodeSwapStatus type for use +// with apply. +type NodeSwapStatusApplyConfiguration struct { + Capacity *int64 `json:"capacity,omitempty"` +} + +// NodeSwapStatusApplyConfiguration constructs a declarative configuration of the NodeSwapStatus type for use with +// apply. +func NodeSwapStatus() *NodeSwapStatusApplyConfiguration { + return &NodeSwapStatusApplyConfiguration{} +} + +// WithCapacity sets the Capacity field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Capacity field is set to the value of the last call. +func (b *NodeSwapStatusApplyConfiguration) WithCapacity(value int64) *NodeSwapStatusApplyConfiguration { + b.Capacity = &value + return b +} diff --git a/applyconfigurations/core/v1/nodesysteminfo.go b/applyconfigurations/core/v1/nodesysteminfo.go index 11ac50713c..55effd7171 100644 --- a/applyconfigurations/core/v1/nodesysteminfo.go +++ b/applyconfigurations/core/v1/nodesysteminfo.go @@ -21,16 +21,17 @@ package v1 // NodeSystemInfoApplyConfiguration represents a declarative configuration of the NodeSystemInfo type for use // with apply. type NodeSystemInfoApplyConfiguration struct { - MachineID *string `json:"machineID,omitempty"` - SystemUUID *string `json:"systemUUID,omitempty"` - BootID *string `json:"bootID,omitempty"` - KernelVersion *string `json:"kernelVersion,omitempty"` - OSImage *string `json:"osImage,omitempty"` - ContainerRuntimeVersion *string `json:"containerRuntimeVersion,omitempty"` - KubeletVersion *string `json:"kubeletVersion,omitempty"` - KubeProxyVersion *string `json:"kubeProxyVersion,omitempty"` - OperatingSystem *string `json:"operatingSystem,omitempty"` - Architecture *string `json:"architecture,omitempty"` + MachineID *string `json:"machineID,omitempty"` + SystemUUID *string `json:"systemUUID,omitempty"` + BootID *string `json:"bootID,omitempty"` + KernelVersion *string `json:"kernelVersion,omitempty"` + OSImage *string `json:"osImage,omitempty"` + ContainerRuntimeVersion *string `json:"containerRuntimeVersion,omitempty"` + KubeletVersion *string `json:"kubeletVersion,omitempty"` + KubeProxyVersion *string `json:"kubeProxyVersion,omitempty"` + OperatingSystem *string `json:"operatingSystem,omitempty"` + Architecture *string `json:"architecture,omitempty"` + Swap *NodeSwapStatusApplyConfiguration `json:"swap,omitempty"` } // NodeSystemInfoApplyConfiguration constructs a declarative configuration of the NodeSystemInfo type for use with @@ -118,3 +119,11 @@ func (b *NodeSystemInfoApplyConfiguration) WithArchitecture(value string) *NodeS b.Architecture = &value return b } + +// WithSwap sets the Swap field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Swap field is set to the value of the last call. +func (b *NodeSystemInfoApplyConfiguration) WithSwap(value *NodeSwapStatusApplyConfiguration) *NodeSystemInfoApplyConfiguration { + b.Swap = value + return b +} diff --git a/applyconfigurations/core/v1/podcondition.go b/applyconfigurations/core/v1/podcondition.go index 67cd1bd09b..90bb8711b1 100644 --- a/applyconfigurations/core/v1/podcondition.go +++ b/applyconfigurations/core/v1/podcondition.go @@ -27,6 +27,7 @@ import ( // with apply. type PodConditionApplyConfiguration struct { Type *corev1.PodConditionType `json:"type,omitempty"` + ObservedGeneration *int64 `json:"observedGeneration,omitempty"` Status *corev1.ConditionStatus `json:"status,omitempty"` LastProbeTime *metav1.Time `json:"lastProbeTime,omitempty"` LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` @@ -48,6 +49,14 @@ func (b *PodConditionApplyConfiguration) WithType(value corev1.PodConditionType) return b } +// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ObservedGeneration field is set to the value of the last call. +func (b *PodConditionApplyConfiguration) WithObservedGeneration(value int64) *PodConditionApplyConfiguration { + b.ObservedGeneration = &value + return b +} + // WithStatus sets the Status field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Status field is set to the value of the last call. diff --git a/applyconfigurations/core/v1/podstatus.go b/applyconfigurations/core/v1/podstatus.go index b79e1210a9..28ad57bac5 100644 --- a/applyconfigurations/core/v1/podstatus.go +++ b/applyconfigurations/core/v1/podstatus.go @@ -26,6 +26,7 @@ import ( // PodStatusApplyConfiguration represents a declarative configuration of the PodStatus type for use // with apply. type PodStatusApplyConfiguration struct { + ObservedGeneration *int64 `json:"observedGeneration,omitempty"` Phase *corev1.PodPhase `json:"phase,omitempty"` Conditions []PodConditionApplyConfiguration `json:"conditions,omitempty"` Message *string `json:"message,omitempty"` @@ -50,6 +51,14 @@ func PodStatus() *PodStatusApplyConfiguration { return &PodStatusApplyConfiguration{} } +// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ObservedGeneration field is set to the value of the last call. +func (b *PodStatusApplyConfiguration) WithObservedGeneration(value int64) *PodStatusApplyConfiguration { + b.ObservedGeneration = &value + return b +} + // WithPhase sets the Phase field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Phase field is set to the value of the last call. diff --git a/applyconfigurations/discovery/v1/endpointhints.go b/applyconfigurations/discovery/v1/endpointhints.go index d2d0f67769..7afda39b6b 100644 --- a/applyconfigurations/discovery/v1/endpointhints.go +++ b/applyconfigurations/discovery/v1/endpointhints.go @@ -22,6 +22,7 @@ package v1 // with apply. type EndpointHintsApplyConfiguration struct { ForZones []ForZoneApplyConfiguration `json:"forZones,omitempty"` + ForNodes []ForNodeApplyConfiguration `json:"forNodes,omitempty"` } // EndpointHintsApplyConfiguration constructs a declarative configuration of the EndpointHints type for use with @@ -42,3 +43,16 @@ func (b *EndpointHintsApplyConfiguration) WithForZones(values ...*ForZoneApplyCo } return b } + +// WithForNodes adds the given value to the ForNodes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ForNodes field. +func (b *EndpointHintsApplyConfiguration) WithForNodes(values ...*ForNodeApplyConfiguration) *EndpointHintsApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithForNodes") + } + b.ForNodes = append(b.ForNodes, *values[i]) + } + return b +} diff --git a/applyconfigurations/discovery/v1/fornode.go b/applyconfigurations/discovery/v1/fornode.go new file mode 100644 index 0000000000..3b2304d307 --- /dev/null +++ b/applyconfigurations/discovery/v1/fornode.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// ForNodeApplyConfiguration represents a declarative configuration of the ForNode type for use +// with apply. +type ForNodeApplyConfiguration struct { + Name *string `json:"name,omitempty"` +} + +// ForNodeApplyConfiguration constructs a declarative configuration of the ForNode type for use with +// apply. +func ForNode() *ForNodeApplyConfiguration { + return &ForNodeApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ForNodeApplyConfiguration) WithName(value string) *ForNodeApplyConfiguration { + b.Name = &value + return b +} diff --git a/applyconfigurations/discovery/v1beta1/endpointhints.go b/applyconfigurations/discovery/v1beta1/endpointhints.go index 99f69027a8..9637f9940f 100644 --- a/applyconfigurations/discovery/v1beta1/endpointhints.go +++ b/applyconfigurations/discovery/v1beta1/endpointhints.go @@ -22,6 +22,7 @@ package v1beta1 // with apply. type EndpointHintsApplyConfiguration struct { ForZones []ForZoneApplyConfiguration `json:"forZones,omitempty"` + ForNodes []ForNodeApplyConfiguration `json:"forNodes,omitempty"` } // EndpointHintsApplyConfiguration constructs a declarative configuration of the EndpointHints type for use with @@ -42,3 +43,16 @@ func (b *EndpointHintsApplyConfiguration) WithForZones(values ...*ForZoneApplyCo } return b } + +// WithForNodes adds the given value to the ForNodes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ForNodes field. +func (b *EndpointHintsApplyConfiguration) WithForNodes(values ...*ForNodeApplyConfiguration) *EndpointHintsApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithForNodes") + } + b.ForNodes = append(b.ForNodes, *values[i]) + } + return b +} diff --git a/applyconfigurations/discovery/v1beta1/fornode.go b/applyconfigurations/discovery/v1beta1/fornode.go new file mode 100644 index 0000000000..79aff881d2 --- /dev/null +++ b/applyconfigurations/discovery/v1beta1/fornode.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// ForNodeApplyConfiguration represents a declarative configuration of the ForNode type for use +// with apply. +type ForNodeApplyConfiguration struct { + Name *string `json:"name,omitempty"` +} + +// ForNodeApplyConfiguration constructs a declarative configuration of the ForNode type for use with +// apply. +func ForNode() *ForNodeApplyConfiguration { + return &ForNodeApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ForNodeApplyConfiguration) WithName(value string) *ForNodeApplyConfiguration { + b.Name = &value + return b +} diff --git a/applyconfigurations/doc.go b/applyconfigurations/doc.go index ac426c6075..8efc9523ed 100644 --- a/applyconfigurations/doc.go +++ b/applyconfigurations/doc.go @@ -148,4 +148,4 @@ reconciliation code that performs a "read/modify-in-place/update" (or patch) wor // apply applied, err := deploymentClient.Apply(ctx, extractedDeployment, metav1.ApplyOptions{FieldManager: fieldMgr}) */ -package applyconfigurations // import "k8s.io/client-go/applyconfigurations" +package applyconfigurations diff --git a/applyconfigurations/extensions/v1beta1/deploymentstatus.go b/applyconfigurations/extensions/v1beta1/deploymentstatus.go index adc023a34d..36b4fd42b6 100644 --- a/applyconfigurations/extensions/v1beta1/deploymentstatus.go +++ b/applyconfigurations/extensions/v1beta1/deploymentstatus.go @@ -27,6 +27,7 @@ type DeploymentStatusApplyConfiguration struct { ReadyReplicas *int32 `json:"readyReplicas,omitempty"` AvailableReplicas *int32 `json:"availableReplicas,omitempty"` UnavailableReplicas *int32 `json:"unavailableReplicas,omitempty"` + TerminatingReplicas *int32 `json:"terminatingReplicas,omitempty"` Conditions []DeploymentConditionApplyConfiguration `json:"conditions,omitempty"` CollisionCount *int32 `json:"collisionCount,omitempty"` } @@ -85,6 +86,14 @@ func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32 return b } +// WithTerminatingReplicas sets the TerminatingReplicas field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TerminatingReplicas field is set to the value of the last call. +func (b *DeploymentStatusApplyConfiguration) WithTerminatingReplicas(value int32) *DeploymentStatusApplyConfiguration { + b.TerminatingReplicas = &value + return b +} + // WithConditions adds the given value to the Conditions field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the Conditions field. diff --git a/applyconfigurations/extensions/v1beta1/replicasetstatus.go b/applyconfigurations/extensions/v1beta1/replicasetstatus.go index 9a5b468a3f..46abc94322 100644 --- a/applyconfigurations/extensions/v1beta1/replicasetstatus.go +++ b/applyconfigurations/extensions/v1beta1/replicasetstatus.go @@ -25,6 +25,7 @@ type ReplicaSetStatusApplyConfiguration struct { FullyLabeledReplicas *int32 `json:"fullyLabeledReplicas,omitempty"` ReadyReplicas *int32 `json:"readyReplicas,omitempty"` AvailableReplicas *int32 `json:"availableReplicas,omitempty"` + TerminatingReplicas *int32 `json:"terminatingReplicas,omitempty"` ObservedGeneration *int64 `json:"observedGeneration,omitempty"` Conditions []ReplicaSetConditionApplyConfiguration `json:"conditions,omitempty"` } @@ -67,6 +68,14 @@ func (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) return b } +// WithTerminatingReplicas sets the TerminatingReplicas field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TerminatingReplicas field is set to the value of the last call. +func (b *ReplicaSetStatusApplyConfiguration) WithTerminatingReplicas(value int32) *ReplicaSetStatusApplyConfiguration { + b.TerminatingReplicas = &value + return b +} + // WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ObservedGeneration field is set to the value of the last call. diff --git a/applyconfigurations/internal/internal.go b/applyconfigurations/internal/internal.go index cd9fcd98b7..41332b742f 100644 --- a/applyconfigurations/internal/internal.go +++ b/applyconfigurations/internal/internal.go @@ -1662,6 +1662,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: replicas type: scalar: numeric + - name: terminatingReplicas + type: + scalar: numeric - name: unavailableReplicas type: scalar: numeric @@ -1761,6 +1764,9 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: numeric default: 0 + - name: terminatingReplicas + type: + scalar: numeric - name: io.k8s.api.apps.v1.RollingUpdateDaemonSet map: fields: @@ -2058,6 +2064,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: replicas type: scalar: numeric + - name: terminatingReplicas + type: + scalar: numeric - name: unavailableReplicas type: scalar: numeric @@ -2476,6 +2485,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: replicas type: scalar: numeric + - name: terminatingReplicas + type: + scalar: numeric - name: unavailableReplicas type: scalar: numeric @@ -2575,6 +2587,9 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: numeric default: 0 + - name: terminatingReplicas + type: + scalar: numeric - name: io.k8s.api.apps.v1beta2.RollingUpdateDaemonSet map: fields: @@ -2919,6 +2934,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: stabilizationWindowSeconds type: scalar: numeric + - name: tolerance + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity - name: io.k8s.api.autoscaling.v2.HorizontalPodAutoscaler map: fields: @@ -4430,6 +4448,33 @@ var schemaYAML = typed.YAMLObject(`types: elementRelationship: associative keys: - type +- name: io.k8s.api.certificates.v1beta1.ClusterTrustBundle + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.certificates.v1beta1.ClusterTrustBundleSpec + default: {} +- name: io.k8s.api.certificates.v1beta1.ClusterTrustBundleSpec + map: + fields: + - name: signerName + type: + scalar: string + - name: trustBundle + type: + scalar: string + default: "" - name: io.k8s.api.coordination.v1.Lease map: fields: @@ -4528,6 +4573,46 @@ var schemaYAML = typed.YAMLObject(`types: type: namedType: io.k8s.api.coordination.v1beta1.LeaseSpec default: {} +- name: io.k8s.api.coordination.v1beta1.LeaseCandidate + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.coordination.v1beta1.LeaseCandidateSpec + default: {} +- name: io.k8s.api.coordination.v1beta1.LeaseCandidateSpec + map: + fields: + - name: binaryVersion + type: + scalar: string + default: "" + - name: emulationVersion + type: + scalar: string + - name: leaseName + type: + scalar: string + default: "" + - name: pingTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.MicroTime + - name: renewTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.MicroTime + - name: strategy + type: + scalar: string - name: io.k8s.api.coordination.v1beta1.LeaseSpec map: fields: @@ -5245,6 +5330,9 @@ var schemaYAML = typed.YAMLObject(`types: type: namedType: io.k8s.api.core.v1.ContainerState default: {} + - name: stopSignal + type: + scalar: string - name: user type: namedType: io.k8s.api.core.v1.ContainerUser @@ -5960,6 +6048,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: preStop type: namedType: io.k8s.api.core.v1.LifecycleHandler + - name: stopSignal + type: + scalar: string - name: io.k8s.api.core.v1.LifecycleHandler map: fields: @@ -6446,6 +6537,12 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic +- name: io.k8s.api.core.v1.NodeSwapStatus + map: + fields: + - name: capacity + type: + scalar: numeric - name: io.k8s.api.core.v1.NodeSystemInfo map: fields: @@ -6485,6 +6582,9 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" + - name: swap + type: + namedType: io.k8s.api.core.v1.NodeSwapStatus - name: systemUUID type: scalar: string @@ -6911,6 +7011,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: message type: scalar: string + - name: observedGeneration + type: + scalar: numeric - name: reason type: scalar: string @@ -7275,6 +7378,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: nominatedNodeName type: scalar: string + - name: observedGeneration + type: + scalar: numeric - name: phase type: scalar: string @@ -7558,9 +7664,11 @@ var schemaYAML = typed.YAMLObject(`types: - name: minReadySeconds type: scalar: numeric + default: 0 - name: replicas type: scalar: numeric + default: 1 - name: selector type: map: @@ -8642,6 +8750,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.discovery.v1.EndpointHints map: fields: + - name: forNodes + type: + list: + elementType: + namedType: io.k8s.api.discovery.v1.ForNode + elementRelationship: atomic - name: forZones type: list: @@ -8693,6 +8807,13 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.discovery.v1.EndpointPort elementRelationship: atomic +- name: io.k8s.api.discovery.v1.ForNode + map: + fields: + - name: name + type: + scalar: string + default: "" - name: io.k8s.api.discovery.v1.ForZone map: fields: @@ -8745,6 +8866,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.discovery.v1beta1.EndpointHints map: fields: + - name: forNodes + type: + list: + elementType: + namedType: io.k8s.api.discovery.v1beta1.ForNode + elementRelationship: atomic - name: forZones type: list: @@ -8795,6 +8922,13 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.discovery.v1beta1.EndpointPort elementRelationship: atomic +- name: io.k8s.api.discovery.v1beta1.ForNode + map: + fields: + - name: name + type: + scalar: string + default: "" - name: io.k8s.api.discovery.v1beta1.ForZone map: fields: @@ -9153,6 +9287,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: replicas type: scalar: numeric + - name: terminatingReplicas + type: + scalar: numeric - name: unavailableReplicas type: scalar: numeric @@ -9503,6 +9640,9 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: numeric default: 0 + - name: terminatingReplicas + type: + scalar: numeric - name: io.k8s.api.extensions.v1beta1.RollbackConfig map: fields: @@ -10911,6 +11051,29 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.networking.v1.HTTPIngressPath elementRelationship: atomic +- name: io.k8s.api.networking.v1.IPAddress + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.networking.v1.IPAddressSpec + default: {} +- name: io.k8s.api.networking.v1.IPAddressSpec + map: + fields: + - name: parentRef + type: + namedType: io.k8s.api.networking.v1.ParentReference - name: io.k8s.api.networking.v1.IPBlock map: fields: @@ -11194,6 +11357,21 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic +- name: io.k8s.api.networking.v1.ParentReference + map: + fields: + - name: group + type: + scalar: string + - name: name + type: + scalar: string + - name: namespace + type: + scalar: string + - name: resource + type: + scalar: string - name: io.k8s.api.networking.v1.ServiceBackendPort map: fields: @@ -11204,6 +11382,47 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: numeric elementRelationship: atomic +- name: io.k8s.api.networking.v1.ServiceCIDR + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.networking.v1.ServiceCIDRSpec + default: {} + - name: status + type: + namedType: io.k8s.api.networking.v1.ServiceCIDRStatus + default: {} +- name: io.k8s.api.networking.v1.ServiceCIDRSpec + map: + fields: + - name: cidrs + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.api.networking.v1.ServiceCIDRStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type - name: io.k8s.api.networking.v1alpha1.IPAddress map: fields: @@ -12396,6 +12615,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.resource.v1alpha3.BasicDevice map: fields: + - name: allNodes + type: + scalar: boolean - name: attributes type: map: @@ -12406,6 +12628,24 @@ var schemaYAML = typed.YAMLObject(`types: map: elementType: namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: consumesCounters + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.DeviceCounterConsumption + elementRelationship: atomic + - name: nodeName + type: + scalar: string + - name: nodeSelector + type: + namedType: io.k8s.api.core.v1.NodeSelector + - name: taints + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.DeviceTaint + elementRelationship: atomic - name: io.k8s.api.resource.v1alpha3.CELDeviceSelector map: fields: @@ -12413,6 +12653,24 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" +- name: io.k8s.api.resource.v1alpha3.Counter + map: + fields: + - name: value + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1alpha3.CounterSet + map: + fields: + - name: counters + type: + map: + elementType: + namedType: io.k8s.api.resource.v1alpha3.Counter + - name: name + type: + scalar: string + default: "" - name: io.k8s.api.resource.v1alpha3.Device map: fields: @@ -12552,6 +12810,18 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic +- name: io.k8s.api.resource.v1alpha3.DeviceCounterConsumption + map: + fields: + - name: counterSet + type: + scalar: string + default: "" + - name: counters + type: + map: + elementType: + namedType: io.k8s.api.resource.v1alpha3.Counter - name: io.k8s.api.resource.v1alpha3.DeviceRequest map: fields: @@ -12568,6 +12838,12 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" + - name: firstAvailable + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.DeviceSubRequest + elementRelationship: atomic - name: name type: scalar: string @@ -12578,6 +12854,12 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.resource.v1alpha3.DeviceSelector elementRelationship: atomic + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.DeviceToleration + elementRelationship: atomic - name: io.k8s.api.resource.v1alpha3.DeviceRequestAllocationResult map: fields: @@ -12600,29 +12882,148 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.DeviceToleration + elementRelationship: atomic - name: io.k8s.api.resource.v1alpha3.DeviceSelector map: fields: - name: cel type: namedType: io.k8s.api.resource.v1alpha3.CELDeviceSelector -- name: io.k8s.api.resource.v1alpha3.NetworkDeviceData +- name: io.k8s.api.resource.v1alpha3.DeviceSubRequest map: fields: - - name: hardwareAddress + - name: allocationMode type: scalar: string - - name: interfaceName + - name: count + type: + scalar: numeric + - name: deviceClassName type: scalar: string - - name: ips + default: "" + - name: name + type: + scalar: string + default: "" + - name: selectors type: list: elementType: - scalar: string + namedType: io.k8s.api.resource.v1alpha3.DeviceSelector elementRelationship: atomic -- name: io.k8s.api.resource.v1alpha3.OpaqueDeviceConfiguration - map: + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.DeviceToleration + elementRelationship: atomic +- name: io.k8s.api.resource.v1alpha3.DeviceTaint + map: + fields: + - name: effect + type: + scalar: string + default: "" + - name: key + type: + scalar: string + default: "" + - name: timeAdded + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: value + type: + scalar: string +- name: io.k8s.api.resource.v1alpha3.DeviceTaintRule + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.resource.v1alpha3.DeviceTaintRuleSpec + default: {} +- name: io.k8s.api.resource.v1alpha3.DeviceTaintRuleSpec + map: + fields: + - name: deviceSelector + type: + namedType: io.k8s.api.resource.v1alpha3.DeviceTaintSelector + - name: taint + type: + namedType: io.k8s.api.resource.v1alpha3.DeviceTaint + default: {} +- name: io.k8s.api.resource.v1alpha3.DeviceTaintSelector + map: + fields: + - name: device + type: + scalar: string + - name: deviceClassName + type: + scalar: string + - name: driver + type: + scalar: string + - name: pool + type: + scalar: string + - name: selectors + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.DeviceSelector + elementRelationship: atomic +- name: io.k8s.api.resource.v1alpha3.DeviceToleration + map: + fields: + - name: effect + type: + scalar: string + - name: key + type: + scalar: string + - name: operator + type: + scalar: string + default: Equal + - name: tolerationSeconds + type: + scalar: numeric + - name: value + type: + scalar: string +- name: io.k8s.api.resource.v1alpha3.NetworkDeviceData + map: + fields: + - name: hardwareAddress + type: + scalar: string + - name: interfaceName + type: + scalar: string + - name: ips + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.api.resource.v1alpha3.OpaqueDeviceConfiguration + map: fields: - name: driver type: @@ -12677,17 +13078,599 @@ var schemaYAML = typed.YAMLObject(`types: type: namedType: io.k8s.api.resource.v1alpha3.DeviceClaim default: {} -- name: io.k8s.api.resource.v1alpha3.ResourceClaimStatus +- name: io.k8s.api.resource.v1alpha3.ResourceClaimStatus + map: + fields: + - name: allocation + type: + namedType: io.k8s.api.resource.v1alpha3.AllocationResult + - name: devices + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.AllocatedDeviceStatus + elementRelationship: associative + keys: + - driver + - device + - pool + - name: reservedFor + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.ResourceClaimConsumerReference + elementRelationship: associative + keys: + - uid +- name: io.k8s.api.resource.v1alpha3.ResourceClaimTemplate + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.resource.v1alpha3.ResourceClaimTemplateSpec + default: {} +- name: io.k8s.api.resource.v1alpha3.ResourceClaimTemplateSpec + map: + fields: + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.resource.v1alpha3.ResourceClaimSpec + default: {} +- name: io.k8s.api.resource.v1alpha3.ResourcePool + map: + fields: + - name: generation + type: + scalar: numeric + default: 0 + - name: name + type: + scalar: string + default: "" + - name: resourceSliceCount + type: + scalar: numeric + default: 0 +- name: io.k8s.api.resource.v1alpha3.ResourceSlice + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.resource.v1alpha3.ResourceSliceSpec + default: {} +- name: io.k8s.api.resource.v1alpha3.ResourceSliceSpec + map: + fields: + - name: allNodes + type: + scalar: boolean + - name: devices + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.Device + elementRelationship: atomic + - name: driver + type: + scalar: string + default: "" + - name: nodeName + type: + scalar: string + - name: nodeSelector + type: + namedType: io.k8s.api.core.v1.NodeSelector + - name: perDeviceNodeSelection + type: + scalar: boolean + - name: pool + type: + namedType: io.k8s.api.resource.v1alpha3.ResourcePool + default: {} + - name: sharedCounters + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.CounterSet + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.AllocatedDeviceStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type + - name: data + type: + namedType: __untyped_atomic_ + - name: device + type: + scalar: string + default: "" + - name: driver + type: + scalar: string + default: "" + - name: networkData + type: + namedType: io.k8s.api.resource.v1beta1.NetworkDeviceData + - name: pool + type: + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta1.AllocationResult + map: + fields: + - name: devices + type: + namedType: io.k8s.api.resource.v1beta1.DeviceAllocationResult + default: {} + - name: nodeSelector + type: + namedType: io.k8s.api.core.v1.NodeSelector +- name: io.k8s.api.resource.v1beta1.BasicDevice + map: + fields: + - name: allNodes + type: + scalar: boolean + - name: attributes + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceAttribute + - name: capacity + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceCapacity + - name: consumesCounters + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceCounterConsumption + elementRelationship: atomic + - name: nodeName + type: + scalar: string + - name: nodeSelector + type: + namedType: io.k8s.api.core.v1.NodeSelector + - name: taints + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceTaint + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.CELDeviceSelector + map: + fields: + - name: expression + type: + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta1.Counter + map: + fields: + - name: value + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1beta1.CounterSet + map: + fields: + - name: counters + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta1.Counter + - name: name + type: + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta1.Device + map: + fields: + - name: basic + type: + namedType: io.k8s.api.resource.v1beta1.BasicDevice + - name: name + type: + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta1.DeviceAllocationConfiguration + map: + fields: + - name: opaque + type: + namedType: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration + - name: requests + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: source + type: + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta1.DeviceAllocationResult + map: + fields: + - name: config + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceAllocationConfiguration + elementRelationship: atomic + - name: results + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceRequestAllocationResult + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceAttribute + map: + fields: + - name: bool + type: + scalar: boolean + - name: int + type: + scalar: numeric + - name: string + type: + scalar: string + - name: version + type: + scalar: string +- name: io.k8s.api.resource.v1beta1.DeviceCapacity + map: + fields: + - name: value + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1beta1.DeviceClaim + map: + fields: + - name: config + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceClaimConfiguration + elementRelationship: atomic + - name: constraints + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceConstraint + elementRelationship: atomic + - name: requests + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceRequest + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceClaimConfiguration + map: + fields: + - name: opaque + type: + namedType: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration + - name: requests + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceClass + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.resource.v1beta1.DeviceClassSpec + default: {} +- name: io.k8s.api.resource.v1beta1.DeviceClassConfiguration + map: + fields: + - name: opaque + type: + namedType: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration +- name: io.k8s.api.resource.v1beta1.DeviceClassSpec + map: + fields: + - name: config + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceClassConfiguration + elementRelationship: atomic + - name: selectors + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceSelector + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceConstraint + map: + fields: + - name: matchAttribute + type: + scalar: string + - name: requests + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceCounterConsumption + map: + fields: + - name: counterSet + type: + scalar: string + default: "" + - name: counters + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta1.Counter +- name: io.k8s.api.resource.v1beta1.DeviceRequest + map: + fields: + - name: adminAccess + type: + scalar: boolean + - name: allocationMode + type: + scalar: string + - name: count + type: + scalar: numeric + - name: deviceClassName + type: + scalar: string + default: "" + - name: firstAvailable + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceSubRequest + elementRelationship: atomic + - name: name + type: + scalar: string + default: "" + - name: selectors + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceSelector + elementRelationship: atomic + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceToleration + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceRequestAllocationResult + map: + fields: + - name: adminAccess + type: + scalar: boolean + - name: device + type: + scalar: string + default: "" + - name: driver + type: + scalar: string + default: "" + - name: pool + type: + scalar: string + default: "" + - name: request + type: + scalar: string + default: "" + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceToleration + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceSelector + map: + fields: + - name: cel + type: + namedType: io.k8s.api.resource.v1beta1.CELDeviceSelector +- name: io.k8s.api.resource.v1beta1.DeviceSubRequest + map: + fields: + - name: allocationMode + type: + scalar: string + - name: count + type: + scalar: numeric + - name: deviceClassName + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" + - name: selectors + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceSelector + elementRelationship: atomic + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceToleration + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.DeviceTaint + map: + fields: + - name: effect + type: + scalar: string + default: "" + - name: key + type: + scalar: string + default: "" + - name: timeAdded + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: value + type: + scalar: string +- name: io.k8s.api.resource.v1beta1.DeviceToleration + map: + fields: + - name: effect + type: + scalar: string + - name: key + type: + scalar: string + - name: operator + type: + scalar: string + default: Equal + - name: tolerationSeconds + type: + scalar: numeric + - name: value + type: + scalar: string +- name: io.k8s.api.resource.v1beta1.NetworkDeviceData + map: + fields: + - name: hardwareAddress + type: + scalar: string + - name: interfaceName + type: + scalar: string + - name: ips + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration + map: + fields: + - name: driver + type: + scalar: string + default: "" + - name: parameters + type: + namedType: __untyped_atomic_ +- name: io.k8s.api.resource.v1beta1.ResourceClaim + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.resource.v1beta1.ResourceClaimSpec + default: {} + - name: status + type: + namedType: io.k8s.api.resource.v1beta1.ResourceClaimStatus + default: {} +- name: io.k8s.api.resource.v1beta1.ResourceClaimConsumerReference + map: + fields: + - name: apiGroup + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: resource + type: + scalar: string + default: "" + - name: uid + type: + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta1.ResourceClaimSpec + map: + fields: + - name: devices + type: + namedType: io.k8s.api.resource.v1beta1.DeviceClaim + default: {} +- name: io.k8s.api.resource.v1beta1.ResourceClaimStatus map: fields: - name: allocation type: - namedType: io.k8s.api.resource.v1alpha3.AllocationResult + namedType: io.k8s.api.resource.v1beta1.AllocationResult - name: devices type: list: elementType: - namedType: io.k8s.api.resource.v1alpha3.AllocatedDeviceStatus + namedType: io.k8s.api.resource.v1beta1.AllocatedDeviceStatus elementRelationship: associative keys: - driver @@ -12697,11 +13680,11 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.resource.v1alpha3.ResourceClaimConsumerReference + namedType: io.k8s.api.resource.v1beta1.ResourceClaimConsumerReference elementRelationship: associative keys: - uid -- name: io.k8s.api.resource.v1alpha3.ResourceClaimTemplate +- name: io.k8s.api.resource.v1beta1.ResourceClaimTemplate map: fields: - name: apiVersion @@ -12716,9 +13699,9 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1alpha3.ResourceClaimTemplateSpec + namedType: io.k8s.api.resource.v1beta1.ResourceClaimTemplateSpec default: {} -- name: io.k8s.api.resource.v1alpha3.ResourceClaimTemplateSpec +- name: io.k8s.api.resource.v1beta1.ResourceClaimTemplateSpec map: fields: - name: metadata @@ -12727,9 +13710,9 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1alpha3.ResourceClaimSpec + namedType: io.k8s.api.resource.v1beta1.ResourceClaimSpec default: {} -- name: io.k8s.api.resource.v1alpha3.ResourcePool +- name: io.k8s.api.resource.v1beta1.ResourcePool map: fields: - name: generation @@ -12744,7 +13727,7 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: numeric default: 0 -- name: io.k8s.api.resource.v1alpha3.ResourceSlice +- name: io.k8s.api.resource.v1beta1.ResourceSlice map: fields: - name: apiVersion @@ -12759,9 +13742,9 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1alpha3.ResourceSliceSpec + namedType: io.k8s.api.resource.v1beta1.ResourceSliceSpec default: {} -- name: io.k8s.api.resource.v1alpha3.ResourceSliceSpec +- name: io.k8s.api.resource.v1beta1.ResourceSliceSpec map: fields: - name: allNodes @@ -12771,7 +13754,7 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.resource.v1alpha3.Device + namedType: io.k8s.api.resource.v1beta1.Device elementRelationship: atomic - name: driver type: @@ -12783,11 +13766,20 @@ var schemaYAML = typed.YAMLObject(`types: - name: nodeSelector type: namedType: io.k8s.api.core.v1.NodeSelector + - name: perDeviceNodeSelection + type: + scalar: boolean - name: pool type: - namedType: io.k8s.api.resource.v1alpha3.ResourcePool + namedType: io.k8s.api.resource.v1beta1.ResourcePool default: {} -- name: io.k8s.api.resource.v1beta1.AllocatedDeviceStatus + - name: sharedCounters + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.CounterSet + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta2.AllocatedDeviceStatus map: fields: - name: conditions @@ -12811,57 +13803,90 @@ var schemaYAML = typed.YAMLObject(`types: default: "" - name: networkData type: - namedType: io.k8s.api.resource.v1beta1.NetworkDeviceData + namedType: io.k8s.api.resource.v1beta2.NetworkDeviceData - name: pool type: scalar: string default: "" -- name: io.k8s.api.resource.v1beta1.AllocationResult +- name: io.k8s.api.resource.v1beta2.AllocationResult map: fields: - name: devices type: - namedType: io.k8s.api.resource.v1beta1.DeviceAllocationResult + namedType: io.k8s.api.resource.v1beta2.DeviceAllocationResult default: {} - name: nodeSelector type: namedType: io.k8s.api.core.v1.NodeSelector -- name: io.k8s.api.resource.v1beta1.BasicDevice +- name: io.k8s.api.resource.v1beta2.CELDeviceSelector map: fields: - - name: attributes + - name: expression type: - map: - elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceAttribute - - name: capacity + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta2.Counter + map: + fields: + - name: value type: - map: - elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceCapacity -- name: io.k8s.api.resource.v1beta1.CELDeviceSelector + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1beta2.CounterSet map: fields: - - name: expression + - name: counters + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta2.Counter + - name: name type: scalar: string default: "" -- name: io.k8s.api.resource.v1beta1.Device +- name: io.k8s.api.resource.v1beta2.Device map: fields: - - name: basic + - name: allNodes type: - namedType: io.k8s.api.resource.v1beta1.BasicDevice + scalar: boolean + - name: attributes + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceAttribute + - name: capacity + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceCapacity + - name: consumesCounters + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceCounterConsumption + elementRelationship: atomic - name: name type: scalar: string default: "" -- name: io.k8s.api.resource.v1beta1.DeviceAllocationConfiguration + - name: nodeName + type: + scalar: string + - name: nodeSelector + type: + namedType: io.k8s.api.core.v1.NodeSelector + - name: taints + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceTaint + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta2.DeviceAllocationConfiguration map: fields: - name: opaque type: - namedType: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration + namedType: io.k8s.api.resource.v1beta2.OpaqueDeviceConfiguration - name: requests type: list: @@ -12872,22 +13897,22 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" -- name: io.k8s.api.resource.v1beta1.DeviceAllocationResult +- name: io.k8s.api.resource.v1beta2.DeviceAllocationResult map: fields: - name: config type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceAllocationConfiguration + namedType: io.k8s.api.resource.v1beta2.DeviceAllocationConfiguration elementRelationship: atomic - name: results type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceRequestAllocationResult + namedType: io.k8s.api.resource.v1beta2.DeviceRequestAllocationResult elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.DeviceAttribute +- name: io.k8s.api.resource.v1beta2.DeviceAttribute map: fields: - name: bool @@ -12902,46 +13927,46 @@ var schemaYAML = typed.YAMLObject(`types: - name: version type: scalar: string -- name: io.k8s.api.resource.v1beta1.DeviceCapacity +- name: io.k8s.api.resource.v1beta2.DeviceCapacity map: fields: - name: value type: namedType: io.k8s.apimachinery.pkg.api.resource.Quantity -- name: io.k8s.api.resource.v1beta1.DeviceClaim +- name: io.k8s.api.resource.v1beta2.DeviceClaim map: fields: - name: config type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceClaimConfiguration + namedType: io.k8s.api.resource.v1beta2.DeviceClaimConfiguration elementRelationship: atomic - name: constraints type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceConstraint + namedType: io.k8s.api.resource.v1beta2.DeviceConstraint elementRelationship: atomic - name: requests type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceRequest + namedType: io.k8s.api.resource.v1beta2.DeviceRequest elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.DeviceClaimConfiguration +- name: io.k8s.api.resource.v1beta2.DeviceClaimConfiguration map: fields: - name: opaque type: - namedType: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration + namedType: io.k8s.api.resource.v1beta2.OpaqueDeviceConfiguration - name: requests type: list: elementType: scalar: string elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.DeviceClass +- name: io.k8s.api.resource.v1beta2.DeviceClass map: fields: - name: apiVersion @@ -12956,30 +13981,30 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1beta1.DeviceClassSpec + namedType: io.k8s.api.resource.v1beta2.DeviceClassSpec default: {} -- name: io.k8s.api.resource.v1beta1.DeviceClassConfiguration +- name: io.k8s.api.resource.v1beta2.DeviceClassConfiguration map: fields: - name: opaque type: - namedType: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration -- name: io.k8s.api.resource.v1beta1.DeviceClassSpec + namedType: io.k8s.api.resource.v1beta2.OpaqueDeviceConfiguration +- name: io.k8s.api.resource.v1beta2.DeviceClassSpec map: fields: - name: config type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceClassConfiguration + namedType: io.k8s.api.resource.v1beta2.DeviceClassConfiguration elementRelationship: atomic - name: selectors type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceSelector + namedType: io.k8s.api.resource.v1beta2.DeviceSelector elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.DeviceConstraint +- name: io.k8s.api.resource.v1beta2.DeviceConstraint map: fields: - name: matchAttribute @@ -12991,12 +14016,71 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.DeviceRequest +- name: io.k8s.api.resource.v1beta2.DeviceCounterConsumption + map: + fields: + - name: counterSet + type: + scalar: string + default: "" + - name: counters + type: + map: + elementType: + namedType: io.k8s.api.resource.v1beta2.Counter +- name: io.k8s.api.resource.v1beta2.DeviceRequest + map: + fields: + - name: exactly + type: + namedType: io.k8s.api.resource.v1beta2.ExactDeviceRequest + - name: firstAvailable + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceSubRequest + elementRelationship: atomic + - name: name + type: + scalar: string + default: "" +- name: io.k8s.api.resource.v1beta2.DeviceRequestAllocationResult map: fields: - name: adminAccess type: scalar: boolean + - name: device + type: + scalar: string + default: "" + - name: driver + type: + scalar: string + default: "" + - name: pool + type: + scalar: string + default: "" + - name: request + type: + scalar: string + default: "" + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceToleration + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta2.DeviceSelector + map: + fields: + - name: cel + type: + namedType: io.k8s.api.resource.v1beta2.CELDeviceSelector +- name: io.k8s.api.resource.v1beta2.DeviceSubRequest + map: + fields: - name: allocationMode type: scalar: string @@ -13015,37 +14099,79 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.DeviceSelector + namedType: io.k8s.api.resource.v1beta2.DeviceSelector elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.DeviceRequestAllocationResult + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceToleration + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta2.DeviceTaint map: fields: - - name: adminAccess - type: - scalar: boolean - - name: device + - name: effect type: scalar: string default: "" - - name: driver + - name: key type: scalar: string default: "" - - name: pool + - name: timeAdded + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: value type: scalar: string - default: "" - - name: request +- name: io.k8s.api.resource.v1beta2.DeviceToleration + map: + fields: + - name: effect type: scalar: string - default: "" -- name: io.k8s.api.resource.v1beta1.DeviceSelector + - name: key + type: + scalar: string + - name: operator + type: + scalar: string + default: Equal + - name: tolerationSeconds + type: + scalar: numeric + - name: value + type: + scalar: string +- name: io.k8s.api.resource.v1beta2.ExactDeviceRequest map: fields: - - name: cel + - name: adminAccess type: - namedType: io.k8s.api.resource.v1beta1.CELDeviceSelector -- name: io.k8s.api.resource.v1beta1.NetworkDeviceData + scalar: boolean + - name: allocationMode + type: + scalar: string + - name: count + type: + scalar: numeric + - name: deviceClassName + type: + scalar: string + default: "" + - name: selectors + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceSelector + elementRelationship: atomic + - name: tolerations + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceToleration + elementRelationship: atomic +- name: io.k8s.api.resource.v1beta2.NetworkDeviceData map: fields: - name: hardwareAddress @@ -13060,7 +14186,7 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration +- name: io.k8s.api.resource.v1beta2.OpaqueDeviceConfiguration map: fields: - name: driver @@ -13070,7 +14196,7 @@ var schemaYAML = typed.YAMLObject(`types: - name: parameters type: namedType: __untyped_atomic_ -- name: io.k8s.api.resource.v1beta1.ResourceClaim +- name: io.k8s.api.resource.v1beta2.ResourceClaim map: fields: - name: apiVersion @@ -13085,13 +14211,13 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1beta1.ResourceClaimSpec + namedType: io.k8s.api.resource.v1beta2.ResourceClaimSpec default: {} - name: status type: - namedType: io.k8s.api.resource.v1beta1.ResourceClaimStatus + namedType: io.k8s.api.resource.v1beta2.ResourceClaimStatus default: {} -- name: io.k8s.api.resource.v1beta1.ResourceClaimConsumerReference +- name: io.k8s.api.resource.v1beta2.ResourceClaimConsumerReference map: fields: - name: apiGroup @@ -13109,24 +14235,24 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" -- name: io.k8s.api.resource.v1beta1.ResourceClaimSpec +- name: io.k8s.api.resource.v1beta2.ResourceClaimSpec map: fields: - name: devices type: - namedType: io.k8s.api.resource.v1beta1.DeviceClaim + namedType: io.k8s.api.resource.v1beta2.DeviceClaim default: {} -- name: io.k8s.api.resource.v1beta1.ResourceClaimStatus +- name: io.k8s.api.resource.v1beta2.ResourceClaimStatus map: fields: - name: allocation type: - namedType: io.k8s.api.resource.v1beta1.AllocationResult + namedType: io.k8s.api.resource.v1beta2.AllocationResult - name: devices type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.AllocatedDeviceStatus + namedType: io.k8s.api.resource.v1beta2.AllocatedDeviceStatus elementRelationship: associative keys: - driver @@ -13136,11 +14262,11 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.ResourceClaimConsumerReference + namedType: io.k8s.api.resource.v1beta2.ResourceClaimConsumerReference elementRelationship: associative keys: - uid -- name: io.k8s.api.resource.v1beta1.ResourceClaimTemplate +- name: io.k8s.api.resource.v1beta2.ResourceClaimTemplate map: fields: - name: apiVersion @@ -13155,9 +14281,9 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1beta1.ResourceClaimTemplateSpec + namedType: io.k8s.api.resource.v1beta2.ResourceClaimTemplateSpec default: {} -- name: io.k8s.api.resource.v1beta1.ResourceClaimTemplateSpec +- name: io.k8s.api.resource.v1beta2.ResourceClaimTemplateSpec map: fields: - name: metadata @@ -13166,9 +14292,9 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1beta1.ResourceClaimSpec + namedType: io.k8s.api.resource.v1beta2.ResourceClaimSpec default: {} -- name: io.k8s.api.resource.v1beta1.ResourcePool +- name: io.k8s.api.resource.v1beta2.ResourcePool map: fields: - name: generation @@ -13183,7 +14309,7 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: numeric default: 0 -- name: io.k8s.api.resource.v1beta1.ResourceSlice +- name: io.k8s.api.resource.v1beta2.ResourceSlice map: fields: - name: apiVersion @@ -13198,9 +14324,9 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.resource.v1beta1.ResourceSliceSpec + namedType: io.k8s.api.resource.v1beta2.ResourceSliceSpec default: {} -- name: io.k8s.api.resource.v1beta1.ResourceSliceSpec +- name: io.k8s.api.resource.v1beta2.ResourceSliceSpec map: fields: - name: allNodes @@ -13210,7 +14336,7 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.resource.v1beta1.Device + namedType: io.k8s.api.resource.v1beta2.Device elementRelationship: atomic - name: driver type: @@ -13222,10 +14348,19 @@ var schemaYAML = typed.YAMLObject(`types: - name: nodeSelector type: namedType: io.k8s.api.core.v1.NodeSelector + - name: perDeviceNodeSelection + type: + scalar: boolean - name: pool type: - namedType: io.k8s.api.resource.v1beta1.ResourcePool + namedType: io.k8s.api.resource.v1beta2.ResourcePool default: {} + - name: sharedCounters + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.CounterSet + elementRelationship: atomic - name: io.k8s.api.scheduling.v1.PriorityClass map: fields: @@ -13330,6 +14465,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: fsGroupPolicy type: scalar: string + - name: nodeAllocatableUpdatePeriodSeconds + type: + scalar: numeric - name: podInfoOnMount type: scalar: boolean @@ -13547,6 +14685,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.storage.v1.VolumeError map: fields: + - name: errorCode + type: + scalar: numeric - name: message type: scalar: string @@ -13673,6 +14814,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.storage.v1alpha1.VolumeError map: fields: + - name: errorCode + type: + scalar: numeric - name: message type: scalar: string @@ -13705,6 +14849,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: fsGroupPolicy type: scalar: string + - name: nodeAllocatableUpdatePeriodSeconds + type: + scalar: numeric - name: podInfoOnMount type: scalar: boolean @@ -13944,6 +15091,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.storage.v1beta1.VolumeError map: fields: + - name: errorCode + type: + scalar: numeric - name: message type: scalar: string diff --git a/applyconfigurations/networking/v1/ipaddress.go b/applyconfigurations/networking/v1/ipaddress.go new file mode 100644 index 0000000000..f3098b96be --- /dev/null +++ b/applyconfigurations/networking/v1/ipaddress.go @@ -0,0 +1,253 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + networkingv1 "k8s.io/api/networking/v1" + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// IPAddressApplyConfiguration represents a declarative configuration of the IPAddress type for use +// with apply. +type IPAddressApplyConfiguration struct { + metav1.TypeMetaApplyConfiguration `json:",inline"` + *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *IPAddressSpecApplyConfiguration `json:"spec,omitempty"` +} + +// IPAddress constructs a declarative configuration of the IPAddress type for use with +// apply. +func IPAddress(name string) *IPAddressApplyConfiguration { + b := &IPAddressApplyConfiguration{} + b.WithName(name) + b.WithKind("IPAddress") + b.WithAPIVersion("networking.k8s.io/v1") + return b +} + +// ExtractIPAddress extracts the applied configuration owned by fieldManager from +// iPAddress. If no managedFields are found in iPAddress for fieldManager, a +// IPAddressApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// iPAddress must be a unmodified IPAddress API object that was retrieved from the Kubernetes API. +// ExtractIPAddress provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractIPAddress(iPAddress *networkingv1.IPAddress, fieldManager string) (*IPAddressApplyConfiguration, error) { + return extractIPAddress(iPAddress, fieldManager, "") +} + +// ExtractIPAddressStatus is the same as ExtractIPAddress except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractIPAddressStatus(iPAddress *networkingv1.IPAddress, fieldManager string) (*IPAddressApplyConfiguration, error) { + return extractIPAddress(iPAddress, fieldManager, "status") +} + +func extractIPAddress(iPAddress *networkingv1.IPAddress, fieldManager string, subresource string) (*IPAddressApplyConfiguration, error) { + b := &IPAddressApplyConfiguration{} + err := managedfields.ExtractInto(iPAddress, internal.Parser().Type("io.k8s.api.networking.v1.IPAddress"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(iPAddress.Name) + + b.WithKind("IPAddress") + b.WithAPIVersion("networking.k8s.io/v1") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithKind(value string) *IPAddressApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithAPIVersion(value string) *IPAddressApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithName(value string) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithGenerateName(value string) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithNamespace(value string) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithUID(value types.UID) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithResourceVersion(value string) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithGeneration(value int64) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithCreationTimestamp(value apismetav1.Time) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithDeletionTimestamp(value apismetav1.Time) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *IPAddressApplyConfiguration) WithLabels(entries map[string]string) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *IPAddressApplyConfiguration) WithAnnotations(entries map[string]string) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *IPAddressApplyConfiguration) WithOwnerReferences(values ...*metav1.OwnerReferenceApplyConfiguration) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *IPAddressApplyConfiguration) WithFinalizers(values ...string) *IPAddressApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *IPAddressApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &metav1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *IPAddressApplyConfiguration) WithSpec(value *IPAddressSpecApplyConfiguration) *IPAddressApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *IPAddressApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/networking/v1/ipaddressspec.go b/applyconfigurations/networking/v1/ipaddressspec.go new file mode 100644 index 0000000000..bac6e7912f --- /dev/null +++ b/applyconfigurations/networking/v1/ipaddressspec.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// IPAddressSpecApplyConfiguration represents a declarative configuration of the IPAddressSpec type for use +// with apply. +type IPAddressSpecApplyConfiguration struct { + ParentRef *ParentReferenceApplyConfiguration `json:"parentRef,omitempty"` +} + +// IPAddressSpecApplyConfiguration constructs a declarative configuration of the IPAddressSpec type for use with +// apply. +func IPAddressSpec() *IPAddressSpecApplyConfiguration { + return &IPAddressSpecApplyConfiguration{} +} + +// WithParentRef sets the ParentRef field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ParentRef field is set to the value of the last call. +func (b *IPAddressSpecApplyConfiguration) WithParentRef(value *ParentReferenceApplyConfiguration) *IPAddressSpecApplyConfiguration { + b.ParentRef = value + return b +} diff --git a/applyconfigurations/networking/v1/parentreference.go b/applyconfigurations/networking/v1/parentreference.go new file mode 100644 index 0000000000..896c0f8a6d --- /dev/null +++ b/applyconfigurations/networking/v1/parentreference.go @@ -0,0 +1,66 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// ParentReferenceApplyConfiguration represents a declarative configuration of the ParentReference type for use +// with apply. +type ParentReferenceApplyConfiguration struct { + Group *string `json:"group,omitempty"` + Resource *string `json:"resource,omitempty"` + Namespace *string `json:"namespace,omitempty"` + Name *string `json:"name,omitempty"` +} + +// ParentReferenceApplyConfiguration constructs a declarative configuration of the ParentReference type for use with +// apply. +func ParentReference() *ParentReferenceApplyConfiguration { + return &ParentReferenceApplyConfiguration{} +} + +// WithGroup sets the Group field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Group field is set to the value of the last call. +func (b *ParentReferenceApplyConfiguration) WithGroup(value string) *ParentReferenceApplyConfiguration { + b.Group = &value + return b +} + +// WithResource sets the Resource field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Resource field is set to the value of the last call. +func (b *ParentReferenceApplyConfiguration) WithResource(value string) *ParentReferenceApplyConfiguration { + b.Resource = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ParentReferenceApplyConfiguration) WithNamespace(value string) *ParentReferenceApplyConfiguration { + b.Namespace = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ParentReferenceApplyConfiguration) WithName(value string) *ParentReferenceApplyConfiguration { + b.Name = &value + return b +} diff --git a/applyconfigurations/networking/v1/servicecidr.go b/applyconfigurations/networking/v1/servicecidr.go new file mode 100644 index 0000000000..1590c1579c --- /dev/null +++ b/applyconfigurations/networking/v1/servicecidr.go @@ -0,0 +1,262 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + networkingv1 "k8s.io/api/networking/v1" + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ServiceCIDRApplyConfiguration represents a declarative configuration of the ServiceCIDR type for use +// with apply. +type ServiceCIDRApplyConfiguration struct { + metav1.TypeMetaApplyConfiguration `json:",inline"` + *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *ServiceCIDRSpecApplyConfiguration `json:"spec,omitempty"` + Status *ServiceCIDRStatusApplyConfiguration `json:"status,omitempty"` +} + +// ServiceCIDR constructs a declarative configuration of the ServiceCIDR type for use with +// apply. +func ServiceCIDR(name string) *ServiceCIDRApplyConfiguration { + b := &ServiceCIDRApplyConfiguration{} + b.WithName(name) + b.WithKind("ServiceCIDR") + b.WithAPIVersion("networking.k8s.io/v1") + return b +} + +// ExtractServiceCIDR extracts the applied configuration owned by fieldManager from +// serviceCIDR. If no managedFields are found in serviceCIDR for fieldManager, a +// ServiceCIDRApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// serviceCIDR must be a unmodified ServiceCIDR API object that was retrieved from the Kubernetes API. +// ExtractServiceCIDR provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractServiceCIDR(serviceCIDR *networkingv1.ServiceCIDR, fieldManager string) (*ServiceCIDRApplyConfiguration, error) { + return extractServiceCIDR(serviceCIDR, fieldManager, "") +} + +// ExtractServiceCIDRStatus is the same as ExtractServiceCIDR except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractServiceCIDRStatus(serviceCIDR *networkingv1.ServiceCIDR, fieldManager string) (*ServiceCIDRApplyConfiguration, error) { + return extractServiceCIDR(serviceCIDR, fieldManager, "status") +} + +func extractServiceCIDR(serviceCIDR *networkingv1.ServiceCIDR, fieldManager string, subresource string) (*ServiceCIDRApplyConfiguration, error) { + b := &ServiceCIDRApplyConfiguration{} + err := managedfields.ExtractInto(serviceCIDR, internal.Parser().Type("io.k8s.api.networking.v1.ServiceCIDR"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(serviceCIDR.Name) + + b.WithKind("ServiceCIDR") + b.WithAPIVersion("networking.k8s.io/v1") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithKind(value string) *ServiceCIDRApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithAPIVersion(value string) *ServiceCIDRApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithName(value string) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithGenerateName(value string) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithNamespace(value string) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithUID(value types.UID) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithResourceVersion(value string) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithGeneration(value int64) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithCreationTimestamp(value apismetav1.Time) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithDeletionTimestamp(value apismetav1.Time) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ServiceCIDRApplyConfiguration) WithLabels(entries map[string]string) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ServiceCIDRApplyConfiguration) WithAnnotations(entries map[string]string) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ServiceCIDRApplyConfiguration) WithOwnerReferences(values ...*metav1.OwnerReferenceApplyConfiguration) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ServiceCIDRApplyConfiguration) WithFinalizers(values ...string) *ServiceCIDRApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ServiceCIDRApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &metav1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithSpec(value *ServiceCIDRSpecApplyConfiguration) *ServiceCIDRApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *ServiceCIDRApplyConfiguration) WithStatus(value *ServiceCIDRStatusApplyConfiguration) *ServiceCIDRApplyConfiguration { + b.Status = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ServiceCIDRApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/networking/v1/servicecidrspec.go b/applyconfigurations/networking/v1/servicecidrspec.go new file mode 100644 index 0000000000..f84b7ba1e0 --- /dev/null +++ b/applyconfigurations/networking/v1/servicecidrspec.go @@ -0,0 +1,41 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// ServiceCIDRSpecApplyConfiguration represents a declarative configuration of the ServiceCIDRSpec type for use +// with apply. +type ServiceCIDRSpecApplyConfiguration struct { + CIDRs []string `json:"cidrs,omitempty"` +} + +// ServiceCIDRSpecApplyConfiguration constructs a declarative configuration of the ServiceCIDRSpec type for use with +// apply. +func ServiceCIDRSpec() *ServiceCIDRSpecApplyConfiguration { + return &ServiceCIDRSpecApplyConfiguration{} +} + +// WithCIDRs adds the given value to the CIDRs field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CIDRs field. +func (b *ServiceCIDRSpecApplyConfiguration) WithCIDRs(values ...string) *ServiceCIDRSpecApplyConfiguration { + for i := range values { + b.CIDRs = append(b.CIDRs, values[i]) + } + return b +} diff --git a/applyconfigurations/networking/v1/servicecidrstatus.go b/applyconfigurations/networking/v1/servicecidrstatus.go new file mode 100644 index 0000000000..9e3d52ae8b --- /dev/null +++ b/applyconfigurations/networking/v1/servicecidrstatus.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ServiceCIDRStatusApplyConfiguration represents a declarative configuration of the ServiceCIDRStatus type for use +// with apply. +type ServiceCIDRStatusApplyConfiguration struct { + Conditions []metav1.ConditionApplyConfiguration `json:"conditions,omitempty"` +} + +// ServiceCIDRStatusApplyConfiguration constructs a declarative configuration of the ServiceCIDRStatus type for use with +// apply. +func ServiceCIDRStatus() *ServiceCIDRStatusApplyConfiguration { + return &ServiceCIDRStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *ServiceCIDRStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *ServiceCIDRStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/basicdevice.go b/applyconfigurations/resource/v1alpha3/basicdevice.go index b58e432947..382ed2a22a 100644 --- a/applyconfigurations/resource/v1alpha3/basicdevice.go +++ b/applyconfigurations/resource/v1alpha3/basicdevice.go @@ -21,13 +21,19 @@ package v1alpha3 import ( resourcev1alpha3 "k8s.io/api/resource/v1alpha3" resource "k8s.io/apimachinery/pkg/api/resource" + v1 "k8s.io/client-go/applyconfigurations/core/v1" ) // BasicDeviceApplyConfiguration represents a declarative configuration of the BasicDevice type for use // with apply. type BasicDeviceApplyConfiguration struct { - Attributes map[resourcev1alpha3.QualifiedName]DeviceAttributeApplyConfiguration `json:"attributes,omitempty"` - Capacity map[resourcev1alpha3.QualifiedName]resource.Quantity `json:"capacity,omitempty"` + Attributes map[resourcev1alpha3.QualifiedName]DeviceAttributeApplyConfiguration `json:"attributes,omitempty"` + Capacity map[resourcev1alpha3.QualifiedName]resource.Quantity `json:"capacity,omitempty"` + ConsumesCounters []DeviceCounterConsumptionApplyConfiguration `json:"consumesCounters,omitempty"` + NodeName *string `json:"nodeName,omitempty"` + NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` + AllNodes *bool `json:"allNodes,omitempty"` + Taints []DeviceTaintApplyConfiguration `json:"taints,omitempty"` } // BasicDeviceApplyConfiguration constructs a declarative configuration of the BasicDevice type for use with @@ -63,3 +69,53 @@ func (b *BasicDeviceApplyConfiguration) WithCapacity(entries map[resourcev1alpha } return b } + +// WithConsumesCounters adds the given value to the ConsumesCounters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ConsumesCounters field. +func (b *BasicDeviceApplyConfiguration) WithConsumesCounters(values ...*DeviceCounterConsumptionApplyConfiguration) *BasicDeviceApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConsumesCounters") + } + b.ConsumesCounters = append(b.ConsumesCounters, *values[i]) + } + return b +} + +// WithNodeName sets the NodeName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeName field is set to the value of the last call. +func (b *BasicDeviceApplyConfiguration) WithNodeName(value string) *BasicDeviceApplyConfiguration { + b.NodeName = &value + return b +} + +// WithNodeSelector sets the NodeSelector field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeSelector field is set to the value of the last call. +func (b *BasicDeviceApplyConfiguration) WithNodeSelector(value *v1.NodeSelectorApplyConfiguration) *BasicDeviceApplyConfiguration { + b.NodeSelector = value + return b +} + +// WithAllNodes sets the AllNodes field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllNodes field is set to the value of the last call. +func (b *BasicDeviceApplyConfiguration) WithAllNodes(value bool) *BasicDeviceApplyConfiguration { + b.AllNodes = &value + return b +} + +// WithTaints adds the given value to the Taints field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Taints field. +func (b *BasicDeviceApplyConfiguration) WithTaints(values ...*DeviceTaintApplyConfiguration) *BasicDeviceApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTaints") + } + b.Taints = append(b.Taints, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/counter.go b/applyconfigurations/resource/v1alpha3/counter.go new file mode 100644 index 0000000000..10a752ee05 --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/counter.go @@ -0,0 +1,43 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// CounterApplyConfiguration represents a declarative configuration of the Counter type for use +// with apply. +type CounterApplyConfiguration struct { + Value *resource.Quantity `json:"value,omitempty"` +} + +// CounterApplyConfiguration constructs a declarative configuration of the Counter type for use with +// apply. +func Counter() *CounterApplyConfiguration { + return &CounterApplyConfiguration{} +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *CounterApplyConfiguration) WithValue(value resource.Quantity) *CounterApplyConfiguration { + b.Value = &value + return b +} diff --git a/applyconfigurations/resource/v1alpha3/counterset.go b/applyconfigurations/resource/v1alpha3/counterset.go new file mode 100644 index 0000000000..aa917c6ff8 --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/counterset.go @@ -0,0 +1,54 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// CounterSetApplyConfiguration represents a declarative configuration of the CounterSet type for use +// with apply. +type CounterSetApplyConfiguration struct { + Name *string `json:"name,omitempty"` + Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` +} + +// CounterSetApplyConfiguration constructs a declarative configuration of the CounterSet type for use with +// apply. +func CounterSet() *CounterSetApplyConfiguration { + return &CounterSetApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *CounterSetApplyConfiguration) WithName(value string) *CounterSetApplyConfiguration { + b.Name = &value + return b +} + +// WithCounters puts the entries into the Counters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Counters field, +// overwriting an existing map entries in Counters field with the same key. +func (b *CounterSetApplyConfiguration) WithCounters(entries map[string]CounterApplyConfiguration) *CounterSetApplyConfiguration { + if b.Counters == nil && len(entries) > 0 { + b.Counters = make(map[string]CounterApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Counters[k] = v + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicecounterconsumption.go b/applyconfigurations/resource/v1alpha3/devicecounterconsumption.go new file mode 100644 index 0000000000..53deb747eb --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/devicecounterconsumption.go @@ -0,0 +1,54 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// DeviceCounterConsumptionApplyConfiguration represents a declarative configuration of the DeviceCounterConsumption type for use +// with apply. +type DeviceCounterConsumptionApplyConfiguration struct { + CounterSet *string `json:"counterSet,omitempty"` + Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` +} + +// DeviceCounterConsumptionApplyConfiguration constructs a declarative configuration of the DeviceCounterConsumption type for use with +// apply. +func DeviceCounterConsumption() *DeviceCounterConsumptionApplyConfiguration { + return &DeviceCounterConsumptionApplyConfiguration{} +} + +// WithCounterSet sets the CounterSet field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CounterSet field is set to the value of the last call. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCounterSet(value string) *DeviceCounterConsumptionApplyConfiguration { + b.CounterSet = &value + return b +} + +// WithCounters puts the entries into the Counters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Counters field, +// overwriting an existing map entries in Counters field with the same key. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCounters(entries map[string]CounterApplyConfiguration) *DeviceCounterConsumptionApplyConfiguration { + if b.Counters == nil && len(entries) > 0 { + b.Counters = make(map[string]CounterApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Counters[k] = v + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicerequest.go b/applyconfigurations/resource/v1alpha3/devicerequest.go index e5c87efe47..bff72a3f59 100644 --- a/applyconfigurations/resource/v1alpha3/devicerequest.go +++ b/applyconfigurations/resource/v1alpha3/devicerequest.go @@ -31,6 +31,8 @@ type DeviceRequestApplyConfiguration struct { AllocationMode *resourcev1alpha3.DeviceAllocationMode `json:"allocationMode,omitempty"` Count *int64 `json:"count,omitempty"` AdminAccess *bool `json:"adminAccess,omitempty"` + FirstAvailable []DeviceSubRequestApplyConfiguration `json:"firstAvailable,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` } // DeviceRequestApplyConfiguration constructs a declarative configuration of the DeviceRequest type for use with @@ -91,3 +93,29 @@ func (b *DeviceRequestApplyConfiguration) WithAdminAccess(value bool) *DeviceReq b.AdminAccess = &value return b } + +// WithFirstAvailable adds the given value to the FirstAvailable field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the FirstAvailable field. +func (b *DeviceRequestApplyConfiguration) WithFirstAvailable(values ...*DeviceSubRequestApplyConfiguration) *DeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithFirstAvailable") + } + b.FirstAvailable = append(b.FirstAvailable, *values[i]) + } + return b +} + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceRequestApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicerequestallocationresult.go b/applyconfigurations/resource/v1alpha3/devicerequestallocationresult.go index 4c3cffcf46..ec8c78e2e5 100644 --- a/applyconfigurations/resource/v1alpha3/devicerequestallocationresult.go +++ b/applyconfigurations/resource/v1alpha3/devicerequestallocationresult.go @@ -21,11 +21,12 @@ package v1alpha3 // DeviceRequestAllocationResultApplyConfiguration represents a declarative configuration of the DeviceRequestAllocationResult type for use // with apply. type DeviceRequestAllocationResultApplyConfiguration struct { - Request *string `json:"request,omitempty"` - Driver *string `json:"driver,omitempty"` - Pool *string `json:"pool,omitempty"` - Device *string `json:"device,omitempty"` - AdminAccess *bool `json:"adminAccess,omitempty"` + Request *string `json:"request,omitempty"` + Driver *string `json:"driver,omitempty"` + Pool *string `json:"pool,omitempty"` + Device *string `json:"device,omitempty"` + AdminAccess *bool `json:"adminAccess,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` } // DeviceRequestAllocationResultApplyConfiguration constructs a declarative configuration of the DeviceRequestAllocationResult type for use with @@ -73,3 +74,16 @@ func (b *DeviceRequestAllocationResultApplyConfiguration) WithAdminAccess(value b.AdminAccess = &value return b } + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceRequestAllocationResultApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicesubrequest.go b/applyconfigurations/resource/v1alpha3/devicesubrequest.go new file mode 100644 index 0000000000..249dcd1f27 --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/devicesubrequest.go @@ -0,0 +1,98 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + resourcev1alpha3 "k8s.io/api/resource/v1alpha3" +) + +// DeviceSubRequestApplyConfiguration represents a declarative configuration of the DeviceSubRequest type for use +// with apply. +type DeviceSubRequestApplyConfiguration struct { + Name *string `json:"name,omitempty"` + DeviceClassName *string `json:"deviceClassName,omitempty"` + Selectors []DeviceSelectorApplyConfiguration `json:"selectors,omitempty"` + AllocationMode *resourcev1alpha3.DeviceAllocationMode `json:"allocationMode,omitempty"` + Count *int64 `json:"count,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` +} + +// DeviceSubRequestApplyConfiguration constructs a declarative configuration of the DeviceSubRequest type for use with +// apply. +func DeviceSubRequest() *DeviceSubRequestApplyConfiguration { + return &DeviceSubRequestApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithName(value string) *DeviceSubRequestApplyConfiguration { + b.Name = &value + return b +} + +// WithDeviceClassName sets the DeviceClassName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeviceClassName field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithDeviceClassName(value string) *DeviceSubRequestApplyConfiguration { + b.DeviceClassName = &value + return b +} + +// WithSelectors adds the given value to the Selectors field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Selectors field. +func (b *DeviceSubRequestApplyConfiguration) WithSelectors(values ...*DeviceSelectorApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSelectors") + } + b.Selectors = append(b.Selectors, *values[i]) + } + return b +} + +// WithAllocationMode sets the AllocationMode field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllocationMode field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithAllocationMode(value resourcev1alpha3.DeviceAllocationMode) *DeviceSubRequestApplyConfiguration { + b.AllocationMode = &value + return b +} + +// WithCount sets the Count field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Count field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithCount(value int64) *DeviceSubRequestApplyConfiguration { + b.Count = &value + return b +} + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceSubRequestApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicetaint.go b/applyconfigurations/resource/v1alpha3/devicetaint.go new file mode 100644 index 0000000000..0dcd9a58c3 --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/devicetaint.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + resourcev1alpha3 "k8s.io/api/resource/v1alpha3" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// DeviceTaintApplyConfiguration represents a declarative configuration of the DeviceTaint type for use +// with apply. +type DeviceTaintApplyConfiguration struct { + Key *string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` + Effect *resourcev1alpha3.DeviceTaintEffect `json:"effect,omitempty"` + TimeAdded *v1.Time `json:"timeAdded,omitempty"` +} + +// DeviceTaintApplyConfiguration constructs a declarative configuration of the DeviceTaint type for use with +// apply. +func DeviceTaint() *DeviceTaintApplyConfiguration { + return &DeviceTaintApplyConfiguration{} +} + +// WithKey sets the Key field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Key field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithKey(value string) *DeviceTaintApplyConfiguration { + b.Key = &value + return b +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithValue(value string) *DeviceTaintApplyConfiguration { + b.Value = &value + return b +} + +// WithEffect sets the Effect field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Effect field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithEffect(value resourcev1alpha3.DeviceTaintEffect) *DeviceTaintApplyConfiguration { + b.Effect = &value + return b +} + +// WithTimeAdded sets the TimeAdded field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TimeAdded field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithTimeAdded(value v1.Time) *DeviceTaintApplyConfiguration { + b.TimeAdded = &value + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicetaintrule.go b/applyconfigurations/resource/v1alpha3/devicetaintrule.go new file mode 100644 index 0000000000..d4f84399a3 --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/devicetaintrule.go @@ -0,0 +1,253 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + resourcev1alpha3 "k8s.io/api/resource/v1alpha3" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// DeviceTaintRuleApplyConfiguration represents a declarative configuration of the DeviceTaintRule type for use +// with apply. +type DeviceTaintRuleApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *DeviceTaintRuleSpecApplyConfiguration `json:"spec,omitempty"` +} + +// DeviceTaintRule constructs a declarative configuration of the DeviceTaintRule type for use with +// apply. +func DeviceTaintRule(name string) *DeviceTaintRuleApplyConfiguration { + b := &DeviceTaintRuleApplyConfiguration{} + b.WithName(name) + b.WithKind("DeviceTaintRule") + b.WithAPIVersion("resource.k8s.io/v1alpha3") + return b +} + +// ExtractDeviceTaintRule extracts the applied configuration owned by fieldManager from +// deviceTaintRule. If no managedFields are found in deviceTaintRule for fieldManager, a +// DeviceTaintRuleApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// deviceTaintRule must be a unmodified DeviceTaintRule API object that was retrieved from the Kubernetes API. +// ExtractDeviceTaintRule provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractDeviceTaintRule(deviceTaintRule *resourcev1alpha3.DeviceTaintRule, fieldManager string) (*DeviceTaintRuleApplyConfiguration, error) { + return extractDeviceTaintRule(deviceTaintRule, fieldManager, "") +} + +// ExtractDeviceTaintRuleStatus is the same as ExtractDeviceTaintRule except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractDeviceTaintRuleStatus(deviceTaintRule *resourcev1alpha3.DeviceTaintRule, fieldManager string) (*DeviceTaintRuleApplyConfiguration, error) { + return extractDeviceTaintRule(deviceTaintRule, fieldManager, "status") +} + +func extractDeviceTaintRule(deviceTaintRule *resourcev1alpha3.DeviceTaintRule, fieldManager string, subresource string) (*DeviceTaintRuleApplyConfiguration, error) { + b := &DeviceTaintRuleApplyConfiguration{} + err := managedfields.ExtractInto(deviceTaintRule, internal.Parser().Type("io.k8s.api.resource.v1alpha3.DeviceTaintRule"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(deviceTaintRule.Name) + + b.WithKind("DeviceTaintRule") + b.WithAPIVersion("resource.k8s.io/v1alpha3") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithKind(value string) *DeviceTaintRuleApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithAPIVersion(value string) *DeviceTaintRuleApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithName(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithGenerateName(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithNamespace(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithUID(value types.UID) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithResourceVersion(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithGeneration(value int64) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *DeviceTaintRuleApplyConfiguration) WithLabels(entries map[string]string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *DeviceTaintRuleApplyConfiguration) WithAnnotations(entries map[string]string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *DeviceTaintRuleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *DeviceTaintRuleApplyConfiguration) WithFinalizers(values ...string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *DeviceTaintRuleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithSpec(value *DeviceTaintRuleSpecApplyConfiguration) *DeviceTaintRuleApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *DeviceTaintRuleApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/resource/v1alpha3/devicetaintrulespec.go b/applyconfigurations/resource/v1alpha3/devicetaintrulespec.go new file mode 100644 index 0000000000..a14ada3d45 --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/devicetaintrulespec.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// DeviceTaintRuleSpecApplyConfiguration represents a declarative configuration of the DeviceTaintRuleSpec type for use +// with apply. +type DeviceTaintRuleSpecApplyConfiguration struct { + DeviceSelector *DeviceTaintSelectorApplyConfiguration `json:"deviceSelector,omitempty"` + Taint *DeviceTaintApplyConfiguration `json:"taint,omitempty"` +} + +// DeviceTaintRuleSpecApplyConfiguration constructs a declarative configuration of the DeviceTaintRuleSpec type for use with +// apply. +func DeviceTaintRuleSpec() *DeviceTaintRuleSpecApplyConfiguration { + return &DeviceTaintRuleSpecApplyConfiguration{} +} + +// WithDeviceSelector sets the DeviceSelector field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeviceSelector field is set to the value of the last call. +func (b *DeviceTaintRuleSpecApplyConfiguration) WithDeviceSelector(value *DeviceTaintSelectorApplyConfiguration) *DeviceTaintRuleSpecApplyConfiguration { + b.DeviceSelector = value + return b +} + +// WithTaint sets the Taint field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Taint field is set to the value of the last call. +func (b *DeviceTaintRuleSpecApplyConfiguration) WithTaint(value *DeviceTaintApplyConfiguration) *DeviceTaintRuleSpecApplyConfiguration { + b.Taint = value + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicetaintselector.go b/applyconfigurations/resource/v1alpha3/devicetaintselector.go new file mode 100644 index 0000000000..aecb2aa245 --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/devicetaintselector.go @@ -0,0 +1,80 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// DeviceTaintSelectorApplyConfiguration represents a declarative configuration of the DeviceTaintSelector type for use +// with apply. +type DeviceTaintSelectorApplyConfiguration struct { + DeviceClassName *string `json:"deviceClassName,omitempty"` + Driver *string `json:"driver,omitempty"` + Pool *string `json:"pool,omitempty"` + Device *string `json:"device,omitempty"` + Selectors []DeviceSelectorApplyConfiguration `json:"selectors,omitempty"` +} + +// DeviceTaintSelectorApplyConfiguration constructs a declarative configuration of the DeviceTaintSelector type for use with +// apply. +func DeviceTaintSelector() *DeviceTaintSelectorApplyConfiguration { + return &DeviceTaintSelectorApplyConfiguration{} +} + +// WithDeviceClassName sets the DeviceClassName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeviceClassName field is set to the value of the last call. +func (b *DeviceTaintSelectorApplyConfiguration) WithDeviceClassName(value string) *DeviceTaintSelectorApplyConfiguration { + b.DeviceClassName = &value + return b +} + +// WithDriver sets the Driver field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Driver field is set to the value of the last call. +func (b *DeviceTaintSelectorApplyConfiguration) WithDriver(value string) *DeviceTaintSelectorApplyConfiguration { + b.Driver = &value + return b +} + +// WithPool sets the Pool field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Pool field is set to the value of the last call. +func (b *DeviceTaintSelectorApplyConfiguration) WithPool(value string) *DeviceTaintSelectorApplyConfiguration { + b.Pool = &value + return b +} + +// WithDevice sets the Device field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Device field is set to the value of the last call. +func (b *DeviceTaintSelectorApplyConfiguration) WithDevice(value string) *DeviceTaintSelectorApplyConfiguration { + b.Device = &value + return b +} + +// WithSelectors adds the given value to the Selectors field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Selectors field. +func (b *DeviceTaintSelectorApplyConfiguration) WithSelectors(values ...*DeviceSelectorApplyConfiguration) *DeviceTaintSelectorApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSelectors") + } + b.Selectors = append(b.Selectors, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1alpha3/devicetoleration.go b/applyconfigurations/resource/v1alpha3/devicetoleration.go new file mode 100644 index 0000000000..fe4a67419a --- /dev/null +++ b/applyconfigurations/resource/v1alpha3/devicetoleration.go @@ -0,0 +1,79 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + resourcev1alpha3 "k8s.io/api/resource/v1alpha3" +) + +// DeviceTolerationApplyConfiguration represents a declarative configuration of the DeviceToleration type for use +// with apply. +type DeviceTolerationApplyConfiguration struct { + Key *string `json:"key,omitempty"` + Operator *resourcev1alpha3.DeviceTolerationOperator `json:"operator,omitempty"` + Value *string `json:"value,omitempty"` + Effect *resourcev1alpha3.DeviceTaintEffect `json:"effect,omitempty"` + TolerationSeconds *int64 `json:"tolerationSeconds,omitempty"` +} + +// DeviceTolerationApplyConfiguration constructs a declarative configuration of the DeviceToleration type for use with +// apply. +func DeviceToleration() *DeviceTolerationApplyConfiguration { + return &DeviceTolerationApplyConfiguration{} +} + +// WithKey sets the Key field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Key field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithKey(value string) *DeviceTolerationApplyConfiguration { + b.Key = &value + return b +} + +// WithOperator sets the Operator field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Operator field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithOperator(value resourcev1alpha3.DeviceTolerationOperator) *DeviceTolerationApplyConfiguration { + b.Operator = &value + return b +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithValue(value string) *DeviceTolerationApplyConfiguration { + b.Value = &value + return b +} + +// WithEffect sets the Effect field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Effect field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithEffect(value resourcev1alpha3.DeviceTaintEffect) *DeviceTolerationApplyConfiguration { + b.Effect = &value + return b +} + +// WithTolerationSeconds sets the TolerationSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TolerationSeconds field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithTolerationSeconds(value int64) *DeviceTolerationApplyConfiguration { + b.TolerationSeconds = &value + return b +} diff --git a/applyconfigurations/resource/v1alpha3/resourceslicespec.go b/applyconfigurations/resource/v1alpha3/resourceslicespec.go index 2ded759073..ec490760f3 100644 --- a/applyconfigurations/resource/v1alpha3/resourceslicespec.go +++ b/applyconfigurations/resource/v1alpha3/resourceslicespec.go @@ -25,12 +25,14 @@ import ( // ResourceSliceSpecApplyConfiguration represents a declarative configuration of the ResourceSliceSpec type for use // with apply. type ResourceSliceSpecApplyConfiguration struct { - Driver *string `json:"driver,omitempty"` - Pool *ResourcePoolApplyConfiguration `json:"pool,omitempty"` - NodeName *string `json:"nodeName,omitempty"` - NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` - AllNodes *bool `json:"allNodes,omitempty"` - Devices []DeviceApplyConfiguration `json:"devices,omitempty"` + Driver *string `json:"driver,omitempty"` + Pool *ResourcePoolApplyConfiguration `json:"pool,omitempty"` + NodeName *string `json:"nodeName,omitempty"` + NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` + AllNodes *bool `json:"allNodes,omitempty"` + Devices []DeviceApplyConfiguration `json:"devices,omitempty"` + PerDeviceNodeSelection *bool `json:"perDeviceNodeSelection,omitempty"` + SharedCounters []CounterSetApplyConfiguration `json:"sharedCounters,omitempty"` } // ResourceSliceSpecApplyConfiguration constructs a declarative configuration of the ResourceSliceSpec type for use with @@ -91,3 +93,24 @@ func (b *ResourceSliceSpecApplyConfiguration) WithDevices(values ...*DeviceApply } return b } + +// WithPerDeviceNodeSelection sets the PerDeviceNodeSelection field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PerDeviceNodeSelection field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithPerDeviceNodeSelection(value bool) *ResourceSliceSpecApplyConfiguration { + b.PerDeviceNodeSelection = &value + return b +} + +// WithSharedCounters adds the given value to the SharedCounters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SharedCounters field. +func (b *ResourceSliceSpecApplyConfiguration) WithSharedCounters(values ...*CounterSetApplyConfiguration) *ResourceSliceSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSharedCounters") + } + b.SharedCounters = append(b.SharedCounters, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta1/basicdevice.go b/applyconfigurations/resource/v1beta1/basicdevice.go index 691a8f15aa..065d0bf4f1 100644 --- a/applyconfigurations/resource/v1beta1/basicdevice.go +++ b/applyconfigurations/resource/v1beta1/basicdevice.go @@ -20,13 +20,19 @@ package v1beta1 import ( resourcev1beta1 "k8s.io/api/resource/v1beta1" + v1 "k8s.io/client-go/applyconfigurations/core/v1" ) // BasicDeviceApplyConfiguration represents a declarative configuration of the BasicDevice type for use // with apply. type BasicDeviceApplyConfiguration struct { - Attributes map[resourcev1beta1.QualifiedName]DeviceAttributeApplyConfiguration `json:"attributes,omitempty"` - Capacity map[resourcev1beta1.QualifiedName]DeviceCapacityApplyConfiguration `json:"capacity,omitempty"` + Attributes map[resourcev1beta1.QualifiedName]DeviceAttributeApplyConfiguration `json:"attributes,omitempty"` + Capacity map[resourcev1beta1.QualifiedName]DeviceCapacityApplyConfiguration `json:"capacity,omitempty"` + ConsumesCounters []DeviceCounterConsumptionApplyConfiguration `json:"consumesCounters,omitempty"` + NodeName *string `json:"nodeName,omitempty"` + NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` + AllNodes *bool `json:"allNodes,omitempty"` + Taints []DeviceTaintApplyConfiguration `json:"taints,omitempty"` } // BasicDeviceApplyConfiguration constructs a declarative configuration of the BasicDevice type for use with @@ -62,3 +68,53 @@ func (b *BasicDeviceApplyConfiguration) WithCapacity(entries map[resourcev1beta1 } return b } + +// WithConsumesCounters adds the given value to the ConsumesCounters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ConsumesCounters field. +func (b *BasicDeviceApplyConfiguration) WithConsumesCounters(values ...*DeviceCounterConsumptionApplyConfiguration) *BasicDeviceApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConsumesCounters") + } + b.ConsumesCounters = append(b.ConsumesCounters, *values[i]) + } + return b +} + +// WithNodeName sets the NodeName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeName field is set to the value of the last call. +func (b *BasicDeviceApplyConfiguration) WithNodeName(value string) *BasicDeviceApplyConfiguration { + b.NodeName = &value + return b +} + +// WithNodeSelector sets the NodeSelector field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeSelector field is set to the value of the last call. +func (b *BasicDeviceApplyConfiguration) WithNodeSelector(value *v1.NodeSelectorApplyConfiguration) *BasicDeviceApplyConfiguration { + b.NodeSelector = value + return b +} + +// WithAllNodes sets the AllNodes field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllNodes field is set to the value of the last call. +func (b *BasicDeviceApplyConfiguration) WithAllNodes(value bool) *BasicDeviceApplyConfiguration { + b.AllNodes = &value + return b +} + +// WithTaints adds the given value to the Taints field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Taints field. +func (b *BasicDeviceApplyConfiguration) WithTaints(values ...*DeviceTaintApplyConfiguration) *BasicDeviceApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTaints") + } + b.Taints = append(b.Taints, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta1/counter.go b/applyconfigurations/resource/v1beta1/counter.go new file mode 100644 index 0000000000..b33ed99a59 --- /dev/null +++ b/applyconfigurations/resource/v1beta1/counter.go @@ -0,0 +1,43 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// CounterApplyConfiguration represents a declarative configuration of the Counter type for use +// with apply. +type CounterApplyConfiguration struct { + Value *resource.Quantity `json:"value,omitempty"` +} + +// CounterApplyConfiguration constructs a declarative configuration of the Counter type for use with +// apply. +func Counter() *CounterApplyConfiguration { + return &CounterApplyConfiguration{} +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *CounterApplyConfiguration) WithValue(value resource.Quantity) *CounterApplyConfiguration { + b.Value = &value + return b +} diff --git a/applyconfigurations/resource/v1beta1/counterset.go b/applyconfigurations/resource/v1beta1/counterset.go new file mode 100644 index 0000000000..7592fa4d5b --- /dev/null +++ b/applyconfigurations/resource/v1beta1/counterset.go @@ -0,0 +1,54 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// CounterSetApplyConfiguration represents a declarative configuration of the CounterSet type for use +// with apply. +type CounterSetApplyConfiguration struct { + Name *string `json:"name,omitempty"` + Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` +} + +// CounterSetApplyConfiguration constructs a declarative configuration of the CounterSet type for use with +// apply. +func CounterSet() *CounterSetApplyConfiguration { + return &CounterSetApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *CounterSetApplyConfiguration) WithName(value string) *CounterSetApplyConfiguration { + b.Name = &value + return b +} + +// WithCounters puts the entries into the Counters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Counters field, +// overwriting an existing map entries in Counters field with the same key. +func (b *CounterSetApplyConfiguration) WithCounters(entries map[string]CounterApplyConfiguration) *CounterSetApplyConfiguration { + if b.Counters == nil && len(entries) > 0 { + b.Counters = make(map[string]CounterApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Counters[k] = v + } + return b +} diff --git a/applyconfigurations/resource/v1beta1/devicecounterconsumption.go b/applyconfigurations/resource/v1beta1/devicecounterconsumption.go new file mode 100644 index 0000000000..a8a8a5f581 --- /dev/null +++ b/applyconfigurations/resource/v1beta1/devicecounterconsumption.go @@ -0,0 +1,54 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// DeviceCounterConsumptionApplyConfiguration represents a declarative configuration of the DeviceCounterConsumption type for use +// with apply. +type DeviceCounterConsumptionApplyConfiguration struct { + CounterSet *string `json:"counterSet,omitempty"` + Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` +} + +// DeviceCounterConsumptionApplyConfiguration constructs a declarative configuration of the DeviceCounterConsumption type for use with +// apply. +func DeviceCounterConsumption() *DeviceCounterConsumptionApplyConfiguration { + return &DeviceCounterConsumptionApplyConfiguration{} +} + +// WithCounterSet sets the CounterSet field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CounterSet field is set to the value of the last call. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCounterSet(value string) *DeviceCounterConsumptionApplyConfiguration { + b.CounterSet = &value + return b +} + +// WithCounters puts the entries into the Counters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Counters field, +// overwriting an existing map entries in Counters field with the same key. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCounters(entries map[string]CounterApplyConfiguration) *DeviceCounterConsumptionApplyConfiguration { + if b.Counters == nil && len(entries) > 0 { + b.Counters = make(map[string]CounterApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Counters[k] = v + } + return b +} diff --git a/applyconfigurations/resource/v1beta1/devicerequest.go b/applyconfigurations/resource/v1beta1/devicerequest.go index ea454a275c..1be114f02a 100644 --- a/applyconfigurations/resource/v1beta1/devicerequest.go +++ b/applyconfigurations/resource/v1beta1/devicerequest.go @@ -31,6 +31,8 @@ type DeviceRequestApplyConfiguration struct { AllocationMode *resourcev1beta1.DeviceAllocationMode `json:"allocationMode,omitempty"` Count *int64 `json:"count,omitempty"` AdminAccess *bool `json:"adminAccess,omitempty"` + FirstAvailable []DeviceSubRequestApplyConfiguration `json:"firstAvailable,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` } // DeviceRequestApplyConfiguration constructs a declarative configuration of the DeviceRequest type for use with @@ -91,3 +93,29 @@ func (b *DeviceRequestApplyConfiguration) WithAdminAccess(value bool) *DeviceReq b.AdminAccess = &value return b } + +// WithFirstAvailable adds the given value to the FirstAvailable field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the FirstAvailable field. +func (b *DeviceRequestApplyConfiguration) WithFirstAvailable(values ...*DeviceSubRequestApplyConfiguration) *DeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithFirstAvailable") + } + b.FirstAvailable = append(b.FirstAvailable, *values[i]) + } + return b +} + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceRequestApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go b/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go index c28eb26ab6..aa207351db 100644 --- a/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go +++ b/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go @@ -21,11 +21,12 @@ package v1beta1 // DeviceRequestAllocationResultApplyConfiguration represents a declarative configuration of the DeviceRequestAllocationResult type for use // with apply. type DeviceRequestAllocationResultApplyConfiguration struct { - Request *string `json:"request,omitempty"` - Driver *string `json:"driver,omitempty"` - Pool *string `json:"pool,omitempty"` - Device *string `json:"device,omitempty"` - AdminAccess *bool `json:"adminAccess,omitempty"` + Request *string `json:"request,omitempty"` + Driver *string `json:"driver,omitempty"` + Pool *string `json:"pool,omitempty"` + Device *string `json:"device,omitempty"` + AdminAccess *bool `json:"adminAccess,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` } // DeviceRequestAllocationResultApplyConfiguration constructs a declarative configuration of the DeviceRequestAllocationResult type for use with @@ -73,3 +74,16 @@ func (b *DeviceRequestAllocationResultApplyConfiguration) WithAdminAccess(value b.AdminAccess = &value return b } + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceRequestAllocationResultApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta1/devicesubrequest.go b/applyconfigurations/resource/v1beta1/devicesubrequest.go new file mode 100644 index 0000000000..f2ea820013 --- /dev/null +++ b/applyconfigurations/resource/v1beta1/devicesubrequest.go @@ -0,0 +1,98 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + resourcev1beta1 "k8s.io/api/resource/v1beta1" +) + +// DeviceSubRequestApplyConfiguration represents a declarative configuration of the DeviceSubRequest type for use +// with apply. +type DeviceSubRequestApplyConfiguration struct { + Name *string `json:"name,omitempty"` + DeviceClassName *string `json:"deviceClassName,omitempty"` + Selectors []DeviceSelectorApplyConfiguration `json:"selectors,omitempty"` + AllocationMode *resourcev1beta1.DeviceAllocationMode `json:"allocationMode,omitempty"` + Count *int64 `json:"count,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` +} + +// DeviceSubRequestApplyConfiguration constructs a declarative configuration of the DeviceSubRequest type for use with +// apply. +func DeviceSubRequest() *DeviceSubRequestApplyConfiguration { + return &DeviceSubRequestApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithName(value string) *DeviceSubRequestApplyConfiguration { + b.Name = &value + return b +} + +// WithDeviceClassName sets the DeviceClassName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeviceClassName field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithDeviceClassName(value string) *DeviceSubRequestApplyConfiguration { + b.DeviceClassName = &value + return b +} + +// WithSelectors adds the given value to the Selectors field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Selectors field. +func (b *DeviceSubRequestApplyConfiguration) WithSelectors(values ...*DeviceSelectorApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSelectors") + } + b.Selectors = append(b.Selectors, *values[i]) + } + return b +} + +// WithAllocationMode sets the AllocationMode field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllocationMode field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithAllocationMode(value resourcev1beta1.DeviceAllocationMode) *DeviceSubRequestApplyConfiguration { + b.AllocationMode = &value + return b +} + +// WithCount sets the Count field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Count field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithCount(value int64) *DeviceSubRequestApplyConfiguration { + b.Count = &value + return b +} + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceSubRequestApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta1/devicetaint.go b/applyconfigurations/resource/v1beta1/devicetaint.go new file mode 100644 index 0000000000..bfa826f063 --- /dev/null +++ b/applyconfigurations/resource/v1beta1/devicetaint.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + resourcev1beta1 "k8s.io/api/resource/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// DeviceTaintApplyConfiguration represents a declarative configuration of the DeviceTaint type for use +// with apply. +type DeviceTaintApplyConfiguration struct { + Key *string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` + Effect *resourcev1beta1.DeviceTaintEffect `json:"effect,omitempty"` + TimeAdded *v1.Time `json:"timeAdded,omitempty"` +} + +// DeviceTaintApplyConfiguration constructs a declarative configuration of the DeviceTaint type for use with +// apply. +func DeviceTaint() *DeviceTaintApplyConfiguration { + return &DeviceTaintApplyConfiguration{} +} + +// WithKey sets the Key field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Key field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithKey(value string) *DeviceTaintApplyConfiguration { + b.Key = &value + return b +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithValue(value string) *DeviceTaintApplyConfiguration { + b.Value = &value + return b +} + +// WithEffect sets the Effect field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Effect field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithEffect(value resourcev1beta1.DeviceTaintEffect) *DeviceTaintApplyConfiguration { + b.Effect = &value + return b +} + +// WithTimeAdded sets the TimeAdded field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TimeAdded field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithTimeAdded(value v1.Time) *DeviceTaintApplyConfiguration { + b.TimeAdded = &value + return b +} diff --git a/applyconfigurations/resource/v1beta1/devicetoleration.go b/applyconfigurations/resource/v1beta1/devicetoleration.go new file mode 100644 index 0000000000..977af67043 --- /dev/null +++ b/applyconfigurations/resource/v1beta1/devicetoleration.go @@ -0,0 +1,79 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + resourcev1beta1 "k8s.io/api/resource/v1beta1" +) + +// DeviceTolerationApplyConfiguration represents a declarative configuration of the DeviceToleration type for use +// with apply. +type DeviceTolerationApplyConfiguration struct { + Key *string `json:"key,omitempty"` + Operator *resourcev1beta1.DeviceTolerationOperator `json:"operator,omitempty"` + Value *string `json:"value,omitempty"` + Effect *resourcev1beta1.DeviceTaintEffect `json:"effect,omitempty"` + TolerationSeconds *int64 `json:"tolerationSeconds,omitempty"` +} + +// DeviceTolerationApplyConfiguration constructs a declarative configuration of the DeviceToleration type for use with +// apply. +func DeviceToleration() *DeviceTolerationApplyConfiguration { + return &DeviceTolerationApplyConfiguration{} +} + +// WithKey sets the Key field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Key field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithKey(value string) *DeviceTolerationApplyConfiguration { + b.Key = &value + return b +} + +// WithOperator sets the Operator field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Operator field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithOperator(value resourcev1beta1.DeviceTolerationOperator) *DeviceTolerationApplyConfiguration { + b.Operator = &value + return b +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithValue(value string) *DeviceTolerationApplyConfiguration { + b.Value = &value + return b +} + +// WithEffect sets the Effect field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Effect field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithEffect(value resourcev1beta1.DeviceTaintEffect) *DeviceTolerationApplyConfiguration { + b.Effect = &value + return b +} + +// WithTolerationSeconds sets the TolerationSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TolerationSeconds field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithTolerationSeconds(value int64) *DeviceTolerationApplyConfiguration { + b.TolerationSeconds = &value + return b +} diff --git a/applyconfigurations/resource/v1beta1/resourceslicespec.go b/applyconfigurations/resource/v1beta1/resourceslicespec.go index 75bbb53c87..6eaae7da85 100644 --- a/applyconfigurations/resource/v1beta1/resourceslicespec.go +++ b/applyconfigurations/resource/v1beta1/resourceslicespec.go @@ -25,12 +25,14 @@ import ( // ResourceSliceSpecApplyConfiguration represents a declarative configuration of the ResourceSliceSpec type for use // with apply. type ResourceSliceSpecApplyConfiguration struct { - Driver *string `json:"driver,omitempty"` - Pool *ResourcePoolApplyConfiguration `json:"pool,omitempty"` - NodeName *string `json:"nodeName,omitempty"` - NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` - AllNodes *bool `json:"allNodes,omitempty"` - Devices []DeviceApplyConfiguration `json:"devices,omitempty"` + Driver *string `json:"driver,omitempty"` + Pool *ResourcePoolApplyConfiguration `json:"pool,omitempty"` + NodeName *string `json:"nodeName,omitempty"` + NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` + AllNodes *bool `json:"allNodes,omitempty"` + Devices []DeviceApplyConfiguration `json:"devices,omitempty"` + PerDeviceNodeSelection *bool `json:"perDeviceNodeSelection,omitempty"` + SharedCounters []CounterSetApplyConfiguration `json:"sharedCounters,omitempty"` } // ResourceSliceSpecApplyConfiguration constructs a declarative configuration of the ResourceSliceSpec type for use with @@ -91,3 +93,24 @@ func (b *ResourceSliceSpecApplyConfiguration) WithDevices(values ...*DeviceApply } return b } + +// WithPerDeviceNodeSelection sets the PerDeviceNodeSelection field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PerDeviceNodeSelection field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithPerDeviceNodeSelection(value bool) *ResourceSliceSpecApplyConfiguration { + b.PerDeviceNodeSelection = &value + return b +} + +// WithSharedCounters adds the given value to the SharedCounters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SharedCounters field. +func (b *ResourceSliceSpecApplyConfiguration) WithSharedCounters(values ...*CounterSetApplyConfiguration) *ResourceSliceSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSharedCounters") + } + b.SharedCounters = append(b.SharedCounters, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/allocateddevicestatus.go b/applyconfigurations/resource/v1beta2/allocateddevicestatus.go new file mode 100644 index 0000000000..a69cf26eb3 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/allocateddevicestatus.go @@ -0,0 +1,94 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// AllocatedDeviceStatusApplyConfiguration represents a declarative configuration of the AllocatedDeviceStatus type for use +// with apply. +type AllocatedDeviceStatusApplyConfiguration struct { + Driver *string `json:"driver,omitempty"` + Pool *string `json:"pool,omitempty"` + Device *string `json:"device,omitempty"` + Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` + Data *runtime.RawExtension `json:"data,omitempty"` + NetworkData *NetworkDeviceDataApplyConfiguration `json:"networkData,omitempty"` +} + +// AllocatedDeviceStatusApplyConfiguration constructs a declarative configuration of the AllocatedDeviceStatus type for use with +// apply. +func AllocatedDeviceStatus() *AllocatedDeviceStatusApplyConfiguration { + return &AllocatedDeviceStatusApplyConfiguration{} +} + +// WithDriver sets the Driver field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Driver field is set to the value of the last call. +func (b *AllocatedDeviceStatusApplyConfiguration) WithDriver(value string) *AllocatedDeviceStatusApplyConfiguration { + b.Driver = &value + return b +} + +// WithPool sets the Pool field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Pool field is set to the value of the last call. +func (b *AllocatedDeviceStatusApplyConfiguration) WithPool(value string) *AllocatedDeviceStatusApplyConfiguration { + b.Pool = &value + return b +} + +// WithDevice sets the Device field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Device field is set to the value of the last call. +func (b *AllocatedDeviceStatusApplyConfiguration) WithDevice(value string) *AllocatedDeviceStatusApplyConfiguration { + b.Device = &value + return b +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *AllocatedDeviceStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *AllocatedDeviceStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} + +// WithData sets the Data field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Data field is set to the value of the last call. +func (b *AllocatedDeviceStatusApplyConfiguration) WithData(value runtime.RawExtension) *AllocatedDeviceStatusApplyConfiguration { + b.Data = &value + return b +} + +// WithNetworkData sets the NetworkData field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NetworkData field is set to the value of the last call. +func (b *AllocatedDeviceStatusApplyConfiguration) WithNetworkData(value *NetworkDeviceDataApplyConfiguration) *AllocatedDeviceStatusApplyConfiguration { + b.NetworkData = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/allocationresult.go b/applyconfigurations/resource/v1beta2/allocationresult.go new file mode 100644 index 0000000000..a82b01c967 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/allocationresult.go @@ -0,0 +1,52 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + v1 "k8s.io/client-go/applyconfigurations/core/v1" +) + +// AllocationResultApplyConfiguration represents a declarative configuration of the AllocationResult type for use +// with apply. +type AllocationResultApplyConfiguration struct { + Devices *DeviceAllocationResultApplyConfiguration `json:"devices,omitempty"` + NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` +} + +// AllocationResultApplyConfiguration constructs a declarative configuration of the AllocationResult type for use with +// apply. +func AllocationResult() *AllocationResultApplyConfiguration { + return &AllocationResultApplyConfiguration{} +} + +// WithDevices sets the Devices field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Devices field is set to the value of the last call. +func (b *AllocationResultApplyConfiguration) WithDevices(value *DeviceAllocationResultApplyConfiguration) *AllocationResultApplyConfiguration { + b.Devices = value + return b +} + +// WithNodeSelector sets the NodeSelector field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeSelector field is set to the value of the last call. +func (b *AllocationResultApplyConfiguration) WithNodeSelector(value *v1.NodeSelectorApplyConfiguration) *AllocationResultApplyConfiguration { + b.NodeSelector = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/celdeviceselector.go b/applyconfigurations/resource/v1beta2/celdeviceselector.go new file mode 100644 index 0000000000..c2c3e52f0e --- /dev/null +++ b/applyconfigurations/resource/v1beta2/celdeviceselector.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// CELDeviceSelectorApplyConfiguration represents a declarative configuration of the CELDeviceSelector type for use +// with apply. +type CELDeviceSelectorApplyConfiguration struct { + Expression *string `json:"expression,omitempty"` +} + +// CELDeviceSelectorApplyConfiguration constructs a declarative configuration of the CELDeviceSelector type for use with +// apply. +func CELDeviceSelector() *CELDeviceSelectorApplyConfiguration { + return &CELDeviceSelectorApplyConfiguration{} +} + +// WithExpression sets the Expression field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Expression field is set to the value of the last call. +func (b *CELDeviceSelectorApplyConfiguration) WithExpression(value string) *CELDeviceSelectorApplyConfiguration { + b.Expression = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/counter.go b/applyconfigurations/resource/v1beta2/counter.go new file mode 100644 index 0000000000..4afdb9a3a5 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/counter.go @@ -0,0 +1,43 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// CounterApplyConfiguration represents a declarative configuration of the Counter type for use +// with apply. +type CounterApplyConfiguration struct { + Value *resource.Quantity `json:"value,omitempty"` +} + +// CounterApplyConfiguration constructs a declarative configuration of the Counter type for use with +// apply. +func Counter() *CounterApplyConfiguration { + return &CounterApplyConfiguration{} +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *CounterApplyConfiguration) WithValue(value resource.Quantity) *CounterApplyConfiguration { + b.Value = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/counterset.go b/applyconfigurations/resource/v1beta2/counterset.go new file mode 100644 index 0000000000..2882b4ef25 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/counterset.go @@ -0,0 +1,54 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// CounterSetApplyConfiguration represents a declarative configuration of the CounterSet type for use +// with apply. +type CounterSetApplyConfiguration struct { + Name *string `json:"name,omitempty"` + Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` +} + +// CounterSetApplyConfiguration constructs a declarative configuration of the CounterSet type for use with +// apply. +func CounterSet() *CounterSetApplyConfiguration { + return &CounterSetApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *CounterSetApplyConfiguration) WithName(value string) *CounterSetApplyConfiguration { + b.Name = &value + return b +} + +// WithCounters puts the entries into the Counters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Counters field, +// overwriting an existing map entries in Counters field with the same key. +func (b *CounterSetApplyConfiguration) WithCounters(entries map[string]CounterApplyConfiguration) *CounterSetApplyConfiguration { + if b.Counters == nil && len(entries) > 0 { + b.Counters = make(map[string]CounterApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Counters[k] = v + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/device.go b/applyconfigurations/resource/v1beta2/device.go new file mode 100644 index 0000000000..a05eb513f7 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/device.go @@ -0,0 +1,129 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/client-go/applyconfigurations/core/v1" +) + +// DeviceApplyConfiguration represents a declarative configuration of the Device type for use +// with apply. +type DeviceApplyConfiguration struct { + Name *string `json:"name,omitempty"` + Attributes map[resourcev1beta2.QualifiedName]DeviceAttributeApplyConfiguration `json:"attributes,omitempty"` + Capacity map[resourcev1beta2.QualifiedName]DeviceCapacityApplyConfiguration `json:"capacity,omitempty"` + ConsumesCounters []DeviceCounterConsumptionApplyConfiguration `json:"consumesCounters,omitempty"` + NodeName *string `json:"nodeName,omitempty"` + NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` + AllNodes *bool `json:"allNodes,omitempty"` + Taints []DeviceTaintApplyConfiguration `json:"taints,omitempty"` +} + +// DeviceApplyConfiguration constructs a declarative configuration of the Device type for use with +// apply. +func Device() *DeviceApplyConfiguration { + return &DeviceApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *DeviceApplyConfiguration) WithName(value string) *DeviceApplyConfiguration { + b.Name = &value + return b +} + +// WithAttributes puts the entries into the Attributes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Attributes field, +// overwriting an existing map entries in Attributes field with the same key. +func (b *DeviceApplyConfiguration) WithAttributes(entries map[resourcev1beta2.QualifiedName]DeviceAttributeApplyConfiguration) *DeviceApplyConfiguration { + if b.Attributes == nil && len(entries) > 0 { + b.Attributes = make(map[resourcev1beta2.QualifiedName]DeviceAttributeApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Attributes[k] = v + } + return b +} + +// WithCapacity puts the entries into the Capacity field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Capacity field, +// overwriting an existing map entries in Capacity field with the same key. +func (b *DeviceApplyConfiguration) WithCapacity(entries map[resourcev1beta2.QualifiedName]DeviceCapacityApplyConfiguration) *DeviceApplyConfiguration { + if b.Capacity == nil && len(entries) > 0 { + b.Capacity = make(map[resourcev1beta2.QualifiedName]DeviceCapacityApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Capacity[k] = v + } + return b +} + +// WithConsumesCounters adds the given value to the ConsumesCounters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ConsumesCounters field. +func (b *DeviceApplyConfiguration) WithConsumesCounters(values ...*DeviceCounterConsumptionApplyConfiguration) *DeviceApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConsumesCounters") + } + b.ConsumesCounters = append(b.ConsumesCounters, *values[i]) + } + return b +} + +// WithNodeName sets the NodeName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeName field is set to the value of the last call. +func (b *DeviceApplyConfiguration) WithNodeName(value string) *DeviceApplyConfiguration { + b.NodeName = &value + return b +} + +// WithNodeSelector sets the NodeSelector field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeSelector field is set to the value of the last call. +func (b *DeviceApplyConfiguration) WithNodeSelector(value *v1.NodeSelectorApplyConfiguration) *DeviceApplyConfiguration { + b.NodeSelector = value + return b +} + +// WithAllNodes sets the AllNodes field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllNodes field is set to the value of the last call. +func (b *DeviceApplyConfiguration) WithAllNodes(value bool) *DeviceApplyConfiguration { + b.AllNodes = &value + return b +} + +// WithTaints adds the given value to the Taints field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Taints field. +func (b *DeviceApplyConfiguration) WithTaints(values ...*DeviceTaintApplyConfiguration) *DeviceApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTaints") + } + b.Taints = append(b.Taints, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceallocationconfiguration.go b/applyconfigurations/resource/v1beta2/deviceallocationconfiguration.go new file mode 100644 index 0000000000..971fe807c8 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceallocationconfiguration.go @@ -0,0 +1,63 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" +) + +// DeviceAllocationConfigurationApplyConfiguration represents a declarative configuration of the DeviceAllocationConfiguration type for use +// with apply. +type DeviceAllocationConfigurationApplyConfiguration struct { + Source *resourcev1beta2.AllocationConfigSource `json:"source,omitempty"` + Requests []string `json:"requests,omitempty"` + DeviceConfigurationApplyConfiguration `json:",inline"` +} + +// DeviceAllocationConfigurationApplyConfiguration constructs a declarative configuration of the DeviceAllocationConfiguration type for use with +// apply. +func DeviceAllocationConfiguration() *DeviceAllocationConfigurationApplyConfiguration { + return &DeviceAllocationConfigurationApplyConfiguration{} +} + +// WithSource sets the Source field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Source field is set to the value of the last call. +func (b *DeviceAllocationConfigurationApplyConfiguration) WithSource(value resourcev1beta2.AllocationConfigSource) *DeviceAllocationConfigurationApplyConfiguration { + b.Source = &value + return b +} + +// WithRequests adds the given value to the Requests field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Requests field. +func (b *DeviceAllocationConfigurationApplyConfiguration) WithRequests(values ...string) *DeviceAllocationConfigurationApplyConfiguration { + for i := range values { + b.Requests = append(b.Requests, values[i]) + } + return b +} + +// WithOpaque sets the Opaque field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Opaque field is set to the value of the last call. +func (b *DeviceAllocationConfigurationApplyConfiguration) WithOpaque(value *OpaqueDeviceConfigurationApplyConfiguration) *DeviceAllocationConfigurationApplyConfiguration { + b.DeviceConfigurationApplyConfiguration.Opaque = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceallocationresult.go b/applyconfigurations/resource/v1beta2/deviceallocationresult.go new file mode 100644 index 0000000000..5d9f013073 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceallocationresult.go @@ -0,0 +1,58 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceAllocationResultApplyConfiguration represents a declarative configuration of the DeviceAllocationResult type for use +// with apply. +type DeviceAllocationResultApplyConfiguration struct { + Results []DeviceRequestAllocationResultApplyConfiguration `json:"results,omitempty"` + Config []DeviceAllocationConfigurationApplyConfiguration `json:"config,omitempty"` +} + +// DeviceAllocationResultApplyConfiguration constructs a declarative configuration of the DeviceAllocationResult type for use with +// apply. +func DeviceAllocationResult() *DeviceAllocationResultApplyConfiguration { + return &DeviceAllocationResultApplyConfiguration{} +} + +// WithResults adds the given value to the Results field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Results field. +func (b *DeviceAllocationResultApplyConfiguration) WithResults(values ...*DeviceRequestAllocationResultApplyConfiguration) *DeviceAllocationResultApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithResults") + } + b.Results = append(b.Results, *values[i]) + } + return b +} + +// WithConfig adds the given value to the Config field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Config field. +func (b *DeviceAllocationResultApplyConfiguration) WithConfig(values ...*DeviceAllocationConfigurationApplyConfiguration) *DeviceAllocationResultApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConfig") + } + b.Config = append(b.Config, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceattribute.go b/applyconfigurations/resource/v1beta2/deviceattribute.go new file mode 100644 index 0000000000..c5f88c3f78 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceattribute.go @@ -0,0 +1,66 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceAttributeApplyConfiguration represents a declarative configuration of the DeviceAttribute type for use +// with apply. +type DeviceAttributeApplyConfiguration struct { + IntValue *int64 `json:"int,omitempty"` + BoolValue *bool `json:"bool,omitempty"` + StringValue *string `json:"string,omitempty"` + VersionValue *string `json:"version,omitempty"` +} + +// DeviceAttributeApplyConfiguration constructs a declarative configuration of the DeviceAttribute type for use with +// apply. +func DeviceAttribute() *DeviceAttributeApplyConfiguration { + return &DeviceAttributeApplyConfiguration{} +} + +// WithIntValue sets the IntValue field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the IntValue field is set to the value of the last call. +func (b *DeviceAttributeApplyConfiguration) WithIntValue(value int64) *DeviceAttributeApplyConfiguration { + b.IntValue = &value + return b +} + +// WithBoolValue sets the BoolValue field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BoolValue field is set to the value of the last call. +func (b *DeviceAttributeApplyConfiguration) WithBoolValue(value bool) *DeviceAttributeApplyConfiguration { + b.BoolValue = &value + return b +} + +// WithStringValue sets the StringValue field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the StringValue field is set to the value of the last call. +func (b *DeviceAttributeApplyConfiguration) WithStringValue(value string) *DeviceAttributeApplyConfiguration { + b.StringValue = &value + return b +} + +// WithVersionValue sets the VersionValue field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the VersionValue field is set to the value of the last call. +func (b *DeviceAttributeApplyConfiguration) WithVersionValue(value string) *DeviceAttributeApplyConfiguration { + b.VersionValue = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/devicecapacity.go b/applyconfigurations/resource/v1beta2/devicecapacity.go new file mode 100644 index 0000000000..f62168cdee --- /dev/null +++ b/applyconfigurations/resource/v1beta2/devicecapacity.go @@ -0,0 +1,43 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// DeviceCapacityApplyConfiguration represents a declarative configuration of the DeviceCapacity type for use +// with apply. +type DeviceCapacityApplyConfiguration struct { + Value *resource.Quantity `json:"value,omitempty"` +} + +// DeviceCapacityApplyConfiguration constructs a declarative configuration of the DeviceCapacity type for use with +// apply. +func DeviceCapacity() *DeviceCapacityApplyConfiguration { + return &DeviceCapacityApplyConfiguration{} +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *DeviceCapacityApplyConfiguration) WithValue(value resource.Quantity) *DeviceCapacityApplyConfiguration { + b.Value = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceclaim.go b/applyconfigurations/resource/v1beta2/deviceclaim.go new file mode 100644 index 0000000000..33af599ac8 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceclaim.go @@ -0,0 +1,72 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceClaimApplyConfiguration represents a declarative configuration of the DeviceClaim type for use +// with apply. +type DeviceClaimApplyConfiguration struct { + Requests []DeviceRequestApplyConfiguration `json:"requests,omitempty"` + Constraints []DeviceConstraintApplyConfiguration `json:"constraints,omitempty"` + Config []DeviceClaimConfigurationApplyConfiguration `json:"config,omitempty"` +} + +// DeviceClaimApplyConfiguration constructs a declarative configuration of the DeviceClaim type for use with +// apply. +func DeviceClaim() *DeviceClaimApplyConfiguration { + return &DeviceClaimApplyConfiguration{} +} + +// WithRequests adds the given value to the Requests field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Requests field. +func (b *DeviceClaimApplyConfiguration) WithRequests(values ...*DeviceRequestApplyConfiguration) *DeviceClaimApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithRequests") + } + b.Requests = append(b.Requests, *values[i]) + } + return b +} + +// WithConstraints adds the given value to the Constraints field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Constraints field. +func (b *DeviceClaimApplyConfiguration) WithConstraints(values ...*DeviceConstraintApplyConfiguration) *DeviceClaimApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConstraints") + } + b.Constraints = append(b.Constraints, *values[i]) + } + return b +} + +// WithConfig adds the given value to the Config field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Config field. +func (b *DeviceClaimApplyConfiguration) WithConfig(values ...*DeviceClaimConfigurationApplyConfiguration) *DeviceClaimApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConfig") + } + b.Config = append(b.Config, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceclaimconfiguration.go b/applyconfigurations/resource/v1beta2/deviceclaimconfiguration.go new file mode 100644 index 0000000000..08464b399a --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceclaimconfiguration.go @@ -0,0 +1,50 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceClaimConfigurationApplyConfiguration represents a declarative configuration of the DeviceClaimConfiguration type for use +// with apply. +type DeviceClaimConfigurationApplyConfiguration struct { + Requests []string `json:"requests,omitempty"` + DeviceConfigurationApplyConfiguration `json:",inline"` +} + +// DeviceClaimConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClaimConfiguration type for use with +// apply. +func DeviceClaimConfiguration() *DeviceClaimConfigurationApplyConfiguration { + return &DeviceClaimConfigurationApplyConfiguration{} +} + +// WithRequests adds the given value to the Requests field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Requests field. +func (b *DeviceClaimConfigurationApplyConfiguration) WithRequests(values ...string) *DeviceClaimConfigurationApplyConfiguration { + for i := range values { + b.Requests = append(b.Requests, values[i]) + } + return b +} + +// WithOpaque sets the Opaque field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Opaque field is set to the value of the last call. +func (b *DeviceClaimConfigurationApplyConfiguration) WithOpaque(value *OpaqueDeviceConfigurationApplyConfiguration) *DeviceClaimConfigurationApplyConfiguration { + b.DeviceConfigurationApplyConfiguration.Opaque = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceclass.go b/applyconfigurations/resource/v1beta2/deviceclass.go new file mode 100644 index 0000000000..a361f331e1 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceclass.go @@ -0,0 +1,253 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// DeviceClassApplyConfiguration represents a declarative configuration of the DeviceClass type for use +// with apply. +type DeviceClassApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *DeviceClassSpecApplyConfiguration `json:"spec,omitempty"` +} + +// DeviceClass constructs a declarative configuration of the DeviceClass type for use with +// apply. +func DeviceClass(name string) *DeviceClassApplyConfiguration { + b := &DeviceClassApplyConfiguration{} + b.WithName(name) + b.WithKind("DeviceClass") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b +} + +// ExtractDeviceClass extracts the applied configuration owned by fieldManager from +// deviceClass. If no managedFields are found in deviceClass for fieldManager, a +// DeviceClassApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// deviceClass must be a unmodified DeviceClass API object that was retrieved from the Kubernetes API. +// ExtractDeviceClass provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractDeviceClass(deviceClass *resourcev1beta2.DeviceClass, fieldManager string) (*DeviceClassApplyConfiguration, error) { + return extractDeviceClass(deviceClass, fieldManager, "") +} + +// ExtractDeviceClassStatus is the same as ExtractDeviceClass except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractDeviceClassStatus(deviceClass *resourcev1beta2.DeviceClass, fieldManager string) (*DeviceClassApplyConfiguration, error) { + return extractDeviceClass(deviceClass, fieldManager, "status") +} + +func extractDeviceClass(deviceClass *resourcev1beta2.DeviceClass, fieldManager string, subresource string) (*DeviceClassApplyConfiguration, error) { + b := &DeviceClassApplyConfiguration{} + err := managedfields.ExtractInto(deviceClass, internal.Parser().Type("io.k8s.api.resource.v1beta2.DeviceClass"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(deviceClass.Name) + + b.WithKind("DeviceClass") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithKind(value string) *DeviceClassApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithAPIVersion(value string) *DeviceClassApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithName(value string) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithGenerateName(value string) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithNamespace(value string) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithUID(value types.UID) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithResourceVersion(value string) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithGeneration(value int64) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *DeviceClassApplyConfiguration) WithLabels(entries map[string]string) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *DeviceClassApplyConfiguration) WithAnnotations(entries map[string]string) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *DeviceClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *DeviceClassApplyConfiguration) WithFinalizers(values ...string) *DeviceClassApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *DeviceClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *DeviceClassApplyConfiguration) WithSpec(value *DeviceClassSpecApplyConfiguration) *DeviceClassApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *DeviceClassApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/resource/v1beta2/deviceclassconfiguration.go b/applyconfigurations/resource/v1beta2/deviceclassconfiguration.go new file mode 100644 index 0000000000..9044102802 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceclassconfiguration.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceClassConfigurationApplyConfiguration represents a declarative configuration of the DeviceClassConfiguration type for use +// with apply. +type DeviceClassConfigurationApplyConfiguration struct { + DeviceConfigurationApplyConfiguration `json:",inline"` +} + +// DeviceClassConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClassConfiguration type for use with +// apply. +func DeviceClassConfiguration() *DeviceClassConfigurationApplyConfiguration { + return &DeviceClassConfigurationApplyConfiguration{} +} + +// WithOpaque sets the Opaque field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Opaque field is set to the value of the last call. +func (b *DeviceClassConfigurationApplyConfiguration) WithOpaque(value *OpaqueDeviceConfigurationApplyConfiguration) *DeviceClassConfigurationApplyConfiguration { + b.DeviceConfigurationApplyConfiguration.Opaque = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceclassspec.go b/applyconfigurations/resource/v1beta2/deviceclassspec.go new file mode 100644 index 0000000000..c92a83e6b5 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceclassspec.go @@ -0,0 +1,58 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceClassSpecApplyConfiguration represents a declarative configuration of the DeviceClassSpec type for use +// with apply. +type DeviceClassSpecApplyConfiguration struct { + Selectors []DeviceSelectorApplyConfiguration `json:"selectors,omitempty"` + Config []DeviceClassConfigurationApplyConfiguration `json:"config,omitempty"` +} + +// DeviceClassSpecApplyConfiguration constructs a declarative configuration of the DeviceClassSpec type for use with +// apply. +func DeviceClassSpec() *DeviceClassSpecApplyConfiguration { + return &DeviceClassSpecApplyConfiguration{} +} + +// WithSelectors adds the given value to the Selectors field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Selectors field. +func (b *DeviceClassSpecApplyConfiguration) WithSelectors(values ...*DeviceSelectorApplyConfiguration) *DeviceClassSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSelectors") + } + b.Selectors = append(b.Selectors, *values[i]) + } + return b +} + +// WithConfig adds the given value to the Config field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Config field. +func (b *DeviceClassSpecApplyConfiguration) WithConfig(values ...*DeviceClassConfigurationApplyConfiguration) *DeviceClassSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConfig") + } + b.Config = append(b.Config, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceconfiguration.go b/applyconfigurations/resource/v1beta2/deviceconfiguration.go new file mode 100644 index 0000000000..2032433f34 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceconfiguration.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceConfigurationApplyConfiguration represents a declarative configuration of the DeviceConfiguration type for use +// with apply. +type DeviceConfigurationApplyConfiguration struct { + Opaque *OpaqueDeviceConfigurationApplyConfiguration `json:"opaque,omitempty"` +} + +// DeviceConfigurationApplyConfiguration constructs a declarative configuration of the DeviceConfiguration type for use with +// apply. +func DeviceConfiguration() *DeviceConfigurationApplyConfiguration { + return &DeviceConfigurationApplyConfiguration{} +} + +// WithOpaque sets the Opaque field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Opaque field is set to the value of the last call. +func (b *DeviceConfigurationApplyConfiguration) WithOpaque(value *OpaqueDeviceConfigurationApplyConfiguration) *DeviceConfigurationApplyConfiguration { + b.Opaque = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceconstraint.go b/applyconfigurations/resource/v1beta2/deviceconstraint.go new file mode 100644 index 0000000000..460ffdd080 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceconstraint.go @@ -0,0 +1,54 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" +) + +// DeviceConstraintApplyConfiguration represents a declarative configuration of the DeviceConstraint type for use +// with apply. +type DeviceConstraintApplyConfiguration struct { + Requests []string `json:"requests,omitempty"` + MatchAttribute *resourcev1beta2.FullyQualifiedName `json:"matchAttribute,omitempty"` +} + +// DeviceConstraintApplyConfiguration constructs a declarative configuration of the DeviceConstraint type for use with +// apply. +func DeviceConstraint() *DeviceConstraintApplyConfiguration { + return &DeviceConstraintApplyConfiguration{} +} + +// WithRequests adds the given value to the Requests field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Requests field. +func (b *DeviceConstraintApplyConfiguration) WithRequests(values ...string) *DeviceConstraintApplyConfiguration { + for i := range values { + b.Requests = append(b.Requests, values[i]) + } + return b +} + +// WithMatchAttribute sets the MatchAttribute field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the MatchAttribute field is set to the value of the last call. +func (b *DeviceConstraintApplyConfiguration) WithMatchAttribute(value resourcev1beta2.FullyQualifiedName) *DeviceConstraintApplyConfiguration { + b.MatchAttribute = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/devicecounterconsumption.go b/applyconfigurations/resource/v1beta2/devicecounterconsumption.go new file mode 100644 index 0000000000..9d6d0a8738 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/devicecounterconsumption.go @@ -0,0 +1,54 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceCounterConsumptionApplyConfiguration represents a declarative configuration of the DeviceCounterConsumption type for use +// with apply. +type DeviceCounterConsumptionApplyConfiguration struct { + CounterSet *string `json:"counterSet,omitempty"` + Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` +} + +// DeviceCounterConsumptionApplyConfiguration constructs a declarative configuration of the DeviceCounterConsumption type for use with +// apply. +func DeviceCounterConsumption() *DeviceCounterConsumptionApplyConfiguration { + return &DeviceCounterConsumptionApplyConfiguration{} +} + +// WithCounterSet sets the CounterSet field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CounterSet field is set to the value of the last call. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCounterSet(value string) *DeviceCounterConsumptionApplyConfiguration { + b.CounterSet = &value + return b +} + +// WithCounters puts the entries into the Counters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Counters field, +// overwriting an existing map entries in Counters field with the same key. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCounters(entries map[string]CounterApplyConfiguration) *DeviceCounterConsumptionApplyConfiguration { + if b.Counters == nil && len(entries) > 0 { + b.Counters = make(map[string]CounterApplyConfiguration, len(entries)) + } + for k, v := range entries { + b.Counters[k] = v + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/devicerequest.go b/applyconfigurations/resource/v1beta2/devicerequest.go new file mode 100644 index 0000000000..426c974876 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/devicerequest.go @@ -0,0 +1,62 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceRequestApplyConfiguration represents a declarative configuration of the DeviceRequest type for use +// with apply. +type DeviceRequestApplyConfiguration struct { + Name *string `json:"name,omitempty"` + Exactly *ExactDeviceRequestApplyConfiguration `json:"exactly,omitempty"` + FirstAvailable []DeviceSubRequestApplyConfiguration `json:"firstAvailable,omitempty"` +} + +// DeviceRequestApplyConfiguration constructs a declarative configuration of the DeviceRequest type for use with +// apply. +func DeviceRequest() *DeviceRequestApplyConfiguration { + return &DeviceRequestApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *DeviceRequestApplyConfiguration) WithName(value string) *DeviceRequestApplyConfiguration { + b.Name = &value + return b +} + +// WithExactly sets the Exactly field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Exactly field is set to the value of the last call. +func (b *DeviceRequestApplyConfiguration) WithExactly(value *ExactDeviceRequestApplyConfiguration) *DeviceRequestApplyConfiguration { + b.Exactly = value + return b +} + +// WithFirstAvailable adds the given value to the FirstAvailable field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the FirstAvailable field. +func (b *DeviceRequestApplyConfiguration) WithFirstAvailable(values ...*DeviceSubRequestApplyConfiguration) *DeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithFirstAvailable") + } + b.FirstAvailable = append(b.FirstAvailable, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/devicerequestallocationresult.go b/applyconfigurations/resource/v1beta2/devicerequestallocationresult.go new file mode 100644 index 0000000000..ab826812e6 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/devicerequestallocationresult.go @@ -0,0 +1,89 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceRequestAllocationResultApplyConfiguration represents a declarative configuration of the DeviceRequestAllocationResult type for use +// with apply. +type DeviceRequestAllocationResultApplyConfiguration struct { + Request *string `json:"request,omitempty"` + Driver *string `json:"driver,omitempty"` + Pool *string `json:"pool,omitempty"` + Device *string `json:"device,omitempty"` + AdminAccess *bool `json:"adminAccess,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` +} + +// DeviceRequestAllocationResultApplyConfiguration constructs a declarative configuration of the DeviceRequestAllocationResult type for use with +// apply. +func DeviceRequestAllocationResult() *DeviceRequestAllocationResultApplyConfiguration { + return &DeviceRequestAllocationResultApplyConfiguration{} +} + +// WithRequest sets the Request field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Request field is set to the value of the last call. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithRequest(value string) *DeviceRequestAllocationResultApplyConfiguration { + b.Request = &value + return b +} + +// WithDriver sets the Driver field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Driver field is set to the value of the last call. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithDriver(value string) *DeviceRequestAllocationResultApplyConfiguration { + b.Driver = &value + return b +} + +// WithPool sets the Pool field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Pool field is set to the value of the last call. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithPool(value string) *DeviceRequestAllocationResultApplyConfiguration { + b.Pool = &value + return b +} + +// WithDevice sets the Device field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Device field is set to the value of the last call. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithDevice(value string) *DeviceRequestAllocationResultApplyConfiguration { + b.Device = &value + return b +} + +// WithAdminAccess sets the AdminAccess field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AdminAccess field is set to the value of the last call. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithAdminAccess(value bool) *DeviceRequestAllocationResultApplyConfiguration { + b.AdminAccess = &value + return b +} + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceRequestAllocationResultApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/deviceselector.go b/applyconfigurations/resource/v1beta2/deviceselector.go new file mode 100644 index 0000000000..fd064e5f6c --- /dev/null +++ b/applyconfigurations/resource/v1beta2/deviceselector.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceSelectorApplyConfiguration represents a declarative configuration of the DeviceSelector type for use +// with apply. +type DeviceSelectorApplyConfiguration struct { + CEL *CELDeviceSelectorApplyConfiguration `json:"cel,omitempty"` +} + +// DeviceSelectorApplyConfiguration constructs a declarative configuration of the DeviceSelector type for use with +// apply. +func DeviceSelector() *DeviceSelectorApplyConfiguration { + return &DeviceSelectorApplyConfiguration{} +} + +// WithCEL sets the CEL field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CEL field is set to the value of the last call. +func (b *DeviceSelectorApplyConfiguration) WithCEL(value *CELDeviceSelectorApplyConfiguration) *DeviceSelectorApplyConfiguration { + b.CEL = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/devicesubrequest.go b/applyconfigurations/resource/v1beta2/devicesubrequest.go new file mode 100644 index 0000000000..aaf8600adf --- /dev/null +++ b/applyconfigurations/resource/v1beta2/devicesubrequest.go @@ -0,0 +1,98 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" +) + +// DeviceSubRequestApplyConfiguration represents a declarative configuration of the DeviceSubRequest type for use +// with apply. +type DeviceSubRequestApplyConfiguration struct { + Name *string `json:"name,omitempty"` + DeviceClassName *string `json:"deviceClassName,omitempty"` + Selectors []DeviceSelectorApplyConfiguration `json:"selectors,omitempty"` + AllocationMode *resourcev1beta2.DeviceAllocationMode `json:"allocationMode,omitempty"` + Count *int64 `json:"count,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` +} + +// DeviceSubRequestApplyConfiguration constructs a declarative configuration of the DeviceSubRequest type for use with +// apply. +func DeviceSubRequest() *DeviceSubRequestApplyConfiguration { + return &DeviceSubRequestApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithName(value string) *DeviceSubRequestApplyConfiguration { + b.Name = &value + return b +} + +// WithDeviceClassName sets the DeviceClassName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeviceClassName field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithDeviceClassName(value string) *DeviceSubRequestApplyConfiguration { + b.DeviceClassName = &value + return b +} + +// WithSelectors adds the given value to the Selectors field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Selectors field. +func (b *DeviceSubRequestApplyConfiguration) WithSelectors(values ...*DeviceSelectorApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSelectors") + } + b.Selectors = append(b.Selectors, *values[i]) + } + return b +} + +// WithAllocationMode sets the AllocationMode field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllocationMode field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithAllocationMode(value resourcev1beta2.DeviceAllocationMode) *DeviceSubRequestApplyConfiguration { + b.AllocationMode = &value + return b +} + +// WithCount sets the Count field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Count field is set to the value of the last call. +func (b *DeviceSubRequestApplyConfiguration) WithCount(value int64) *DeviceSubRequestApplyConfiguration { + b.Count = &value + return b +} + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *DeviceSubRequestApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/devicetaint.go b/applyconfigurations/resource/v1beta2/devicetaint.go new file mode 100644 index 0000000000..b21f98a152 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/devicetaint.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// DeviceTaintApplyConfiguration represents a declarative configuration of the DeviceTaint type for use +// with apply. +type DeviceTaintApplyConfiguration struct { + Key *string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` + Effect *resourcev1beta2.DeviceTaintEffect `json:"effect,omitempty"` + TimeAdded *v1.Time `json:"timeAdded,omitempty"` +} + +// DeviceTaintApplyConfiguration constructs a declarative configuration of the DeviceTaint type for use with +// apply. +func DeviceTaint() *DeviceTaintApplyConfiguration { + return &DeviceTaintApplyConfiguration{} +} + +// WithKey sets the Key field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Key field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithKey(value string) *DeviceTaintApplyConfiguration { + b.Key = &value + return b +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithValue(value string) *DeviceTaintApplyConfiguration { + b.Value = &value + return b +} + +// WithEffect sets the Effect field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Effect field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithEffect(value resourcev1beta2.DeviceTaintEffect) *DeviceTaintApplyConfiguration { + b.Effect = &value + return b +} + +// WithTimeAdded sets the TimeAdded field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TimeAdded field is set to the value of the last call. +func (b *DeviceTaintApplyConfiguration) WithTimeAdded(value v1.Time) *DeviceTaintApplyConfiguration { + b.TimeAdded = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/devicetoleration.go b/applyconfigurations/resource/v1beta2/devicetoleration.go new file mode 100644 index 0000000000..ae471233f4 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/devicetoleration.go @@ -0,0 +1,79 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" +) + +// DeviceTolerationApplyConfiguration represents a declarative configuration of the DeviceToleration type for use +// with apply. +type DeviceTolerationApplyConfiguration struct { + Key *string `json:"key,omitempty"` + Operator *resourcev1beta2.DeviceTolerationOperator `json:"operator,omitempty"` + Value *string `json:"value,omitempty"` + Effect *resourcev1beta2.DeviceTaintEffect `json:"effect,omitempty"` + TolerationSeconds *int64 `json:"tolerationSeconds,omitempty"` +} + +// DeviceTolerationApplyConfiguration constructs a declarative configuration of the DeviceToleration type for use with +// apply. +func DeviceToleration() *DeviceTolerationApplyConfiguration { + return &DeviceTolerationApplyConfiguration{} +} + +// WithKey sets the Key field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Key field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithKey(value string) *DeviceTolerationApplyConfiguration { + b.Key = &value + return b +} + +// WithOperator sets the Operator field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Operator field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithOperator(value resourcev1beta2.DeviceTolerationOperator) *DeviceTolerationApplyConfiguration { + b.Operator = &value + return b +} + +// WithValue sets the Value field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Value field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithValue(value string) *DeviceTolerationApplyConfiguration { + b.Value = &value + return b +} + +// WithEffect sets the Effect field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Effect field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithEffect(value resourcev1beta2.DeviceTaintEffect) *DeviceTolerationApplyConfiguration { + b.Effect = &value + return b +} + +// WithTolerationSeconds sets the TolerationSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TolerationSeconds field is set to the value of the last call. +func (b *DeviceTolerationApplyConfiguration) WithTolerationSeconds(value int64) *DeviceTolerationApplyConfiguration { + b.TolerationSeconds = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/exactdevicerequest.go b/applyconfigurations/resource/v1beta2/exactdevicerequest.go new file mode 100644 index 0000000000..2d7d7155e4 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/exactdevicerequest.go @@ -0,0 +1,98 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" +) + +// ExactDeviceRequestApplyConfiguration represents a declarative configuration of the ExactDeviceRequest type for use +// with apply. +type ExactDeviceRequestApplyConfiguration struct { + DeviceClassName *string `json:"deviceClassName,omitempty"` + Selectors []DeviceSelectorApplyConfiguration `json:"selectors,omitempty"` + AllocationMode *resourcev1beta2.DeviceAllocationMode `json:"allocationMode,omitempty"` + Count *int64 `json:"count,omitempty"` + AdminAccess *bool `json:"adminAccess,omitempty"` + Tolerations []DeviceTolerationApplyConfiguration `json:"tolerations,omitempty"` +} + +// ExactDeviceRequestApplyConfiguration constructs a declarative configuration of the ExactDeviceRequest type for use with +// apply. +func ExactDeviceRequest() *ExactDeviceRequestApplyConfiguration { + return &ExactDeviceRequestApplyConfiguration{} +} + +// WithDeviceClassName sets the DeviceClassName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeviceClassName field is set to the value of the last call. +func (b *ExactDeviceRequestApplyConfiguration) WithDeviceClassName(value string) *ExactDeviceRequestApplyConfiguration { + b.DeviceClassName = &value + return b +} + +// WithSelectors adds the given value to the Selectors field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Selectors field. +func (b *ExactDeviceRequestApplyConfiguration) WithSelectors(values ...*DeviceSelectorApplyConfiguration) *ExactDeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSelectors") + } + b.Selectors = append(b.Selectors, *values[i]) + } + return b +} + +// WithAllocationMode sets the AllocationMode field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllocationMode field is set to the value of the last call. +func (b *ExactDeviceRequestApplyConfiguration) WithAllocationMode(value resourcev1beta2.DeviceAllocationMode) *ExactDeviceRequestApplyConfiguration { + b.AllocationMode = &value + return b +} + +// WithCount sets the Count field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Count field is set to the value of the last call. +func (b *ExactDeviceRequestApplyConfiguration) WithCount(value int64) *ExactDeviceRequestApplyConfiguration { + b.Count = &value + return b +} + +// WithAdminAccess sets the AdminAccess field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AdminAccess field is set to the value of the last call. +func (b *ExactDeviceRequestApplyConfiguration) WithAdminAccess(value bool) *ExactDeviceRequestApplyConfiguration { + b.AdminAccess = &value + return b +} + +// WithTolerations adds the given value to the Tolerations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tolerations field. +func (b *ExactDeviceRequestApplyConfiguration) WithTolerations(values ...*DeviceTolerationApplyConfiguration) *ExactDeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTolerations") + } + b.Tolerations = append(b.Tolerations, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/networkdevicedata.go b/applyconfigurations/resource/v1beta2/networkdevicedata.go new file mode 100644 index 0000000000..9b0944f8f2 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/networkdevicedata.go @@ -0,0 +1,59 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// NetworkDeviceDataApplyConfiguration represents a declarative configuration of the NetworkDeviceData type for use +// with apply. +type NetworkDeviceDataApplyConfiguration struct { + InterfaceName *string `json:"interfaceName,omitempty"` + IPs []string `json:"ips,omitempty"` + HardwareAddress *string `json:"hardwareAddress,omitempty"` +} + +// NetworkDeviceDataApplyConfiguration constructs a declarative configuration of the NetworkDeviceData type for use with +// apply. +func NetworkDeviceData() *NetworkDeviceDataApplyConfiguration { + return &NetworkDeviceDataApplyConfiguration{} +} + +// WithInterfaceName sets the InterfaceName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the InterfaceName field is set to the value of the last call. +func (b *NetworkDeviceDataApplyConfiguration) WithInterfaceName(value string) *NetworkDeviceDataApplyConfiguration { + b.InterfaceName = &value + return b +} + +// WithIPs adds the given value to the IPs field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the IPs field. +func (b *NetworkDeviceDataApplyConfiguration) WithIPs(values ...string) *NetworkDeviceDataApplyConfiguration { + for i := range values { + b.IPs = append(b.IPs, values[i]) + } + return b +} + +// WithHardwareAddress sets the HardwareAddress field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the HardwareAddress field is set to the value of the last call. +func (b *NetworkDeviceDataApplyConfiguration) WithHardwareAddress(value string) *NetworkDeviceDataApplyConfiguration { + b.HardwareAddress = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/opaquedeviceconfiguration.go b/applyconfigurations/resource/v1beta2/opaquedeviceconfiguration.go new file mode 100644 index 0000000000..aa8fe43f3e --- /dev/null +++ b/applyconfigurations/resource/v1beta2/opaquedeviceconfiguration.go @@ -0,0 +1,52 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// OpaqueDeviceConfigurationApplyConfiguration represents a declarative configuration of the OpaqueDeviceConfiguration type for use +// with apply. +type OpaqueDeviceConfigurationApplyConfiguration struct { + Driver *string `json:"driver,omitempty"` + Parameters *runtime.RawExtension `json:"parameters,omitempty"` +} + +// OpaqueDeviceConfigurationApplyConfiguration constructs a declarative configuration of the OpaqueDeviceConfiguration type for use with +// apply. +func OpaqueDeviceConfiguration() *OpaqueDeviceConfigurationApplyConfiguration { + return &OpaqueDeviceConfigurationApplyConfiguration{} +} + +// WithDriver sets the Driver field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Driver field is set to the value of the last call. +func (b *OpaqueDeviceConfigurationApplyConfiguration) WithDriver(value string) *OpaqueDeviceConfigurationApplyConfiguration { + b.Driver = &value + return b +} + +// WithParameters sets the Parameters field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Parameters field is set to the value of the last call. +func (b *OpaqueDeviceConfigurationApplyConfiguration) WithParameters(value runtime.RawExtension) *OpaqueDeviceConfigurationApplyConfiguration { + b.Parameters = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/resourceclaim.go b/applyconfigurations/resource/v1beta2/resourceclaim.go new file mode 100644 index 0000000000..65b3a6e0bb --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceclaim.go @@ -0,0 +1,264 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ResourceClaimApplyConfiguration represents a declarative configuration of the ResourceClaim type for use +// with apply. +type ResourceClaimApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *ResourceClaimSpecApplyConfiguration `json:"spec,omitempty"` + Status *ResourceClaimStatusApplyConfiguration `json:"status,omitempty"` +} + +// ResourceClaim constructs a declarative configuration of the ResourceClaim type for use with +// apply. +func ResourceClaim(name, namespace string) *ResourceClaimApplyConfiguration { + b := &ResourceClaimApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("ResourceClaim") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b +} + +// ExtractResourceClaim extracts the applied configuration owned by fieldManager from +// resourceClaim. If no managedFields are found in resourceClaim for fieldManager, a +// ResourceClaimApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// resourceClaim must be a unmodified ResourceClaim API object that was retrieved from the Kubernetes API. +// ExtractResourceClaim provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractResourceClaim(resourceClaim *resourcev1beta2.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error) { + return extractResourceClaim(resourceClaim, fieldManager, "") +} + +// ExtractResourceClaimStatus is the same as ExtractResourceClaim except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractResourceClaimStatus(resourceClaim *resourcev1beta2.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error) { + return extractResourceClaim(resourceClaim, fieldManager, "status") +} + +func extractResourceClaim(resourceClaim *resourcev1beta2.ResourceClaim, fieldManager string, subresource string) (*ResourceClaimApplyConfiguration, error) { + b := &ResourceClaimApplyConfiguration{} + err := managedfields.ExtractInto(resourceClaim, internal.Parser().Type("io.k8s.api.resource.v1beta2.ResourceClaim"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(resourceClaim.Name) + b.WithNamespace(resourceClaim.Namespace) + + b.WithKind("ResourceClaim") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithKind(value string) *ResourceClaimApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithAPIVersion(value string) *ResourceClaimApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithName(value string) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithGenerateName(value string) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithNamespace(value string) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithUID(value types.UID) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithResourceVersion(value string) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithGeneration(value int64) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ResourceClaimApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ResourceClaimApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ResourceClaimApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ResourceClaimApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ResourceClaimApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithSpec(value *ResourceClaimSpecApplyConfiguration) *ResourceClaimApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *ResourceClaimApplyConfiguration) WithStatus(value *ResourceClaimStatusApplyConfiguration) *ResourceClaimApplyConfiguration { + b.Status = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ResourceClaimApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/resource/v1beta2/resourceclaimconsumerreference.go b/applyconfigurations/resource/v1beta2/resourceclaimconsumerreference.go new file mode 100644 index 0000000000..b7824e8599 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceclaimconsumerreference.go @@ -0,0 +1,70 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + types "k8s.io/apimachinery/pkg/types" +) + +// ResourceClaimConsumerReferenceApplyConfiguration represents a declarative configuration of the ResourceClaimConsumerReference type for use +// with apply. +type ResourceClaimConsumerReferenceApplyConfiguration struct { + APIGroup *string `json:"apiGroup,omitempty"` + Resource *string `json:"resource,omitempty"` + Name *string `json:"name,omitempty"` + UID *types.UID `json:"uid,omitempty"` +} + +// ResourceClaimConsumerReferenceApplyConfiguration constructs a declarative configuration of the ResourceClaimConsumerReference type for use with +// apply. +func ResourceClaimConsumerReference() *ResourceClaimConsumerReferenceApplyConfiguration { + return &ResourceClaimConsumerReferenceApplyConfiguration{} +} + +// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIGroup field is set to the value of the last call. +func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithAPIGroup(value string) *ResourceClaimConsumerReferenceApplyConfiguration { + b.APIGroup = &value + return b +} + +// WithResource sets the Resource field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Resource field is set to the value of the last call. +func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithResource(value string) *ResourceClaimConsumerReferenceApplyConfiguration { + b.Resource = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithName(value string) *ResourceClaimConsumerReferenceApplyConfiguration { + b.Name = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithUID(value types.UID) *ResourceClaimConsumerReferenceApplyConfiguration { + b.UID = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/resourceclaimspec.go b/applyconfigurations/resource/v1beta2/resourceclaimspec.go new file mode 100644 index 0000000000..e1fce17157 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceclaimspec.go @@ -0,0 +1,39 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// ResourceClaimSpecApplyConfiguration represents a declarative configuration of the ResourceClaimSpec type for use +// with apply. +type ResourceClaimSpecApplyConfiguration struct { + Devices *DeviceClaimApplyConfiguration `json:"devices,omitempty"` +} + +// ResourceClaimSpecApplyConfiguration constructs a declarative configuration of the ResourceClaimSpec type for use with +// apply. +func ResourceClaimSpec() *ResourceClaimSpecApplyConfiguration { + return &ResourceClaimSpecApplyConfiguration{} +} + +// WithDevices sets the Devices field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Devices field is set to the value of the last call. +func (b *ResourceClaimSpecApplyConfiguration) WithDevices(value *DeviceClaimApplyConfiguration) *ResourceClaimSpecApplyConfiguration { + b.Devices = value + return b +} diff --git a/applyconfigurations/resource/v1beta2/resourceclaimstatus.go b/applyconfigurations/resource/v1beta2/resourceclaimstatus.go new file mode 100644 index 0000000000..a3e7ae258f --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceclaimstatus.go @@ -0,0 +1,67 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// ResourceClaimStatusApplyConfiguration represents a declarative configuration of the ResourceClaimStatus type for use +// with apply. +type ResourceClaimStatusApplyConfiguration struct { + Allocation *AllocationResultApplyConfiguration `json:"allocation,omitempty"` + ReservedFor []ResourceClaimConsumerReferenceApplyConfiguration `json:"reservedFor,omitempty"` + Devices []AllocatedDeviceStatusApplyConfiguration `json:"devices,omitempty"` +} + +// ResourceClaimStatusApplyConfiguration constructs a declarative configuration of the ResourceClaimStatus type for use with +// apply. +func ResourceClaimStatus() *ResourceClaimStatusApplyConfiguration { + return &ResourceClaimStatusApplyConfiguration{} +} + +// WithAllocation sets the Allocation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Allocation field is set to the value of the last call. +func (b *ResourceClaimStatusApplyConfiguration) WithAllocation(value *AllocationResultApplyConfiguration) *ResourceClaimStatusApplyConfiguration { + b.Allocation = value + return b +} + +// WithReservedFor adds the given value to the ReservedFor field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ReservedFor field. +func (b *ResourceClaimStatusApplyConfiguration) WithReservedFor(values ...*ResourceClaimConsumerReferenceApplyConfiguration) *ResourceClaimStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithReservedFor") + } + b.ReservedFor = append(b.ReservedFor, *values[i]) + } + return b +} + +// WithDevices adds the given value to the Devices field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Devices field. +func (b *ResourceClaimStatusApplyConfiguration) WithDevices(values ...*AllocatedDeviceStatusApplyConfiguration) *ResourceClaimStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDevices") + } + b.Devices = append(b.Devices, *values[i]) + } + return b +} diff --git a/applyconfigurations/resource/v1beta2/resourceclaimtemplate.go b/applyconfigurations/resource/v1beta2/resourceclaimtemplate.go new file mode 100644 index 0000000000..eb1f3ca060 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceclaimtemplate.go @@ -0,0 +1,255 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ResourceClaimTemplateApplyConfiguration represents a declarative configuration of the ResourceClaimTemplate type for use +// with apply. +type ResourceClaimTemplateApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *ResourceClaimTemplateSpecApplyConfiguration `json:"spec,omitempty"` +} + +// ResourceClaimTemplate constructs a declarative configuration of the ResourceClaimTemplate type for use with +// apply. +func ResourceClaimTemplate(name, namespace string) *ResourceClaimTemplateApplyConfiguration { + b := &ResourceClaimTemplateApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("ResourceClaimTemplate") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b +} + +// ExtractResourceClaimTemplate extracts the applied configuration owned by fieldManager from +// resourceClaimTemplate. If no managedFields are found in resourceClaimTemplate for fieldManager, a +// ResourceClaimTemplateApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// resourceClaimTemplate must be a unmodified ResourceClaimTemplate API object that was retrieved from the Kubernetes API. +// ExtractResourceClaimTemplate provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractResourceClaimTemplate(resourceClaimTemplate *resourcev1beta2.ResourceClaimTemplate, fieldManager string) (*ResourceClaimTemplateApplyConfiguration, error) { + return extractResourceClaimTemplate(resourceClaimTemplate, fieldManager, "") +} + +// ExtractResourceClaimTemplateStatus is the same as ExtractResourceClaimTemplate except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractResourceClaimTemplateStatus(resourceClaimTemplate *resourcev1beta2.ResourceClaimTemplate, fieldManager string) (*ResourceClaimTemplateApplyConfiguration, error) { + return extractResourceClaimTemplate(resourceClaimTemplate, fieldManager, "status") +} + +func extractResourceClaimTemplate(resourceClaimTemplate *resourcev1beta2.ResourceClaimTemplate, fieldManager string, subresource string) (*ResourceClaimTemplateApplyConfiguration, error) { + b := &ResourceClaimTemplateApplyConfiguration{} + err := managedfields.ExtractInto(resourceClaimTemplate, internal.Parser().Type("io.k8s.api.resource.v1beta2.ResourceClaimTemplate"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(resourceClaimTemplate.Name) + b.WithNamespace(resourceClaimTemplate.Namespace) + + b.WithKind("ResourceClaimTemplate") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithKind(value string) *ResourceClaimTemplateApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithAPIVersion(value string) *ResourceClaimTemplateApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithName(value string) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithGenerateName(value string) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithNamespace(value string) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithUID(value types.UID) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithResourceVersion(value string) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithGeneration(value int64) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ResourceClaimTemplateApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ResourceClaimTemplateApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ResourceClaimTemplateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ResourceClaimTemplateApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimTemplateApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ResourceClaimTemplateApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *ResourceClaimTemplateApplyConfiguration) WithSpec(value *ResourceClaimTemplateSpecApplyConfiguration) *ResourceClaimTemplateApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ResourceClaimTemplateApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/resource/v1beta2/resourceclaimtemplatespec.go b/applyconfigurations/resource/v1beta2/resourceclaimtemplatespec.go new file mode 100644 index 0000000000..c2aef66c7d --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceclaimtemplatespec.go @@ -0,0 +1,194 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ResourceClaimTemplateSpecApplyConfiguration represents a declarative configuration of the ResourceClaimTemplateSpec type for use +// with apply. +type ResourceClaimTemplateSpecApplyConfiguration struct { + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *ResourceClaimSpecApplyConfiguration `json:"spec,omitempty"` +} + +// ResourceClaimTemplateSpecApplyConfiguration constructs a declarative configuration of the ResourceClaimTemplateSpec type for use with +// apply. +func ResourceClaimTemplateSpec() *ResourceClaimTemplateSpecApplyConfiguration { + return &ResourceClaimTemplateSpecApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithName(value string) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithGenerateName(value string) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithNamespace(value string) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithUID(value types.UID) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithResourceVersion(value string) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithGeneration(value int64) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimTemplateSpecApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ResourceClaimTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *ResourceClaimTemplateSpecApplyConfiguration) WithSpec(value *ResourceClaimSpecApplyConfiguration) *ResourceClaimTemplateSpecApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ResourceClaimTemplateSpecApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/resource/v1beta2/resourcepool.go b/applyconfigurations/resource/v1beta2/resourcepool.go new file mode 100644 index 0000000000..6923085d6b --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourcepool.go @@ -0,0 +1,57 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// ResourcePoolApplyConfiguration represents a declarative configuration of the ResourcePool type for use +// with apply. +type ResourcePoolApplyConfiguration struct { + Name *string `json:"name,omitempty"` + Generation *int64 `json:"generation,omitempty"` + ResourceSliceCount *int64 `json:"resourceSliceCount,omitempty"` +} + +// ResourcePoolApplyConfiguration constructs a declarative configuration of the ResourcePool type for use with +// apply. +func ResourcePool() *ResourcePoolApplyConfiguration { + return &ResourcePoolApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ResourcePoolApplyConfiguration) WithName(value string) *ResourcePoolApplyConfiguration { + b.Name = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *ResourcePoolApplyConfiguration) WithGeneration(value int64) *ResourcePoolApplyConfiguration { + b.Generation = &value + return b +} + +// WithResourceSliceCount sets the ResourceSliceCount field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceSliceCount field is set to the value of the last call. +func (b *ResourcePoolApplyConfiguration) WithResourceSliceCount(value int64) *ResourcePoolApplyConfiguration { + b.ResourceSliceCount = &value + return b +} diff --git a/applyconfigurations/resource/v1beta2/resourceslice.go b/applyconfigurations/resource/v1beta2/resourceslice.go new file mode 100644 index 0000000000..7333d709de --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceslice.go @@ -0,0 +1,253 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ResourceSliceApplyConfiguration represents a declarative configuration of the ResourceSlice type for use +// with apply. +type ResourceSliceApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *ResourceSliceSpecApplyConfiguration `json:"spec,omitempty"` +} + +// ResourceSlice constructs a declarative configuration of the ResourceSlice type for use with +// apply. +func ResourceSlice(name string) *ResourceSliceApplyConfiguration { + b := &ResourceSliceApplyConfiguration{} + b.WithName(name) + b.WithKind("ResourceSlice") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b +} + +// ExtractResourceSlice extracts the applied configuration owned by fieldManager from +// resourceSlice. If no managedFields are found in resourceSlice for fieldManager, a +// ResourceSliceApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// resourceSlice must be a unmodified ResourceSlice API object that was retrieved from the Kubernetes API. +// ExtractResourceSlice provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractResourceSlice(resourceSlice *resourcev1beta2.ResourceSlice, fieldManager string) (*ResourceSliceApplyConfiguration, error) { + return extractResourceSlice(resourceSlice, fieldManager, "") +} + +// ExtractResourceSliceStatus is the same as ExtractResourceSlice except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractResourceSliceStatus(resourceSlice *resourcev1beta2.ResourceSlice, fieldManager string) (*ResourceSliceApplyConfiguration, error) { + return extractResourceSlice(resourceSlice, fieldManager, "status") +} + +func extractResourceSlice(resourceSlice *resourcev1beta2.ResourceSlice, fieldManager string, subresource string) (*ResourceSliceApplyConfiguration, error) { + b := &ResourceSliceApplyConfiguration{} + err := managedfields.ExtractInto(resourceSlice, internal.Parser().Type("io.k8s.api.resource.v1beta2.ResourceSlice"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(resourceSlice.Name) + + b.WithKind("ResourceSlice") + b.WithAPIVersion("resource.k8s.io/v1beta2") + return b, nil +} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithKind(value string) *ResourceSliceApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithAPIVersion(value string) *ResourceSliceApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithName(value string) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithGenerateName(value string) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithNamespace(value string) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithUID(value types.UID) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithResourceVersion(value string) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithGeneration(value int64) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ResourceSliceApplyConfiguration) WithLabels(entries map[string]string) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ResourceSliceApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ResourceSliceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ResourceSliceApplyConfiguration) WithFinalizers(values ...string) *ResourceSliceApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ResourceSliceApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *ResourceSliceApplyConfiguration) WithSpec(value *ResourceSliceSpecApplyConfiguration) *ResourceSliceApplyConfiguration { + b.Spec = value + return b +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ResourceSliceApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} diff --git a/applyconfigurations/resource/v1beta2/resourceslicespec.go b/applyconfigurations/resource/v1beta2/resourceslicespec.go new file mode 100644 index 0000000000..5a000829f9 --- /dev/null +++ b/applyconfigurations/resource/v1beta2/resourceslicespec.go @@ -0,0 +1,116 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + v1 "k8s.io/client-go/applyconfigurations/core/v1" +) + +// ResourceSliceSpecApplyConfiguration represents a declarative configuration of the ResourceSliceSpec type for use +// with apply. +type ResourceSliceSpecApplyConfiguration struct { + Driver *string `json:"driver,omitempty"` + Pool *ResourcePoolApplyConfiguration `json:"pool,omitempty"` + NodeName *string `json:"nodeName,omitempty"` + NodeSelector *v1.NodeSelectorApplyConfiguration `json:"nodeSelector,omitempty"` + AllNodes *bool `json:"allNodes,omitempty"` + Devices []DeviceApplyConfiguration `json:"devices,omitempty"` + PerDeviceNodeSelection *bool `json:"perDeviceNodeSelection,omitempty"` + SharedCounters []CounterSetApplyConfiguration `json:"sharedCounters,omitempty"` +} + +// ResourceSliceSpecApplyConfiguration constructs a declarative configuration of the ResourceSliceSpec type for use with +// apply. +func ResourceSliceSpec() *ResourceSliceSpecApplyConfiguration { + return &ResourceSliceSpecApplyConfiguration{} +} + +// WithDriver sets the Driver field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Driver field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithDriver(value string) *ResourceSliceSpecApplyConfiguration { + b.Driver = &value + return b +} + +// WithPool sets the Pool field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Pool field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithPool(value *ResourcePoolApplyConfiguration) *ResourceSliceSpecApplyConfiguration { + b.Pool = value + return b +} + +// WithNodeName sets the NodeName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeName field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithNodeName(value string) *ResourceSliceSpecApplyConfiguration { + b.NodeName = &value + return b +} + +// WithNodeSelector sets the NodeSelector field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeSelector field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithNodeSelector(value *v1.NodeSelectorApplyConfiguration) *ResourceSliceSpecApplyConfiguration { + b.NodeSelector = value + return b +} + +// WithAllNodes sets the AllNodes field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AllNodes field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithAllNodes(value bool) *ResourceSliceSpecApplyConfiguration { + b.AllNodes = &value + return b +} + +// WithDevices adds the given value to the Devices field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Devices field. +func (b *ResourceSliceSpecApplyConfiguration) WithDevices(values ...*DeviceApplyConfiguration) *ResourceSliceSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDevices") + } + b.Devices = append(b.Devices, *values[i]) + } + return b +} + +// WithPerDeviceNodeSelection sets the PerDeviceNodeSelection field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PerDeviceNodeSelection field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithPerDeviceNodeSelection(value bool) *ResourceSliceSpecApplyConfiguration { + b.PerDeviceNodeSelection = &value + return b +} + +// WithSharedCounters adds the given value to the SharedCounters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SharedCounters field. +func (b *ResourceSliceSpecApplyConfiguration) WithSharedCounters(values ...*CounterSetApplyConfiguration) *ResourceSliceSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSharedCounters") + } + b.SharedCounters = append(b.SharedCounters, *values[i]) + } + return b +} diff --git a/applyconfigurations/storage/v1/csidriverspec.go b/applyconfigurations/storage/v1/csidriverspec.go index 1b58c6db89..fc6f2fbf94 100644 --- a/applyconfigurations/storage/v1/csidriverspec.go +++ b/applyconfigurations/storage/v1/csidriverspec.go @@ -25,14 +25,15 @@ import ( // CSIDriverSpecApplyConfiguration represents a declarative configuration of the CSIDriverSpec type for use // with apply. type CSIDriverSpecApplyConfiguration struct { - AttachRequired *bool `json:"attachRequired,omitempty"` - PodInfoOnMount *bool `json:"podInfoOnMount,omitempty"` - VolumeLifecycleModes []storagev1.VolumeLifecycleMode `json:"volumeLifecycleModes,omitempty"` - StorageCapacity *bool `json:"storageCapacity,omitempty"` - FSGroupPolicy *storagev1.FSGroupPolicy `json:"fsGroupPolicy,omitempty"` - TokenRequests []TokenRequestApplyConfiguration `json:"tokenRequests,omitempty"` - RequiresRepublish *bool `json:"requiresRepublish,omitempty"` - SELinuxMount *bool `json:"seLinuxMount,omitempty"` + AttachRequired *bool `json:"attachRequired,omitempty"` + PodInfoOnMount *bool `json:"podInfoOnMount,omitempty"` + VolumeLifecycleModes []storagev1.VolumeLifecycleMode `json:"volumeLifecycleModes,omitempty"` + StorageCapacity *bool `json:"storageCapacity,omitempty"` + FSGroupPolicy *storagev1.FSGroupPolicy `json:"fsGroupPolicy,omitempty"` + TokenRequests []TokenRequestApplyConfiguration `json:"tokenRequests,omitempty"` + RequiresRepublish *bool `json:"requiresRepublish,omitempty"` + SELinuxMount *bool `json:"seLinuxMount,omitempty"` + NodeAllocatableUpdatePeriodSeconds *int64 `json:"nodeAllocatableUpdatePeriodSeconds,omitempty"` } // CSIDriverSpecApplyConfiguration constructs a declarative configuration of the CSIDriverSpec type for use with @@ -111,3 +112,11 @@ func (b *CSIDriverSpecApplyConfiguration) WithSELinuxMount(value bool) *CSIDrive b.SELinuxMount = &value return b } + +// WithNodeAllocatableUpdatePeriodSeconds sets the NodeAllocatableUpdatePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeAllocatableUpdatePeriodSeconds field is set to the value of the last call. +func (b *CSIDriverSpecApplyConfiguration) WithNodeAllocatableUpdatePeriodSeconds(value int64) *CSIDriverSpecApplyConfiguration { + b.NodeAllocatableUpdatePeriodSeconds = &value + return b +} diff --git a/applyconfigurations/storage/v1/volumeerror.go b/applyconfigurations/storage/v1/volumeerror.go index c16c5c3af3..9becf77268 100644 --- a/applyconfigurations/storage/v1/volumeerror.go +++ b/applyconfigurations/storage/v1/volumeerror.go @@ -25,8 +25,9 @@ import ( // VolumeErrorApplyConfiguration represents a declarative configuration of the VolumeError type for use // with apply. type VolumeErrorApplyConfiguration struct { - Time *metav1.Time `json:"time,omitempty"` - Message *string `json:"message,omitempty"` + Time *metav1.Time `json:"time,omitempty"` + Message *string `json:"message,omitempty"` + ErrorCode *int32 `json:"errorCode,omitempty"` } // VolumeErrorApplyConfiguration constructs a declarative configuration of the VolumeError type for use with @@ -50,3 +51,11 @@ func (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorAp b.Message = &value return b } + +// WithErrorCode sets the ErrorCode field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ErrorCode field is set to the value of the last call. +func (b *VolumeErrorApplyConfiguration) WithErrorCode(value int32) *VolumeErrorApplyConfiguration { + b.ErrorCode = &value + return b +} diff --git a/applyconfigurations/storage/v1alpha1/volumeerror.go b/applyconfigurations/storage/v1alpha1/volumeerror.go index ef8f6bbe64..19e5275105 100644 --- a/applyconfigurations/storage/v1alpha1/volumeerror.go +++ b/applyconfigurations/storage/v1alpha1/volumeerror.go @@ -25,8 +25,9 @@ import ( // VolumeErrorApplyConfiguration represents a declarative configuration of the VolumeError type for use // with apply. type VolumeErrorApplyConfiguration struct { - Time *v1.Time `json:"time,omitempty"` - Message *string `json:"message,omitempty"` + Time *v1.Time `json:"time,omitempty"` + Message *string `json:"message,omitempty"` + ErrorCode *int32 `json:"errorCode,omitempty"` } // VolumeErrorApplyConfiguration constructs a declarative configuration of the VolumeError type for use with @@ -50,3 +51,11 @@ func (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorAp b.Message = &value return b } + +// WithErrorCode sets the ErrorCode field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ErrorCode field is set to the value of the last call. +func (b *VolumeErrorApplyConfiguration) WithErrorCode(value int32) *VolumeErrorApplyConfiguration { + b.ErrorCode = &value + return b +} diff --git a/applyconfigurations/storage/v1beta1/csidriverspec.go b/applyconfigurations/storage/v1beta1/csidriverspec.go index e62fe58883..b1c9ec6d12 100644 --- a/applyconfigurations/storage/v1beta1/csidriverspec.go +++ b/applyconfigurations/storage/v1beta1/csidriverspec.go @@ -25,14 +25,15 @@ import ( // CSIDriverSpecApplyConfiguration represents a declarative configuration of the CSIDriverSpec type for use // with apply. type CSIDriverSpecApplyConfiguration struct { - AttachRequired *bool `json:"attachRequired,omitempty"` - PodInfoOnMount *bool `json:"podInfoOnMount,omitempty"` - VolumeLifecycleModes []storagev1beta1.VolumeLifecycleMode `json:"volumeLifecycleModes,omitempty"` - StorageCapacity *bool `json:"storageCapacity,omitempty"` - FSGroupPolicy *storagev1beta1.FSGroupPolicy `json:"fsGroupPolicy,omitempty"` - TokenRequests []TokenRequestApplyConfiguration `json:"tokenRequests,omitempty"` - RequiresRepublish *bool `json:"requiresRepublish,omitempty"` - SELinuxMount *bool `json:"seLinuxMount,omitempty"` + AttachRequired *bool `json:"attachRequired,omitempty"` + PodInfoOnMount *bool `json:"podInfoOnMount,omitempty"` + VolumeLifecycleModes []storagev1beta1.VolumeLifecycleMode `json:"volumeLifecycleModes,omitempty"` + StorageCapacity *bool `json:"storageCapacity,omitempty"` + FSGroupPolicy *storagev1beta1.FSGroupPolicy `json:"fsGroupPolicy,omitempty"` + TokenRequests []TokenRequestApplyConfiguration `json:"tokenRequests,omitempty"` + RequiresRepublish *bool `json:"requiresRepublish,omitempty"` + SELinuxMount *bool `json:"seLinuxMount,omitempty"` + NodeAllocatableUpdatePeriodSeconds *int64 `json:"nodeAllocatableUpdatePeriodSeconds,omitempty"` } // CSIDriverSpecApplyConfiguration constructs a declarative configuration of the CSIDriverSpec type for use with @@ -111,3 +112,11 @@ func (b *CSIDriverSpecApplyConfiguration) WithSELinuxMount(value bool) *CSIDrive b.SELinuxMount = &value return b } + +// WithNodeAllocatableUpdatePeriodSeconds sets the NodeAllocatableUpdatePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NodeAllocatableUpdatePeriodSeconds field is set to the value of the last call. +func (b *CSIDriverSpecApplyConfiguration) WithNodeAllocatableUpdatePeriodSeconds(value int64) *CSIDriverSpecApplyConfiguration { + b.NodeAllocatableUpdatePeriodSeconds = &value + return b +} diff --git a/applyconfigurations/storage/v1beta1/volumeerror.go b/applyconfigurations/storage/v1beta1/volumeerror.go index fec1c9ade3..015bcd86d5 100644 --- a/applyconfigurations/storage/v1beta1/volumeerror.go +++ b/applyconfigurations/storage/v1beta1/volumeerror.go @@ -25,8 +25,9 @@ import ( // VolumeErrorApplyConfiguration represents a declarative configuration of the VolumeError type for use // with apply. type VolumeErrorApplyConfiguration struct { - Time *v1.Time `json:"time,omitempty"` - Message *string `json:"message,omitempty"` + Time *v1.Time `json:"time,omitempty"` + Message *string `json:"message,omitempty"` + ErrorCode *int32 `json:"errorCode,omitempty"` } // VolumeErrorApplyConfiguration constructs a declarative configuration of the VolumeError type for use with @@ -50,3 +51,11 @@ func (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorAp b.Message = &value return b } + +// WithErrorCode sets the ErrorCode field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ErrorCode field is set to the value of the last call. +func (b *VolumeErrorApplyConfiguration) WithErrorCode(value int32) *VolumeErrorApplyConfiguration { + b.ErrorCode = &value + return b +} diff --git a/applyconfigurations/utils.go b/applyconfigurations/utils.go index afbabac943..eec40ba9f1 100644 --- a/applyconfigurations/utils.go +++ b/applyconfigurations/utils.go @@ -62,6 +62,7 @@ import ( rbacv1beta1 "k8s.io/api/rbac/v1beta1" v1alpha3 "k8s.io/api/resource/v1alpha3" resourcev1beta1 "k8s.io/api/resource/v1beta1" + resourcev1beta2 "k8s.io/api/resource/v1beta2" schedulingv1 "k8s.io/api/scheduling/v1" schedulingv1alpha1 "k8s.io/api/scheduling/v1alpha1" schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" @@ -117,6 +118,7 @@ import ( applyconfigurationsrbacv1beta1 "k8s.io/client-go/applyconfigurations/rbac/v1beta1" resourcev1alpha3 "k8s.io/client-go/applyconfigurations/resource/v1alpha3" applyconfigurationsresourcev1beta1 "k8s.io/client-go/applyconfigurations/resource/v1beta1" + applyconfigurationsresourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" applyconfigurationsschedulingv1 "k8s.io/client-go/applyconfigurations/scheduling/v1" applyconfigurationsschedulingv1alpha1 "k8s.io/client-go/applyconfigurations/scheduling/v1alpha1" applyconfigurationsschedulingv1beta1 "k8s.io/client-go/applyconfigurations/scheduling/v1beta1" @@ -624,6 +626,10 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationscertificatesv1beta1.CertificateSigningRequestSpecApplyConfiguration{} case certificatesv1beta1.SchemeGroupVersion.WithKind("CertificateSigningRequestStatus"): return &applyconfigurationscertificatesv1beta1.CertificateSigningRequestStatusApplyConfiguration{} + case certificatesv1beta1.SchemeGroupVersion.WithKind("ClusterTrustBundle"): + return &applyconfigurationscertificatesv1beta1.ClusterTrustBundleApplyConfiguration{} + case certificatesv1beta1.SchemeGroupVersion.WithKind("ClusterTrustBundleSpec"): + return &applyconfigurationscertificatesv1beta1.ClusterTrustBundleSpecApplyConfiguration{} // Group=coordination.k8s.io, Version=v1 case coordinationv1.SchemeGroupVersion.WithKind("Lease"): @@ -640,6 +646,10 @@ func ForKind(kind schema.GroupVersionKind) interface{} { // Group=coordination.k8s.io, Version=v1beta1 case coordinationv1beta1.SchemeGroupVersion.WithKind("Lease"): return &applyconfigurationscoordinationv1beta1.LeaseApplyConfiguration{} + case coordinationv1beta1.SchemeGroupVersion.WithKind("LeaseCandidate"): + return &applyconfigurationscoordinationv1beta1.LeaseCandidateApplyConfiguration{} + case coordinationv1beta1.SchemeGroupVersion.WithKind("LeaseCandidateSpec"): + return &applyconfigurationscoordinationv1beta1.LeaseCandidateSpecApplyConfiguration{} case coordinationv1beta1.SchemeGroupVersion.WithKind("LeaseSpec"): return &applyconfigurationscoordinationv1beta1.LeaseSpecApplyConfiguration{} @@ -848,6 +858,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationscorev1.NodeSpecApplyConfiguration{} case corev1.SchemeGroupVersion.WithKind("NodeStatus"): return &applyconfigurationscorev1.NodeStatusApplyConfiguration{} + case corev1.SchemeGroupVersion.WithKind("NodeSwapStatus"): + return &applyconfigurationscorev1.NodeSwapStatusApplyConfiguration{} case corev1.SchemeGroupVersion.WithKind("NodeSystemInfo"): return &applyconfigurationscorev1.NodeSystemInfoApplyConfiguration{} case corev1.SchemeGroupVersion.WithKind("ObjectFieldSelector"): @@ -1052,6 +1064,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationsdiscoveryv1.EndpointPortApplyConfiguration{} case discoveryv1.SchemeGroupVersion.WithKind("EndpointSlice"): return &applyconfigurationsdiscoveryv1.EndpointSliceApplyConfiguration{} + case discoveryv1.SchemeGroupVersion.WithKind("ForNode"): + return &applyconfigurationsdiscoveryv1.ForNodeApplyConfiguration{} case discoveryv1.SchemeGroupVersion.WithKind("ForZone"): return &applyconfigurationsdiscoveryv1.ForZoneApplyConfiguration{} @@ -1066,6 +1080,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationsdiscoveryv1beta1.EndpointPortApplyConfiguration{} case discoveryv1beta1.SchemeGroupVersion.WithKind("EndpointSlice"): return &applyconfigurationsdiscoveryv1beta1.EndpointSliceApplyConfiguration{} + case discoveryv1beta1.SchemeGroupVersion.WithKind("ForNode"): + return &applyconfigurationsdiscoveryv1beta1.ForNodeApplyConfiguration{} case discoveryv1beta1.SchemeGroupVersion.WithKind("ForZone"): return &applyconfigurationsdiscoveryv1beta1.ForZoneApplyConfiguration{} @@ -1406,6 +1422,10 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationsnetworkingv1.IngressStatusApplyConfiguration{} case networkingv1.SchemeGroupVersion.WithKind("IngressTLS"): return &applyconfigurationsnetworkingv1.IngressTLSApplyConfiguration{} + case networkingv1.SchemeGroupVersion.WithKind("IPAddress"): + return &applyconfigurationsnetworkingv1.IPAddressApplyConfiguration{} + case networkingv1.SchemeGroupVersion.WithKind("IPAddressSpec"): + return &applyconfigurationsnetworkingv1.IPAddressSpecApplyConfiguration{} case networkingv1.SchemeGroupVersion.WithKind("IPBlock"): return &applyconfigurationsnetworkingv1.IPBlockApplyConfiguration{} case networkingv1.SchemeGroupVersion.WithKind("NetworkPolicy"): @@ -1420,8 +1440,16 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationsnetworkingv1.NetworkPolicyPortApplyConfiguration{} case networkingv1.SchemeGroupVersion.WithKind("NetworkPolicySpec"): return &applyconfigurationsnetworkingv1.NetworkPolicySpecApplyConfiguration{} + case networkingv1.SchemeGroupVersion.WithKind("ParentReference"): + return &applyconfigurationsnetworkingv1.ParentReferenceApplyConfiguration{} case networkingv1.SchemeGroupVersion.WithKind("ServiceBackendPort"): return &applyconfigurationsnetworkingv1.ServiceBackendPortApplyConfiguration{} + case networkingv1.SchemeGroupVersion.WithKind("ServiceCIDR"): + return &applyconfigurationsnetworkingv1.ServiceCIDRApplyConfiguration{} + case networkingv1.SchemeGroupVersion.WithKind("ServiceCIDRSpec"): + return &applyconfigurationsnetworkingv1.ServiceCIDRSpecApplyConfiguration{} + case networkingv1.SchemeGroupVersion.WithKind("ServiceCIDRStatus"): + return &applyconfigurationsnetworkingv1.ServiceCIDRStatusApplyConfiguration{} // Group=networking.k8s.io, Version=v1alpha1 case networkingv1alpha1.SchemeGroupVersion.WithKind("IPAddress"): @@ -1590,6 +1618,10 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &resourcev1alpha3.BasicDeviceApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("CELDeviceSelector"): return &resourcev1alpha3.CELDeviceSelectorApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("Counter"): + return &resourcev1alpha3.CounterApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("CounterSet"): + return &resourcev1alpha3.CounterSetApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("Device"): return &resourcev1alpha3.DeviceApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("DeviceAllocationConfiguration"): @@ -1612,12 +1644,26 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &resourcev1alpha3.DeviceConfigurationApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("DeviceConstraint"): return &resourcev1alpha3.DeviceConstraintApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("DeviceCounterConsumption"): + return &resourcev1alpha3.DeviceCounterConsumptionApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("DeviceRequest"): return &resourcev1alpha3.DeviceRequestApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("DeviceRequestAllocationResult"): return &resourcev1alpha3.DeviceRequestAllocationResultApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("DeviceSelector"): return &resourcev1alpha3.DeviceSelectorApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("DeviceSubRequest"): + return &resourcev1alpha3.DeviceSubRequestApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("DeviceTaint"): + return &resourcev1alpha3.DeviceTaintApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("DeviceTaintRule"): + return &resourcev1alpha3.DeviceTaintRuleApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("DeviceTaintRuleSpec"): + return &resourcev1alpha3.DeviceTaintRuleSpecApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("DeviceTaintSelector"): + return &resourcev1alpha3.DeviceTaintSelectorApplyConfiguration{} + case v1alpha3.SchemeGroupVersion.WithKind("DeviceToleration"): + return &resourcev1alpha3.DeviceTolerationApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("NetworkDeviceData"): return &resourcev1alpha3.NetworkDeviceDataApplyConfiguration{} case v1alpha3.SchemeGroupVersion.WithKind("OpaqueDeviceConfiguration"): @@ -1650,6 +1696,10 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationsresourcev1beta1.BasicDeviceApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("CELDeviceSelector"): return &applyconfigurationsresourcev1beta1.CELDeviceSelectorApplyConfiguration{} + case resourcev1beta1.SchemeGroupVersion.WithKind("Counter"): + return &applyconfigurationsresourcev1beta1.CounterApplyConfiguration{} + case resourcev1beta1.SchemeGroupVersion.WithKind("CounterSet"): + return &applyconfigurationsresourcev1beta1.CounterSetApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("Device"): return &applyconfigurationsresourcev1beta1.DeviceApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceAllocationConfiguration"): @@ -1674,12 +1724,20 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &applyconfigurationsresourcev1beta1.DeviceConfigurationApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceConstraint"): return &applyconfigurationsresourcev1beta1.DeviceConstraintApplyConfiguration{} + case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceCounterConsumption"): + return &applyconfigurationsresourcev1beta1.DeviceCounterConsumptionApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceRequest"): return &applyconfigurationsresourcev1beta1.DeviceRequestApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceRequestAllocationResult"): return &applyconfigurationsresourcev1beta1.DeviceRequestAllocationResultApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceSelector"): return &applyconfigurationsresourcev1beta1.DeviceSelectorApplyConfiguration{} + case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceSubRequest"): + return &applyconfigurationsresourcev1beta1.DeviceSubRequestApplyConfiguration{} + case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceTaint"): + return &applyconfigurationsresourcev1beta1.DeviceTaintApplyConfiguration{} + case resourcev1beta1.SchemeGroupVersion.WithKind("DeviceToleration"): + return &applyconfigurationsresourcev1beta1.DeviceTolerationApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("NetworkDeviceData"): return &applyconfigurationsresourcev1beta1.NetworkDeviceDataApplyConfiguration{} case resourcev1beta1.SchemeGroupVersion.WithKind("OpaqueDeviceConfiguration"): @@ -1703,6 +1761,80 @@ func ForKind(kind schema.GroupVersionKind) interface{} { case resourcev1beta1.SchemeGroupVersion.WithKind("ResourceSliceSpec"): return &applyconfigurationsresourcev1beta1.ResourceSliceSpecApplyConfiguration{} + // Group=resource.k8s.io, Version=v1beta2 + case resourcev1beta2.SchemeGroupVersion.WithKind("AllocatedDeviceStatus"): + return &applyconfigurationsresourcev1beta2.AllocatedDeviceStatusApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("AllocationResult"): + return &applyconfigurationsresourcev1beta2.AllocationResultApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("CELDeviceSelector"): + return &applyconfigurationsresourcev1beta2.CELDeviceSelectorApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("Counter"): + return &applyconfigurationsresourcev1beta2.CounterApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("CounterSet"): + return &applyconfigurationsresourcev1beta2.CounterSetApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("Device"): + return &applyconfigurationsresourcev1beta2.DeviceApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceAllocationConfiguration"): + return &applyconfigurationsresourcev1beta2.DeviceAllocationConfigurationApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceAllocationResult"): + return &applyconfigurationsresourcev1beta2.DeviceAllocationResultApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceAttribute"): + return &applyconfigurationsresourcev1beta2.DeviceAttributeApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceCapacity"): + return &applyconfigurationsresourcev1beta2.DeviceCapacityApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceClaim"): + return &applyconfigurationsresourcev1beta2.DeviceClaimApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceClaimConfiguration"): + return &applyconfigurationsresourcev1beta2.DeviceClaimConfigurationApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceClass"): + return &applyconfigurationsresourcev1beta2.DeviceClassApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceClassConfiguration"): + return &applyconfigurationsresourcev1beta2.DeviceClassConfigurationApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceClassSpec"): + return &applyconfigurationsresourcev1beta2.DeviceClassSpecApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceConfiguration"): + return &applyconfigurationsresourcev1beta2.DeviceConfigurationApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceConstraint"): + return &applyconfigurationsresourcev1beta2.DeviceConstraintApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceCounterConsumption"): + return &applyconfigurationsresourcev1beta2.DeviceCounterConsumptionApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceRequest"): + return &applyconfigurationsresourcev1beta2.DeviceRequestApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceRequestAllocationResult"): + return &applyconfigurationsresourcev1beta2.DeviceRequestAllocationResultApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceSelector"): + return &applyconfigurationsresourcev1beta2.DeviceSelectorApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceSubRequest"): + return &applyconfigurationsresourcev1beta2.DeviceSubRequestApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceTaint"): + return &applyconfigurationsresourcev1beta2.DeviceTaintApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("DeviceToleration"): + return &applyconfigurationsresourcev1beta2.DeviceTolerationApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ExactDeviceRequest"): + return &applyconfigurationsresourcev1beta2.ExactDeviceRequestApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("NetworkDeviceData"): + return &applyconfigurationsresourcev1beta2.NetworkDeviceDataApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("OpaqueDeviceConfiguration"): + return &applyconfigurationsresourcev1beta2.OpaqueDeviceConfigurationApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceClaim"): + return &applyconfigurationsresourcev1beta2.ResourceClaimApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceClaimConsumerReference"): + return &applyconfigurationsresourcev1beta2.ResourceClaimConsumerReferenceApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceClaimSpec"): + return &applyconfigurationsresourcev1beta2.ResourceClaimSpecApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceClaimStatus"): + return &applyconfigurationsresourcev1beta2.ResourceClaimStatusApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceClaimTemplate"): + return &applyconfigurationsresourcev1beta2.ResourceClaimTemplateApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceClaimTemplateSpec"): + return &applyconfigurationsresourcev1beta2.ResourceClaimTemplateSpecApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourcePool"): + return &applyconfigurationsresourcev1beta2.ResourcePoolApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceSlice"): + return &applyconfigurationsresourcev1beta2.ResourceSliceApplyConfiguration{} + case resourcev1beta2.SchemeGroupVersion.WithKind("ResourceSliceSpec"): + return &applyconfigurationsresourcev1beta2.ResourceSliceSpecApplyConfiguration{} + // Group=scheduling.k8s.io, Version=v1 case schedulingv1.SchemeGroupVersion.WithKind("PriorityClass"): return &applyconfigurationsschedulingv1.PriorityClassApplyConfiguration{} diff --git a/discovery/aggregated_discovery.go b/discovery/aggregated_discovery.go index f5eaaedab3..82d46b4895 100644 --- a/discovery/aggregated_discovery.go +++ b/discovery/aggregated_discovery.go @@ -156,7 +156,7 @@ func convertAPISubresource(parent metav1.APIResource, in apidiscovery.APISubreso return result, nil } -// Please note the functions below will be removed in v1.33. They facilitate conversion +// Please note the functions below will be removed in v1.35. They facilitate conversion // between the deprecated type apidiscoveryv2beta1.APIGroupDiscoveryList. // SplitGroupsAndResourcesV2Beta1 transforms "aggregated" discovery top-level structure into diff --git a/discovery/cached/disk/cached_discovery_test.go b/discovery/cached/disk/cached_discovery_test.go index 9b197fa31d..94cbfc8b77 100644 --- a/discovery/cached/disk/cached_discovery_test.go +++ b/discovery/cached/disk/cached_discovery_test.go @@ -350,7 +350,10 @@ func TestCachedDiscoveryClientUnaggregatedServerGroups(t *testing.T) { return } output, err := json.Marshal(body) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } // Content-type is "unaggregated" discovery format -- no resources returned. w.Header().Set("Content-Type", discovery.AcceptV1) w.WriteHeader(http.StatusOK) diff --git a/discovery/cached/memory/memcache_test.go b/discovery/cached/memory/memcache_test.go index dc017cb52d..1412a961ba 100644 --- a/discovery/cached/memory/memcache_test.go +++ b/discovery/cached/memory/memcache_test.go @@ -587,7 +587,10 @@ func TestMemCacheGroupsAndMaybeResources(t *testing.T) { return } output, err := json.Marshal(body) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } // Content-type is "unaggregated" discovery format -- no resources returned. w.Header().Set("Content-Type", discovery.AcceptV1) w.WriteHeader(http.StatusOK) @@ -1116,7 +1119,10 @@ func TestAggregatedMemCacheGroupsAndMaybeResources(t *testing.T) { return } output, err := json.Marshal(agg) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } // Content-type is "aggregated" discovery format. w.Header().Set("Content-Type", discovery.AcceptV2) w.WriteHeader(http.StatusOK) @@ -1414,9 +1420,12 @@ func TestMemCacheAggregatedServerGroups(t *testing.T) { return } output, err := json.Marshal(agg) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } // Content-type is "aggregated" discovery format. - w.Header().Set("Content-Type", discovery.AcceptV2Beta1) + w.Header().Set("Content-Type", discovery.AcceptV2) w.WriteHeader(http.StatusOK) w.Write(output) })) diff --git a/discovery/discovery_client.go b/discovery/discovery_client.go index ef14fee5f0..646820cbc2 100644 --- a/discovery/discovery_client.go +++ b/discovery/discovery_client.go @@ -29,9 +29,8 @@ import ( "sync" "time" - //nolint:staticcheck // SA1019 Keep using module since it's still being maintained and the api of google.golang.org/protobuf/proto differs - "github.com/golang/protobuf/proto" openapi_v2 "github.com/google/gnostic-models/openapiv2" + "google.golang.org/protobuf/proto" apidiscoveryv2 "k8s.io/api/apidiscovery/v2" apidiscoveryv2beta1 "k8s.io/api/apidiscovery/v2beta1" diff --git a/discovery/discovery_client_test.go b/discovery/discovery_client_test.go index 5382370190..7f36980690 100644 --- a/discovery/discovery_client_test.go +++ b/discovery/discovery_client_test.go @@ -60,7 +60,9 @@ func TestGetServerVersion(t *testing.T) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) @@ -107,7 +109,9 @@ func TestGetServerGroupsWithV1Server(t *testing.T) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) @@ -148,7 +152,9 @@ func TestDiscoveryToleratesMissingCoreGroup(t *testing.T) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) @@ -185,7 +191,9 @@ func TestDiscoveryFailsWhenNonCoreGroupsMissing(t *testing.T) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) @@ -386,7 +394,9 @@ func TestGetServerResourcesForGroupVersion(t *testing.T) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() for _, test := range tests { @@ -1313,13 +1323,19 @@ func TestAggregatedServerGroups(t *testing.T) { return } output, err = json.Marshal(agg) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } // Content-Type is "aggregated" discovery format. Add extra parameter // to ensure we are resilient to these extra parameters. w.Header().Set("Content-Type", AcceptV2+"; charset=utf-8") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } })) defer server.Close() client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) @@ -2383,7 +2399,10 @@ func TestAggregatedServerGroupsAndResources(t *testing.T) { return } output, err = json.Marshal(agg) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } } else { var agg *apidiscoveryv2beta1.APIGroupDiscoveryList switch req.URL.Path { @@ -2396,14 +2415,19 @@ func TestAggregatedServerGroupsAndResources(t *testing.T) { return } output, err = json.Marshal(&agg) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } } // Content-Type is "aggregated" discovery format. Add extra parameter // to ensure we are resilient to these extra parameters. w.Header().Set("Content-Type", accept+"; charset=utf-8") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() @@ -2543,13 +2567,18 @@ func TestAggregatedServerGroupsAndResourcesWithErrors(t *testing.T) { return } output, err = json.Marshal(agg) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } // Content-Type is "aggregated" discovery format. Add extra parameter // to ensure we are resilient to these extra parameters. w.Header().Set("Content-Type", AcceptV2+"; charset=utf-8") w.WriteHeader(status) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() @@ -3156,13 +3185,18 @@ func TestAggregatedServerPreferredResources(t *testing.T) { return } output, err = json.Marshal(agg) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } // Content-Type is "aggregated" discovery format. Add extra parameter // to ensure we are resilient to these extra parameters. w.Header().Set("Content-Type", AcceptV2+"; charset=utf-8") w.WriteHeader(http.StatusOK) _, err = w.Write(output) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer server.Close() client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) diff --git a/discovery/doc.go b/discovery/doc.go index 6baa1ef2a5..76495588ef 100644 --- a/discovery/doc.go +++ b/discovery/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package discovery provides ways to discover server-supported // API groups, versions and resources. -package discovery // import "k8s.io/client-go/discovery" +package discovery diff --git a/doc.go b/doc.go index 2d69be7194..d0f766a7ed 100644 --- a/doc.go +++ b/doc.go @@ -14,4 +14,4 @@ See the License for the specific language governing permissions and limitations under the License. */ -package clientgo // import "k8s.io/client-go" +package clientgo diff --git a/dynamic/dynamicinformer/informer.go b/dynamic/dynamicinformer/informer.go index 62d01339db..d1381823d6 100644 --- a/dynamic/dynamicinformer/informer.go +++ b/dynamic/dynamicinformer/informer.go @@ -153,13 +153,25 @@ func NewFilteredDynamicInformer(client dynamic.Interface, gvr schema.GroupVersio if tweakListOptions != nil { tweakListOptions(&options) } - return client.Resource(gvr).Namespace(namespace).List(context.TODO(), options) + return client.Resource(gvr).Namespace(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.Resource(gvr).Namespace(namespace).Watch(context.TODO(), options) + return client.Resource(gvr).Namespace(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Resource(gvr).Namespace(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Resource(gvr).Namespace(namespace).Watch(ctx, options) }, }, &unstructured.Unstructured{}, diff --git a/examples/fake-client/doc.go b/examples/fake-client/doc.go index 9379376ec9..1c02e5ea5e 100644 --- a/examples/fake-client/doc.go +++ b/examples/fake-client/doc.go @@ -17,4 +17,4 @@ limitations under the License. // Package fakeclient contains examples on how to use fakeclient in tests. // Note: This file is here to avoid warnings on go build since there are no // non-test files in this package. -package fakeclient // import "k8s.io/client-go/examples/fake-client" +package fakeclient diff --git a/examples/workqueue/main.go b/examples/workqueue/main.go index b8825dc1e2..eab9dabac3 100644 --- a/examples/workqueue/main.go +++ b/examples/workqueue/main.go @@ -17,6 +17,8 @@ limitations under the License. package main import ( + "context" + "errors" "flag" "fmt" "time" @@ -116,30 +118,30 @@ func (c *Controller) handleErr(err error, key string) { } // Run begins watching and syncing. -func (c *Controller) Run(workers int, stopCh chan struct{}) { - defer runtime.HandleCrash() +func (c *Controller) Run(ctx context.Context, workers int) { + defer runtime.HandleCrashWithContext(ctx) // Let the workers stop when we are done defer c.queue.ShutDown() klog.Info("Starting Pod controller") - go c.informer.Run(stopCh) + go c.informer.RunWithContext(ctx) // Wait for all involved caches to be synced, before processing items from the queue is started - if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) { + if !cache.WaitForNamedCacheSyncWithContext(ctx, c.informer.HasSynced) { runtime.HandleError(fmt.Errorf("Timed out waiting for caches to sync")) return } for i := 0; i < workers; i++ { - go wait.Until(c.runWorker, time.Second, stopCh) + go wait.UntilWithContext(ctx, c.runWorker, time.Second) } - <-stopCh + <-ctx.Done() klog.Info("Stopping Pod controller") } -func (c *Controller) runWorker() { +func (c *Controller) runWorker(ctx context.Context) { for c.processNextItem() { } } @@ -164,6 +166,8 @@ func main() { klog.Fatal(err) } + ctx := context.Background() + // create the pod watcher podListWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "pods", v1.NamespaceDefault, fields.Everything()) @@ -211,9 +215,9 @@ func main() { }) // Now let's start the controller - stop := make(chan struct{}) - defer close(stop) - go controller.Run(1, stop) + cancelCtx, cancel := context.WithCancelCause(ctx) + defer cancel(errors.New("time to stop because main has completed")) + go controller.Run(cancelCtx, 1) // Wait forever select {} diff --git a/features/known_features.go b/features/known_features.go index a74f6a8333..344d2ebb72 100644 --- a/features/known_features.go +++ b/features/known_features.go @@ -53,6 +53,12 @@ const ( // alpha: v1.30 InformerResourceVersion Feature = "InformerResourceVersion" + // owner: @deads2k + // beta: v1.33 + // + // Refactor informers to deliver watch stream events in order instead of out of order. + InOrderInformers Feature = "InOrderInformers" + // owner: @p0lyn0mial // beta: v1.30 // @@ -73,5 +79,6 @@ var defaultKubernetesFeatureGates = map[Feature]FeatureSpec{ ClientsAllowCBOR: {Default: false, PreRelease: Alpha}, ClientsPreferCBOR: {Default: false, PreRelease: Alpha}, InformerResourceVersion: {Default: false, PreRelease: Alpha}, + InOrderInformers: {Default: true, PreRelease: Beta}, WatchListClient: {Default: false, PreRelease: Beta}, } diff --git a/gentype/fake.go b/gentype/fake.go index 92420ee7e7..6ea3cbe0c0 100644 --- a/gentype/fake.go +++ b/gentype/fake.go @@ -32,7 +32,7 @@ import ( ) // FakeClient represents a fake client -type FakeClient[T runtime.Object] struct { +type FakeClient[T objectWithMeta] struct { *testing.Fake ns string resource schema.GroupVersionResource @@ -41,26 +41,26 @@ type FakeClient[T runtime.Object] struct { } // FakeClientWithList represents a fake client with support for lists. -type FakeClientWithList[T runtime.Object, L runtime.Object] struct { +type FakeClientWithList[T objectWithMeta, L runtime.Object] struct { *FakeClient[T] alsoFakeLister[T, L] } // FakeClientWithApply represents a fake client with support for apply declarative configurations. -type FakeClientWithApply[T runtime.Object, C namedObject] struct { +type FakeClientWithApply[T objectWithMeta, C namedObject] struct { *FakeClient[T] alsoFakeApplier[T, C] } // FakeClientWithListAndApply represents a fake client with support for lists and apply declarative configurations. -type FakeClientWithListAndApply[T runtime.Object, L runtime.Object, C namedObject] struct { +type FakeClientWithListAndApply[T objectWithMeta, L runtime.Object, C namedObject] struct { *FakeClient[T] alsoFakeLister[T, L] alsoFakeApplier[T, C] } // Helper types for composition -type alsoFakeLister[T runtime.Object, L runtime.Object] struct { +type alsoFakeLister[T objectWithMeta, L runtime.Object] struct { client *FakeClient[T] newList func() L copyListMeta func(L, L) @@ -68,20 +68,20 @@ type alsoFakeLister[T runtime.Object, L runtime.Object] struct { setItems func(L, []T) } -type alsoFakeApplier[T runtime.Object, C namedObject] struct { +type alsoFakeApplier[T objectWithMeta, C namedObject] struct { client *FakeClient[T] } // NewFakeClient constructs a fake client, namespaced or not, with no support for lists or apply. // Non-namespaced clients are constructed by passing an empty namespace (""). -func NewFakeClient[T runtime.Object]( +func NewFakeClient[T objectWithMeta]( fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T, ) *FakeClient[T] { return &FakeClient[T]{fake, namespace, resource, kind, emptyObjectCreator} } // NewFakeClientWithList constructs a namespaced client with support for lists. -func NewFakeClientWithList[T runtime.Object, L runtime.Object]( +func NewFakeClientWithList[T objectWithMeta, L runtime.Object]( fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T, emptyListCreator func() L, listMetaCopier func(L, L), itemGetter func(L) []T, itemSetter func(L, []T), ) *FakeClientWithList[T, L] { @@ -93,7 +93,7 @@ func NewFakeClientWithList[T runtime.Object, L runtime.Object]( } // NewFakeClientWithApply constructs a namespaced client with support for apply declarative configurations. -func NewFakeClientWithApply[T runtime.Object, C namedObject]( +func NewFakeClientWithApply[T objectWithMeta, C namedObject]( fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T, ) *FakeClientWithApply[T, C] { fakeClient := NewFakeClient[T](fake, namespace, resource, kind, emptyObjectCreator) @@ -104,7 +104,7 @@ func NewFakeClientWithApply[T runtime.Object, C namedObject]( } // NewFakeClientWithListAndApply constructs a client with support for lists and applying declarative configurations. -func NewFakeClientWithListAndApply[T runtime.Object, L runtime.Object, C namedObject]( +func NewFakeClientWithListAndApply[T objectWithMeta, L runtime.Object, C namedObject]( fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T, emptyListCreator func() L, listMetaCopier func(L, L), itemGetter func(L) []T, itemSetter func(L, []T), ) *FakeClientWithListAndApply[T, L, C] { @@ -183,6 +183,7 @@ func (l *alsoFakeLister[T, L]) List(ctx context.Context, opts metav1.ListOptions // Watch returns a watch.Interface that watches the requested resources. func (c *FakeClient[T]) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + opts.Watch = true return c.Fake. InvokesWatch(testing.NewWatchActionWithOptions(c.resource, c.ns, opts)) } diff --git a/go.mod b/go.mod index a399a15503..c9f09a326b 100644 --- a/go.mod +++ b/go.mod @@ -2,50 +2,48 @@ module k8s.io/client-go -go 1.23.0 +go 1.24.0 -godebug default=go1.23 +godebug default=go1.24 require ( + github.com/go-logr/logr v1.4.2 github.com/gogo/protobuf v1.3.2 - github.com/golang/protobuf v1.5.4 - github.com/google/gnostic-models v0.6.8 - github.com/google/go-cmp v0.6.0 - github.com/google/gofuzz v1.2.0 + github.com/google/gnostic-models v0.6.9 + github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 - github.com/gorilla/websocket v1.5.0 + github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 github.com/peterbourgon/diskv v2.0.1+incompatible github.com/spf13/pflag v1.0.5 - github.com/stretchr/testify v1.9.0 + github.com/stretchr/testify v1.10.0 go.uber.org/goleak v1.3.0 - golang.org/x/net v0.30.0 - golang.org/x/oauth2 v0.23.0 - golang.org/x/term v0.25.0 - golang.org/x/time v0.7.0 - google.golang.org/protobuf v1.35.1 + golang.org/x/net v0.38.0 + golang.org/x/oauth2 v0.27.0 + golang.org/x/term v0.30.0 + golang.org/x/time v0.9.0 + google.golang.org/protobuf v1.36.5 gopkg.in/evanphx/json-patch.v4 v4.12.0 - k8s.io/api v0.0.0-20241108114318-6cc44b8953ae - k8s.io/apimachinery v0.0.0-20241108022104-96b97de8d6ba + k8s.io/api v0.33.0 + k8s.io/apimachinery v0.33.0 k8s.io/klog/v2 v2.130.1 - k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f + k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 - sigs.k8s.io/structured-merge-diff/v4 v4.4.2 + sigs.k8s.io/randfill v1.0.0 + sigs.k8s.io/structured-merge-diff/v4 v4.6.0 sigs.k8s.io/yaml v1.4.0 ) require ( - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/davecgh/go-spew v1.1.1 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect - github.com/go-logr/logr v1.4.2 // indirect github.com/go-openapi/jsonpointer v0.21.0 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.23.0 // indirect - github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/btree v1.0.1 // indirect + github.com/google/btree v1.1.3 // indirect github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect @@ -54,12 +52,12 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect - github.com/onsi/ginkgo/v2 v2.21.0 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/objx v0.5.2 // indirect github.com/x448/float16 v0.8.4 // indirect - golang.org/x/sys v0.26.0 // indirect - golang.org/x/text v0.19.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect golang.org/x/tools v0.26.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index d7c9ef037b..81fdcabd1b 100644 --- a/go.sum +++ b/go.sum @@ -2,9 +2,8 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPd github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= @@ -23,24 +22,20 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= -github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA= -github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= -github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= +github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= +github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= +github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= -github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= @@ -77,22 +72,23 @@ github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+v github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -108,26 +104,26 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= -golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= -golang.org/x/oauth2 v0.23.0 h1:PbgcYx2W7i4LvjJWEbf0ngHV6qJYr86PkAV3bXdLEbs= -golang.org/x/oauth2 v0.23.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= +golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= -golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24= -golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y= +golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= -golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= -golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= -golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -138,8 +134,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= -google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -150,19 +146,22 @@ gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/api v0.0.0-20241108114318-6cc44b8953ae h1:XX7vEVBchw0xx4YJZ6OyPxOq3e5hX2PTZ5wu8dw0vco= -k8s.io/api v0.0.0-20241108114318-6cc44b8953ae/go.mod h1:jw6pQTESH9mdZL2vOK3twojvpPxipl5TpLZpPyl5ZYU= -k8s.io/apimachinery v0.0.0-20241108022104-96b97de8d6ba h1:ghB5Iygt6Ge8UyIwW7C1kJx4kP7AUTCL9Qg6GCsUUOY= -k8s.io/apimachinery v0.0.0-20241108022104-96b97de8d6ba/go.mod h1:HqhdaJUgQqky29T1V0o2yFkt/pZqLFIDyn9Zi/8rxoY= +k8s.io/api v0.33.0 h1:yTgZVn1XEe6opVpP1FylmNrIFWuDqe2H0V8CT5gxfIU= +k8s.io/api v0.33.0/go.mod h1:CTO61ECK/KU7haa3qq8sarQ0biLq2ju405IZAd9zsiM= +k8s.io/apimachinery v0.33.0 h1:1a6kHrJxb2hs4t8EE5wuR/WxKDwGN1FKH3JvDtA0CIQ= +k8s.io/apimachinery v0.33.0/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f h1:GA7//TjRY9yWGy1poLzYYJJ4JRdzg3+O6e8I+e+8T5Y= -k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f/go.mod h1:R/HEjbvWI0qdfb8viZUeVZm0X6IZnxAydC7YU42CMw4= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff h1:/usPimJzUKKu+m+TE36gUyGcf03XZEP0ZIKgKj35LS4= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo= -sigs.k8s.io/structured-merge-diff/v4 v4.4.2 h1:MdmvkGuXi/8io6ixD5wud3vOLwc1rj0aNqRlpuvjmwA= -sigs.k8s.io/structured-merge-diff/v4 v4.4.2/go.mod h1:N8f93tFZh9U6vpxwRArLiikrE5/2tiu1w1AGfACIGE4= +sigs.k8s.io/randfill v0.0.0-20250304075658-069ef1bbf016/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= +sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0 h1:IUA9nvMmnKWcj5jl84xn+T5MnlZKThmUW1TdblaLVAc= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0/go.mod h1:dDy58f92j70zLsuZVuUX5Wp9vtxXpaZnkPGWeqDfCps= sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/informers/admissionregistration/v1/mutatingwebhookconfiguration.go b/informers/admissionregistration/v1/mutatingwebhookconfiguration.go index 11c67480f9..7adafde23e 100644 --- a/informers/admissionregistration/v1/mutatingwebhookconfiguration.go +++ b/informers/admissionregistration/v1/mutatingwebhookconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().MutatingWebhookConfigurations().List(context.TODO(), options) + return client.AdmissionregistrationV1().MutatingWebhookConfigurations().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().MutatingWebhookConfigurations().Watch(context.TODO(), options) + return client.AdmissionregistrationV1().MutatingWebhookConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().MutatingWebhookConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().MutatingWebhookConfigurations().Watch(ctx, options) }, }, &apiadmissionregistrationv1.MutatingWebhookConfiguration{}, diff --git a/informers/admissionregistration/v1/validatingadmissionpolicy.go b/informers/admissionregistration/v1/validatingadmissionpolicy.go index e6974238c6..92cfa1fa4f 100644 --- a/informers/admissionregistration/v1/validatingadmissionpolicy.go +++ b/informers/admissionregistration/v1/validatingadmissionpolicy.go @@ -61,13 +61,25 @@ func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().List(context.TODO(), options) + return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Watch(context.TODO(), options) + return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Watch(ctx, options) }, }, &apiadmissionregistrationv1.ValidatingAdmissionPolicy{}, diff --git a/informers/admissionregistration/v1/validatingadmissionpolicybinding.go b/informers/admissionregistration/v1/validatingadmissionpolicybinding.go index 34067ca383..e0c35ec5e3 100644 --- a/informers/admissionregistration/v1/validatingadmissionpolicybinding.go +++ b/informers/admissionregistration/v1/validatingadmissionpolicybinding.go @@ -61,13 +61,25 @@ func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Inter if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().List(context.TODO(), options) + return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Watch(context.TODO(), options) + return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Watch(ctx, options) }, }, &apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding{}, diff --git a/informers/admissionregistration/v1/validatingwebhookconfiguration.go b/informers/admissionregistration/v1/validatingwebhookconfiguration.go index 42ca69c228..8ddeb0492d 100644 --- a/informers/admissionregistration/v1/validatingwebhookconfiguration.go +++ b/informers/admissionregistration/v1/validatingwebhookconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interfa if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().ValidatingWebhookConfigurations().List(context.TODO(), options) + return client.AdmissionregistrationV1().ValidatingWebhookConfigurations().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Watch(context.TODO(), options) + return client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().ValidatingWebhookConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Watch(ctx, options) }, }, &apiadmissionregistrationv1.ValidatingWebhookConfiguration{}, diff --git a/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go b/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go index 5a23158bfa..939eff9835 100644 --- a/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go +++ b/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go @@ -61,13 +61,25 @@ func NewFilteredMutatingAdmissionPolicyInformer(client kubernetes.Interface, res if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicies().List(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicies().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicies().Watch(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicies().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicies().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicies().Watch(ctx, options) }, }, &apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy{}, diff --git a/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go b/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go index efa143fe55..a94f6d27bd 100644 --- a/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go +++ b/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go @@ -61,13 +61,25 @@ func NewFilteredMutatingAdmissionPolicyBindingInformer(client kubernetes.Interfa if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicyBindings().List(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicyBindings().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicyBindings().Watch(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicyBindings().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicyBindings().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().MutatingAdmissionPolicyBindings().Watch(ctx, options) }, }, &apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding{}, diff --git a/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go b/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go index aaae7b297f..1a6f7d56de 100644 --- a/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go +++ b/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go @@ -61,13 +61,25 @@ func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().List(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().Watch(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().Watch(ctx, options) }, }, &apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy{}, diff --git a/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go b/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go index d62c59061c..3afaa3beca 100644 --- a/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go +++ b/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go @@ -61,13 +61,25 @@ func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Inter if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().List(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().Watch(context.TODO(), options) + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().Watch(ctx, options) }, }, &apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding{}, diff --git a/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go b/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go index c6ca36ea29..697dae852a 100644 --- a/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go +++ b/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().List(context.TODO(), options) + return client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Watch(context.TODO(), options) + return client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Watch(ctx, options) }, }, &apiadmissionregistrationv1beta1.MutatingWebhookConfiguration{}, diff --git a/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go b/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go index d5b4204f1b..31c3569d94 100644 --- a/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go +++ b/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go @@ -61,13 +61,25 @@ func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().List(context.TODO(), options) + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Watch(context.TODO(), options) + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Watch(ctx, options) }, }, &apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy{}, diff --git a/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go b/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go index dbb5153ef3..fb2c10e3e7 100644 --- a/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go +++ b/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go @@ -61,13 +61,25 @@ func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Inter if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().List(context.TODO(), options) + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().Watch(context.TODO(), options) + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().Watch(ctx, options) }, }, &apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding{}, diff --git a/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go b/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go index 602b361afa..2eb6991cb5 100644 --- a/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go +++ b/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interfa if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().List(context.TODO(), options) + return client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Watch(context.TODO(), options) + return client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Watch(ctx, options) }, }, &apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration{}, diff --git a/informers/apiserverinternal/v1alpha1/storageversion.go b/informers/apiserverinternal/v1alpha1/storageversion.go index a99dbd17d2..e8e1669d12 100644 --- a/informers/apiserverinternal/v1alpha1/storageversion.go +++ b/informers/apiserverinternal/v1alpha1/storageversion.go @@ -61,13 +61,25 @@ func NewFilteredStorageVersionInformer(client kubernetes.Interface, resyncPeriod if tweakListOptions != nil { tweakListOptions(&options) } - return client.InternalV1alpha1().StorageVersions().List(context.TODO(), options) + return client.InternalV1alpha1().StorageVersions().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.InternalV1alpha1().StorageVersions().Watch(context.TODO(), options) + return client.InternalV1alpha1().StorageVersions().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.InternalV1alpha1().StorageVersions().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.InternalV1alpha1().StorageVersions().Watch(ctx, options) }, }, &apiapiserverinternalv1alpha1.StorageVersion{}, diff --git a/informers/apps/v1/controllerrevision.go b/informers/apps/v1/controllerrevision.go index 334a1b8f81..64eeddec0e 100644 --- a/informers/apps/v1/controllerrevision.go +++ b/informers/apps/v1/controllerrevision.go @@ -62,13 +62,25 @@ func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespac if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().ControllerRevisions(namespace).List(context.TODO(), options) + return client.AppsV1().ControllerRevisions(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().ControllerRevisions(namespace).Watch(context.TODO(), options) + return client.AppsV1().ControllerRevisions(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().ControllerRevisions(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().ControllerRevisions(namespace).Watch(ctx, options) }, }, &apiappsv1.ControllerRevision{}, diff --git a/informers/apps/v1/daemonset.go b/informers/apps/v1/daemonset.go index 73adf8cbf8..4a3e95e1f1 100644 --- a/informers/apps/v1/daemonset.go +++ b/informers/apps/v1/daemonset.go @@ -62,13 +62,25 @@ func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().DaemonSets(namespace).List(context.TODO(), options) + return client.AppsV1().DaemonSets(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().DaemonSets(namespace).Watch(context.TODO(), options) + return client.AppsV1().DaemonSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().DaemonSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().DaemonSets(namespace).Watch(ctx, options) }, }, &apiappsv1.DaemonSet{}, diff --git a/informers/apps/v1/deployment.go b/informers/apps/v1/deployment.go index f9314844cc..9c0c20c536 100644 --- a/informers/apps/v1/deployment.go +++ b/informers/apps/v1/deployment.go @@ -62,13 +62,25 @@ func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().Deployments(namespace).List(context.TODO(), options) + return client.AppsV1().Deployments(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().Deployments(namespace).Watch(context.TODO(), options) + return client.AppsV1().Deployments(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().Deployments(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().Deployments(namespace).Watch(ctx, options) }, }, &apiappsv1.Deployment{}, diff --git a/informers/apps/v1/replicaset.go b/informers/apps/v1/replicaset.go index dfa8ae87a9..75c7a79e82 100644 --- a/informers/apps/v1/replicaset.go +++ b/informers/apps/v1/replicaset.go @@ -62,13 +62,25 @@ func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().ReplicaSets(namespace).List(context.TODO(), options) + return client.AppsV1().ReplicaSets(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().ReplicaSets(namespace).Watch(context.TODO(), options) + return client.AppsV1().ReplicaSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().ReplicaSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().ReplicaSets(namespace).Watch(ctx, options) }, }, &apiappsv1.ReplicaSet{}, diff --git a/informers/apps/v1/statefulset.go b/informers/apps/v1/statefulset.go index 84ca50123f..f759e0464f 100644 --- a/informers/apps/v1/statefulset.go +++ b/informers/apps/v1/statefulset.go @@ -62,13 +62,25 @@ func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace strin if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().StatefulSets(namespace).List(context.TODO(), options) + return client.AppsV1().StatefulSets(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1().StatefulSets(namespace).Watch(context.TODO(), options) + return client.AppsV1().StatefulSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().StatefulSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1().StatefulSets(namespace).Watch(ctx, options) }, }, &apiappsv1.StatefulSet{}, diff --git a/informers/apps/v1beta1/controllerrevision.go b/informers/apps/v1beta1/controllerrevision.go index c0a51dbe36..79b2fb907e 100644 --- a/informers/apps/v1beta1/controllerrevision.go +++ b/informers/apps/v1beta1/controllerrevision.go @@ -62,13 +62,25 @@ func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespac if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta1().ControllerRevisions(namespace).List(context.TODO(), options) + return client.AppsV1beta1().ControllerRevisions(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta1().ControllerRevisions(namespace).Watch(context.TODO(), options) + return client.AppsV1beta1().ControllerRevisions(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta1().ControllerRevisions(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta1().ControllerRevisions(namespace).Watch(ctx, options) }, }, &apiappsv1beta1.ControllerRevision{}, diff --git a/informers/apps/v1beta1/deployment.go b/informers/apps/v1beta1/deployment.go index 027ae402d7..1334c03a97 100644 --- a/informers/apps/v1beta1/deployment.go +++ b/informers/apps/v1beta1/deployment.go @@ -62,13 +62,25 @@ func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta1().Deployments(namespace).List(context.TODO(), options) + return client.AppsV1beta1().Deployments(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta1().Deployments(namespace).Watch(context.TODO(), options) + return client.AppsV1beta1().Deployments(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta1().Deployments(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta1().Deployments(namespace).Watch(ctx, options) }, }, &apiappsv1beta1.Deployment{}, diff --git a/informers/apps/v1beta1/statefulset.go b/informers/apps/v1beta1/statefulset.go index bc357d7e7b..2d52ae02da 100644 --- a/informers/apps/v1beta1/statefulset.go +++ b/informers/apps/v1beta1/statefulset.go @@ -62,13 +62,25 @@ func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace strin if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta1().StatefulSets(namespace).List(context.TODO(), options) + return client.AppsV1beta1().StatefulSets(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta1().StatefulSets(namespace).Watch(context.TODO(), options) + return client.AppsV1beta1().StatefulSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta1().StatefulSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta1().StatefulSets(namespace).Watch(ctx, options) }, }, &apiappsv1beta1.StatefulSet{}, diff --git a/informers/apps/v1beta2/controllerrevision.go b/informers/apps/v1beta2/controllerrevision.go index 62a560fdaf..0936ef7b96 100644 --- a/informers/apps/v1beta2/controllerrevision.go +++ b/informers/apps/v1beta2/controllerrevision.go @@ -62,13 +62,25 @@ func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespac if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().ControllerRevisions(namespace).List(context.TODO(), options) + return client.AppsV1beta2().ControllerRevisions(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().ControllerRevisions(namespace).Watch(context.TODO(), options) + return client.AppsV1beta2().ControllerRevisions(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().ControllerRevisions(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().ControllerRevisions(namespace).Watch(ctx, options) }, }, &apiappsv1beta2.ControllerRevision{}, diff --git a/informers/apps/v1beta2/daemonset.go b/informers/apps/v1beta2/daemonset.go index 9d4c8ede98..d5c49d77f2 100644 --- a/informers/apps/v1beta2/daemonset.go +++ b/informers/apps/v1beta2/daemonset.go @@ -62,13 +62,25 @@ func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().DaemonSets(namespace).List(context.TODO(), options) + return client.AppsV1beta2().DaemonSets(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().DaemonSets(namespace).Watch(context.TODO(), options) + return client.AppsV1beta2().DaemonSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().DaemonSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().DaemonSets(namespace).Watch(ctx, options) }, }, &apiappsv1beta2.DaemonSet{}, diff --git a/informers/apps/v1beta2/deployment.go b/informers/apps/v1beta2/deployment.go index be85192cf4..575ddbfca8 100644 --- a/informers/apps/v1beta2/deployment.go +++ b/informers/apps/v1beta2/deployment.go @@ -62,13 +62,25 @@ func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().Deployments(namespace).List(context.TODO(), options) + return client.AppsV1beta2().Deployments(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().Deployments(namespace).Watch(context.TODO(), options) + return client.AppsV1beta2().Deployments(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().Deployments(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().Deployments(namespace).Watch(ctx, options) }, }, &apiappsv1beta2.Deployment{}, diff --git a/informers/apps/v1beta2/replicaset.go b/informers/apps/v1beta2/replicaset.go index e5d2797087..cfc4b3289f 100644 --- a/informers/apps/v1beta2/replicaset.go +++ b/informers/apps/v1beta2/replicaset.go @@ -62,13 +62,25 @@ func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().ReplicaSets(namespace).List(context.TODO(), options) + return client.AppsV1beta2().ReplicaSets(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().ReplicaSets(namespace).Watch(context.TODO(), options) + return client.AppsV1beta2().ReplicaSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().ReplicaSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().ReplicaSets(namespace).Watch(ctx, options) }, }, &apiappsv1beta2.ReplicaSet{}, diff --git a/informers/apps/v1beta2/statefulset.go b/informers/apps/v1beta2/statefulset.go index d147fc8851..a514c5bbb5 100644 --- a/informers/apps/v1beta2/statefulset.go +++ b/informers/apps/v1beta2/statefulset.go @@ -62,13 +62,25 @@ func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace strin if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().StatefulSets(namespace).List(context.TODO(), options) + return client.AppsV1beta2().StatefulSets(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AppsV1beta2().StatefulSets(namespace).Watch(context.TODO(), options) + return client.AppsV1beta2().StatefulSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().StatefulSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AppsV1beta2().StatefulSets(namespace).Watch(ctx, options) }, }, &apiappsv1beta2.StatefulSet{}, diff --git a/informers/autoscaling/v1/horizontalpodautoscaler.go b/informers/autoscaling/v1/horizontalpodautoscaler.go index fce275934f..e92f756394 100644 --- a/informers/autoscaling/v1/horizontalpodautoscaler.go +++ b/informers/autoscaling/v1/horizontalpodautoscaler.go @@ -62,13 +62,25 @@ func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, nam if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV1().HorizontalPodAutoscalers(namespace).List(context.TODO(), options) + return client.AutoscalingV1().HorizontalPodAutoscalers(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV1().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options) + return client.AutoscalingV1().HorizontalPodAutoscalers(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV1().HorizontalPodAutoscalers(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV1().HorizontalPodAutoscalers(namespace).Watch(ctx, options) }, }, &apiautoscalingv1.HorizontalPodAutoscaler{}, diff --git a/informers/autoscaling/v2/horizontalpodautoscaler.go b/informers/autoscaling/v2/horizontalpodautoscaler.go index 92104f8227..b5d4123e52 100644 --- a/informers/autoscaling/v2/horizontalpodautoscaler.go +++ b/informers/autoscaling/v2/horizontalpodautoscaler.go @@ -62,13 +62,25 @@ func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, nam if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV2().HorizontalPodAutoscalers(namespace).List(context.TODO(), options) + return client.AutoscalingV2().HorizontalPodAutoscalers(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV2().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options) + return client.AutoscalingV2().HorizontalPodAutoscalers(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV2().HorizontalPodAutoscalers(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV2().HorizontalPodAutoscalers(namespace).Watch(ctx, options) }, }, &apiautoscalingv2.HorizontalPodAutoscaler{}, diff --git a/informers/autoscaling/v2beta1/horizontalpodautoscaler.go b/informers/autoscaling/v2beta1/horizontalpodautoscaler.go index b776027186..5a64e7ef9e 100644 --- a/informers/autoscaling/v2beta1/horizontalpodautoscaler.go +++ b/informers/autoscaling/v2beta1/horizontalpodautoscaler.go @@ -62,13 +62,25 @@ func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, nam if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).List(context.TODO(), options) + return client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options) + return client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).Watch(ctx, options) }, }, &apiautoscalingv2beta1.HorizontalPodAutoscaler{}, diff --git a/informers/autoscaling/v2beta2/horizontalpodautoscaler.go b/informers/autoscaling/v2beta2/horizontalpodautoscaler.go index 1848429b14..2d4c3f1de6 100644 --- a/informers/autoscaling/v2beta2/horizontalpodautoscaler.go +++ b/informers/autoscaling/v2beta2/horizontalpodautoscaler.go @@ -62,13 +62,25 @@ func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, nam if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).List(context.TODO(), options) + return client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options) + return client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Watch(ctx, options) }, }, &apiautoscalingv2beta2.HorizontalPodAutoscaler{}, diff --git a/informers/batch/v1/cronjob.go b/informers/batch/v1/cronjob.go index 2a188acdd6..ee4f8808a8 100644 --- a/informers/batch/v1/cronjob.go +++ b/informers/batch/v1/cronjob.go @@ -62,13 +62,25 @@ func NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.BatchV1().CronJobs(namespace).List(context.TODO(), options) + return client.BatchV1().CronJobs(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.BatchV1().CronJobs(namespace).Watch(context.TODO(), options) + return client.BatchV1().CronJobs(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.BatchV1().CronJobs(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.BatchV1().CronJobs(namespace).Watch(ctx, options) }, }, &apibatchv1.CronJob{}, diff --git a/informers/batch/v1/job.go b/informers/batch/v1/job.go index 439ec7a6a5..d3965f53e9 100644 --- a/informers/batch/v1/job.go +++ b/informers/batch/v1/job.go @@ -62,13 +62,25 @@ func NewFilteredJobInformer(client kubernetes.Interface, namespace string, resyn if tweakListOptions != nil { tweakListOptions(&options) } - return client.BatchV1().Jobs(namespace).List(context.TODO(), options) + return client.BatchV1().Jobs(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.BatchV1().Jobs(namespace).Watch(context.TODO(), options) + return client.BatchV1().Jobs(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.BatchV1().Jobs(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.BatchV1().Jobs(namespace).Watch(ctx, options) }, }, &apibatchv1.Job{}, diff --git a/informers/batch/v1beta1/cronjob.go b/informers/batch/v1beta1/cronjob.go index 1f061e16c2..1cf169d92e 100644 --- a/informers/batch/v1beta1/cronjob.go +++ b/informers/batch/v1beta1/cronjob.go @@ -62,13 +62,25 @@ func NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.BatchV1beta1().CronJobs(namespace).List(context.TODO(), options) + return client.BatchV1beta1().CronJobs(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.BatchV1beta1().CronJobs(namespace).Watch(context.TODO(), options) + return client.BatchV1beta1().CronJobs(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.BatchV1beta1().CronJobs(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.BatchV1beta1().CronJobs(namespace).Watch(ctx, options) }, }, &apibatchv1beta1.CronJob{}, diff --git a/informers/certificates/v1/certificatesigningrequest.go b/informers/certificates/v1/certificatesigningrequest.go index 0bd32ab95b..076da13627 100644 --- a/informers/certificates/v1/certificatesigningrequest.go +++ b/informers/certificates/v1/certificatesigningrequest.go @@ -61,13 +61,25 @@ func NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.CertificatesV1().CertificateSigningRequests().List(context.TODO(), options) + return client.CertificatesV1().CertificateSigningRequests().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CertificatesV1().CertificateSigningRequests().Watch(context.TODO(), options) + return client.CertificatesV1().CertificateSigningRequests().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1().CertificateSigningRequests().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1().CertificateSigningRequests().Watch(ctx, options) }, }, &apicertificatesv1.CertificateSigningRequest{}, diff --git a/informers/certificates/v1alpha1/clustertrustbundle.go b/informers/certificates/v1alpha1/clustertrustbundle.go index 046688961c..ca5ee2c979 100644 --- a/informers/certificates/v1alpha1/clustertrustbundle.go +++ b/informers/certificates/v1alpha1/clustertrustbundle.go @@ -61,13 +61,25 @@ func NewFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPe if tweakListOptions != nil { tweakListOptions(&options) } - return client.CertificatesV1alpha1().ClusterTrustBundles().List(context.TODO(), options) + return client.CertificatesV1alpha1().ClusterTrustBundles().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CertificatesV1alpha1().ClusterTrustBundles().Watch(context.TODO(), options) + return client.CertificatesV1alpha1().ClusterTrustBundles().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1alpha1().ClusterTrustBundles().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1alpha1().ClusterTrustBundles().Watch(ctx, options) }, }, &apicertificatesv1alpha1.ClusterTrustBundle{}, diff --git a/informers/certificates/v1beta1/certificatesigningrequest.go b/informers/certificates/v1beta1/certificatesigningrequest.go index b3aff1cc86..f93d435a06 100644 --- a/informers/certificates/v1beta1/certificatesigningrequest.go +++ b/informers/certificates/v1beta1/certificatesigningrequest.go @@ -61,13 +61,25 @@ func NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.CertificatesV1beta1().CertificateSigningRequests().List(context.TODO(), options) + return client.CertificatesV1beta1().CertificateSigningRequests().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CertificatesV1beta1().CertificateSigningRequests().Watch(context.TODO(), options) + return client.CertificatesV1beta1().CertificateSigningRequests().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1beta1().CertificateSigningRequests().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1beta1().CertificateSigningRequests().Watch(ctx, options) }, }, &apicertificatesv1beta1.CertificateSigningRequest{}, diff --git a/informers/certificates/v1beta1/clustertrustbundle.go b/informers/certificates/v1beta1/clustertrustbundle.go new file mode 100644 index 0000000000..c4a69b22ef --- /dev/null +++ b/informers/certificates/v1beta1/clustertrustbundle.go @@ -0,0 +1,101 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + time "time" + + apicertificatesv1beta1 "k8s.io/api/certificates/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + certificatesv1beta1 "k8s.io/client-go/listers/certificates/v1beta1" + cache "k8s.io/client-go/tools/cache" +) + +// ClusterTrustBundleInformer provides access to a shared informer and lister for +// ClusterTrustBundles. +type ClusterTrustBundleInformer interface { + Informer() cache.SharedIndexInformer + Lister() certificatesv1beta1.ClusterTrustBundleLister +} + +type clusterTrustBundleInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredClusterTrustBundleInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1beta1().ClusterTrustBundles().List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1beta1().ClusterTrustBundles().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1beta1().ClusterTrustBundles().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CertificatesV1beta1().ClusterTrustBundles().Watch(ctx, options) + }, + }, + &apicertificatesv1beta1.ClusterTrustBundle{}, + resyncPeriod, + indexers, + ) +} + +func (f *clusterTrustBundleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredClusterTrustBundleInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *clusterTrustBundleInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apicertificatesv1beta1.ClusterTrustBundle{}, f.defaultInformer) +} + +func (f *clusterTrustBundleInformer) Lister() certificatesv1beta1.ClusterTrustBundleLister { + return certificatesv1beta1.NewClusterTrustBundleLister(f.Informer().GetIndexer()) +} diff --git a/informers/certificates/v1beta1/interface.go b/informers/certificates/v1beta1/interface.go index 258dd1d0e6..f13d5e6633 100644 --- a/informers/certificates/v1beta1/interface.go +++ b/informers/certificates/v1beta1/interface.go @@ -26,6 +26,8 @@ import ( type Interface interface { // CertificateSigningRequests returns a CertificateSigningRequestInformer. CertificateSigningRequests() CertificateSigningRequestInformer + // ClusterTrustBundles returns a ClusterTrustBundleInformer. + ClusterTrustBundles() ClusterTrustBundleInformer } type version struct { @@ -43,3 +45,8 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList func (v *version) CertificateSigningRequests() CertificateSigningRequestInformer { return &certificateSigningRequestInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } + +// ClusterTrustBundles returns a ClusterTrustBundleInformer. +func (v *version) ClusterTrustBundles() ClusterTrustBundleInformer { + return &clusterTrustBundleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} diff --git a/informers/coordination/v1/lease.go b/informers/coordination/v1/lease.go index 0627d73099..2d0c812d6b 100644 --- a/informers/coordination/v1/lease.go +++ b/informers/coordination/v1/lease.go @@ -62,13 +62,25 @@ func NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, res if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoordinationV1().Leases(namespace).List(context.TODO(), options) + return client.CoordinationV1().Leases(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoordinationV1().Leases(namespace).Watch(context.TODO(), options) + return client.CoordinationV1().Leases(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1().Leases(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1().Leases(namespace).Watch(ctx, options) }, }, &apicoordinationv1.Lease{}, diff --git a/informers/coordination/v1alpha2/leasecandidate.go b/informers/coordination/v1alpha2/leasecandidate.go index f38adf6524..c220a9b20c 100644 --- a/informers/coordination/v1alpha2/leasecandidate.go +++ b/informers/coordination/v1alpha2/leasecandidate.go @@ -62,13 +62,25 @@ func NewFilteredLeaseCandidateInformer(client kubernetes.Interface, namespace st if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoordinationV1alpha2().LeaseCandidates(namespace).List(context.TODO(), options) + return client.CoordinationV1alpha2().LeaseCandidates(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoordinationV1alpha2().LeaseCandidates(namespace).Watch(context.TODO(), options) + return client.CoordinationV1alpha2().LeaseCandidates(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1alpha2().LeaseCandidates(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1alpha2().LeaseCandidates(namespace).Watch(ctx, options) }, }, &apicoordinationv1alpha2.LeaseCandidate{}, diff --git a/informers/coordination/v1beta1/interface.go b/informers/coordination/v1beta1/interface.go index 360266206c..707e510869 100644 --- a/informers/coordination/v1beta1/interface.go +++ b/informers/coordination/v1beta1/interface.go @@ -26,6 +26,8 @@ import ( type Interface interface { // Leases returns a LeaseInformer. Leases() LeaseInformer + // LeaseCandidates returns a LeaseCandidateInformer. + LeaseCandidates() LeaseCandidateInformer } type version struct { @@ -43,3 +45,8 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList func (v *version) Leases() LeaseInformer { return &leaseInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } + +// LeaseCandidates returns a LeaseCandidateInformer. +func (v *version) LeaseCandidates() LeaseCandidateInformer { + return &leaseCandidateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/informers/coordination/v1beta1/lease.go b/informers/coordination/v1beta1/lease.go index 563a25c30f..ef91381c1d 100644 --- a/informers/coordination/v1beta1/lease.go +++ b/informers/coordination/v1beta1/lease.go @@ -62,13 +62,25 @@ func NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, res if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoordinationV1beta1().Leases(namespace).List(context.TODO(), options) + return client.CoordinationV1beta1().Leases(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoordinationV1beta1().Leases(namespace).Watch(context.TODO(), options) + return client.CoordinationV1beta1().Leases(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1beta1().Leases(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1beta1().Leases(namespace).Watch(ctx, options) }, }, &apicoordinationv1beta1.Lease{}, diff --git a/informers/coordination/v1beta1/leasecandidate.go b/informers/coordination/v1beta1/leasecandidate.go new file mode 100644 index 0000000000..4315e50c32 --- /dev/null +++ b/informers/coordination/v1beta1/leasecandidate.go @@ -0,0 +1,102 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + time "time" + + apicoordinationv1beta1 "k8s.io/api/coordination/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + coordinationv1beta1 "k8s.io/client-go/listers/coordination/v1beta1" + cache "k8s.io/client-go/tools/cache" +) + +// LeaseCandidateInformer provides access to a shared informer and lister for +// LeaseCandidates. +type LeaseCandidateInformer interface { + Informer() cache.SharedIndexInformer + Lister() coordinationv1beta1.LeaseCandidateLister +} + +type leaseCandidateInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewLeaseCandidateInformer constructs a new informer for LeaseCandidate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredLeaseCandidateInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredLeaseCandidateInformer constructs a new informer for LeaseCandidate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1beta1().LeaseCandidates(namespace).List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1beta1().LeaseCandidates(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1beta1().LeaseCandidates(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoordinationV1beta1().LeaseCandidates(namespace).Watch(ctx, options) + }, + }, + &apicoordinationv1beta1.LeaseCandidate{}, + resyncPeriod, + indexers, + ) +} + +func (f *leaseCandidateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredLeaseCandidateInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *leaseCandidateInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apicoordinationv1beta1.LeaseCandidate{}, f.defaultInformer) +} + +func (f *leaseCandidateInformer) Lister() coordinationv1beta1.LeaseCandidateLister { + return coordinationv1beta1.NewLeaseCandidateLister(f.Informer().GetIndexer()) +} diff --git a/informers/core/v1/componentstatus.go b/informers/core/v1/componentstatus.go index 2a97c638fe..a7992bfdff 100644 --- a/informers/core/v1/componentstatus.go +++ b/informers/core/v1/componentstatus.go @@ -61,13 +61,25 @@ func NewFilteredComponentStatusInformer(client kubernetes.Interface, resyncPerio if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ComponentStatuses().List(context.TODO(), options) + return client.CoreV1().ComponentStatuses().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ComponentStatuses().Watch(context.TODO(), options) + return client.CoreV1().ComponentStatuses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ComponentStatuses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ComponentStatuses().Watch(ctx, options) }, }, &apicorev1.ComponentStatus{}, diff --git a/informers/core/v1/configmap.go b/informers/core/v1/configmap.go index 07f5fb1f79..014e55afe4 100644 --- a/informers/core/v1/configmap.go +++ b/informers/core/v1/configmap.go @@ -62,13 +62,25 @@ func NewFilteredConfigMapInformer(client kubernetes.Interface, namespace string, if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ConfigMaps(namespace).List(context.TODO(), options) + return client.CoreV1().ConfigMaps(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ConfigMaps(namespace).Watch(context.TODO(), options) + return client.CoreV1().ConfigMaps(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ConfigMaps(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ConfigMaps(namespace).Watch(ctx, options) }, }, &apicorev1.ConfigMap{}, diff --git a/informers/core/v1/endpoints.go b/informers/core/v1/endpoints.go index 6171d5df6b..2d4412ad00 100644 --- a/informers/core/v1/endpoints.go +++ b/informers/core/v1/endpoints.go @@ -62,13 +62,25 @@ func NewFilteredEndpointsInformer(client kubernetes.Interface, namespace string, if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Endpoints(namespace).List(context.TODO(), options) + return client.CoreV1().Endpoints(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Endpoints(namespace).Watch(context.TODO(), options) + return client.CoreV1().Endpoints(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Endpoints(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Endpoints(namespace).Watch(ctx, options) }, }, &apicorev1.Endpoints{}, diff --git a/informers/core/v1/event.go b/informers/core/v1/event.go index 55500679d2..80a5cad843 100644 --- a/informers/core/v1/event.go +++ b/informers/core/v1/event.go @@ -62,13 +62,25 @@ func NewFilteredEventInformer(client kubernetes.Interface, namespace string, res if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Events(namespace).List(context.TODO(), options) + return client.CoreV1().Events(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Events(namespace).Watch(context.TODO(), options) + return client.CoreV1().Events(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Events(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Events(namespace).Watch(ctx, options) }, }, &apicorev1.Event{}, diff --git a/informers/core/v1/limitrange.go b/informers/core/v1/limitrange.go index 2c2dec79f1..cf8e1eb422 100644 --- a/informers/core/v1/limitrange.go +++ b/informers/core/v1/limitrange.go @@ -62,13 +62,25 @@ func NewFilteredLimitRangeInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().LimitRanges(namespace).List(context.TODO(), options) + return client.CoreV1().LimitRanges(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().LimitRanges(namespace).Watch(context.TODO(), options) + return client.CoreV1().LimitRanges(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().LimitRanges(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().LimitRanges(namespace).Watch(ctx, options) }, }, &apicorev1.LimitRange{}, diff --git a/informers/core/v1/namespace.go b/informers/core/v1/namespace.go index 09e0740ba9..ae09888b9b 100644 --- a/informers/core/v1/namespace.go +++ b/informers/core/v1/namespace.go @@ -61,13 +61,25 @@ func NewFilteredNamespaceInformer(client kubernetes.Interface, resyncPeriod time if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Namespaces().List(context.TODO(), options) + return client.CoreV1().Namespaces().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Namespaces().Watch(context.TODO(), options) + return client.CoreV1().Namespaces().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Namespaces().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Namespaces().Watch(ctx, options) }, }, &apicorev1.Namespace{}, diff --git a/informers/core/v1/node.go b/informers/core/v1/node.go index 608aa9fb7c..a036db034b 100644 --- a/informers/core/v1/node.go +++ b/informers/core/v1/node.go @@ -61,13 +61,25 @@ func NewFilteredNodeInformer(client kubernetes.Interface, resyncPeriod time.Dura if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Nodes().List(context.TODO(), options) + return client.CoreV1().Nodes().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Nodes().Watch(context.TODO(), options) + return client.CoreV1().Nodes().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Nodes().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Nodes().Watch(ctx, options) }, }, &apicorev1.Node{}, diff --git a/informers/core/v1/persistentvolume.go b/informers/core/v1/persistentvolume.go index 19c0929e5e..4d1d63eadc 100644 --- a/informers/core/v1/persistentvolume.go +++ b/informers/core/v1/persistentvolume.go @@ -61,13 +61,25 @@ func NewFilteredPersistentVolumeInformer(client kubernetes.Interface, resyncPeri if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().PersistentVolumes().List(context.TODO(), options) + return client.CoreV1().PersistentVolumes().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().PersistentVolumes().Watch(context.TODO(), options) + return client.CoreV1().PersistentVolumes().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().PersistentVolumes().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().PersistentVolumes().Watch(ctx, options) }, }, &apicorev1.PersistentVolume{}, diff --git a/informers/core/v1/persistentvolumeclaim.go b/informers/core/v1/persistentvolumeclaim.go index 27c35fec1a..87a4cc037c 100644 --- a/informers/core/v1/persistentvolumeclaim.go +++ b/informers/core/v1/persistentvolumeclaim.go @@ -62,13 +62,25 @@ func NewFilteredPersistentVolumeClaimInformer(client kubernetes.Interface, names if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().PersistentVolumeClaims(namespace).List(context.TODO(), options) + return client.CoreV1().PersistentVolumeClaims(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().PersistentVolumeClaims(namespace).Watch(context.TODO(), options) + return client.CoreV1().PersistentVolumeClaims(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().PersistentVolumeClaims(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().PersistentVolumeClaims(namespace).Watch(ctx, options) }, }, &apicorev1.PersistentVolumeClaim{}, diff --git a/informers/core/v1/pod.go b/informers/core/v1/pod.go index c661704bd1..e3a40729f1 100644 --- a/informers/core/v1/pod.go +++ b/informers/core/v1/pod.go @@ -62,13 +62,25 @@ func NewFilteredPodInformer(client kubernetes.Interface, namespace string, resyn if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Pods(namespace).List(context.TODO(), options) + return client.CoreV1().Pods(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Pods(namespace).Watch(context.TODO(), options) + return client.CoreV1().Pods(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Pods(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Pods(namespace).Watch(ctx, options) }, }, &apicorev1.Pod{}, diff --git a/informers/core/v1/podtemplate.go b/informers/core/v1/podtemplate.go index 0d16c5b4e2..9d6e7048e6 100644 --- a/informers/core/v1/podtemplate.go +++ b/informers/core/v1/podtemplate.go @@ -62,13 +62,25 @@ func NewFilteredPodTemplateInformer(client kubernetes.Interface, namespace strin if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().PodTemplates(namespace).List(context.TODO(), options) + return client.CoreV1().PodTemplates(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().PodTemplates(namespace).Watch(context.TODO(), options) + return client.CoreV1().PodTemplates(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().PodTemplates(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().PodTemplates(namespace).Watch(ctx, options) }, }, &apicorev1.PodTemplate{}, diff --git a/informers/core/v1/replicationcontroller.go b/informers/core/v1/replicationcontroller.go index 5866ec1510..89c216e821 100644 --- a/informers/core/v1/replicationcontroller.go +++ b/informers/core/v1/replicationcontroller.go @@ -62,13 +62,25 @@ func NewFilteredReplicationControllerInformer(client kubernetes.Interface, names if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ReplicationControllers(namespace).List(context.TODO(), options) + return client.CoreV1().ReplicationControllers(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ReplicationControllers(namespace).Watch(context.TODO(), options) + return client.CoreV1().ReplicationControllers(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ReplicationControllers(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ReplicationControllers(namespace).Watch(ctx, options) }, }, &apicorev1.ReplicationController{}, diff --git a/informers/core/v1/resourcequota.go b/informers/core/v1/resourcequota.go index 999b49546f..aa77e05702 100644 --- a/informers/core/v1/resourcequota.go +++ b/informers/core/v1/resourcequota.go @@ -62,13 +62,25 @@ func NewFilteredResourceQuotaInformer(client kubernetes.Interface, namespace str if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ResourceQuotas(namespace).List(context.TODO(), options) + return client.CoreV1().ResourceQuotas(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ResourceQuotas(namespace).Watch(context.TODO(), options) + return client.CoreV1().ResourceQuotas(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ResourceQuotas(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ResourceQuotas(namespace).Watch(ctx, options) }, }, &apicorev1.ResourceQuota{}, diff --git a/informers/core/v1/secret.go b/informers/core/v1/secret.go index f3d371501b..be5a80a969 100644 --- a/informers/core/v1/secret.go +++ b/informers/core/v1/secret.go @@ -62,13 +62,25 @@ func NewFilteredSecretInformer(client kubernetes.Interface, namespace string, re if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Secrets(namespace).List(context.TODO(), options) + return client.CoreV1().Secrets(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Secrets(namespace).Watch(context.TODO(), options) + return client.CoreV1().Secrets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Secrets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Secrets(namespace).Watch(ctx, options) }, }, &apicorev1.Secret{}, diff --git a/informers/core/v1/service.go b/informers/core/v1/service.go index c4bc294a3f..10b0587579 100644 --- a/informers/core/v1/service.go +++ b/informers/core/v1/service.go @@ -62,13 +62,25 @@ func NewFilteredServiceInformer(client kubernetes.Interface, namespace string, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Services(namespace).List(context.TODO(), options) + return client.CoreV1().Services(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().Services(namespace).Watch(context.TODO(), options) + return client.CoreV1().Services(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Services(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().Services(namespace).Watch(ctx, options) }, }, &apicorev1.Service{}, diff --git a/informers/core/v1/serviceaccount.go b/informers/core/v1/serviceaccount.go index b04b44cb41..594439618f 100644 --- a/informers/core/v1/serviceaccount.go +++ b/informers/core/v1/serviceaccount.go @@ -62,13 +62,25 @@ func NewFilteredServiceAccountInformer(client kubernetes.Interface, namespace st if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ServiceAccounts(namespace).List(context.TODO(), options) + return client.CoreV1().ServiceAccounts(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.CoreV1().ServiceAccounts(namespace).Watch(context.TODO(), options) + return client.CoreV1().ServiceAccounts(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ServiceAccounts(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CoreV1().ServiceAccounts(namespace).Watch(ctx, options) }, }, &apicorev1.ServiceAccount{}, diff --git a/informers/discovery/v1/endpointslice.go b/informers/discovery/v1/endpointslice.go index ec09b2d267..38f09183cd 100644 --- a/informers/discovery/v1/endpointslice.go +++ b/informers/discovery/v1/endpointslice.go @@ -62,13 +62,25 @@ func NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace str if tweakListOptions != nil { tweakListOptions(&options) } - return client.DiscoveryV1().EndpointSlices(namespace).List(context.TODO(), options) + return client.DiscoveryV1().EndpointSlices(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.DiscoveryV1().EndpointSlices(namespace).Watch(context.TODO(), options) + return client.DiscoveryV1().EndpointSlices(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.DiscoveryV1().EndpointSlices(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.DiscoveryV1().EndpointSlices(namespace).Watch(ctx, options) }, }, &apidiscoveryv1.EndpointSlice{}, diff --git a/informers/discovery/v1beta1/endpointslice.go b/informers/discovery/v1beta1/endpointslice.go index 3af1a3be99..23c51eb7b2 100644 --- a/informers/discovery/v1beta1/endpointslice.go +++ b/informers/discovery/v1beta1/endpointslice.go @@ -62,13 +62,25 @@ func NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace str if tweakListOptions != nil { tweakListOptions(&options) } - return client.DiscoveryV1beta1().EndpointSlices(namespace).List(context.TODO(), options) + return client.DiscoveryV1beta1().EndpointSlices(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.DiscoveryV1beta1().EndpointSlices(namespace).Watch(context.TODO(), options) + return client.DiscoveryV1beta1().EndpointSlices(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.DiscoveryV1beta1().EndpointSlices(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.DiscoveryV1beta1().EndpointSlices(namespace).Watch(ctx, options) }, }, &apidiscoveryv1beta1.EndpointSlice{}, diff --git a/informers/doc.go b/informers/doc.go index f37c3e4d01..231bffb69b 100644 --- a/informers/doc.go +++ b/informers/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package informers provides generated informers for Kubernetes APIs. -package informers // import "k8s.io/client-go/informers" +package informers diff --git a/informers/events/v1/event.go b/informers/events/v1/event.go index 518d798415..139cc155ab 100644 --- a/informers/events/v1/event.go +++ b/informers/events/v1/event.go @@ -62,13 +62,25 @@ func NewFilteredEventInformer(client kubernetes.Interface, namespace string, res if tweakListOptions != nil { tweakListOptions(&options) } - return client.EventsV1().Events(namespace).List(context.TODO(), options) + return client.EventsV1().Events(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.EventsV1().Events(namespace).Watch(context.TODO(), options) + return client.EventsV1().Events(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.EventsV1().Events(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.EventsV1().Events(namespace).Watch(ctx, options) }, }, &apieventsv1.Event{}, diff --git a/informers/events/v1beta1/event.go b/informers/events/v1beta1/event.go index 5324599bb7..75818c0efb 100644 --- a/informers/events/v1beta1/event.go +++ b/informers/events/v1beta1/event.go @@ -62,13 +62,25 @@ func NewFilteredEventInformer(client kubernetes.Interface, namespace string, res if tweakListOptions != nil { tweakListOptions(&options) } - return client.EventsV1beta1().Events(namespace).List(context.TODO(), options) + return client.EventsV1beta1().Events(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.EventsV1beta1().Events(namespace).Watch(context.TODO(), options) + return client.EventsV1beta1().Events(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.EventsV1beta1().Events(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.EventsV1beta1().Events(namespace).Watch(ctx, options) }, }, &apieventsv1beta1.Event{}, diff --git a/informers/extensions/v1beta1/daemonset.go b/informers/extensions/v1beta1/daemonset.go index ea77575c9e..ce8612c1c2 100644 --- a/informers/extensions/v1beta1/daemonset.go +++ b/informers/extensions/v1beta1/daemonset.go @@ -62,13 +62,25 @@ func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().DaemonSets(namespace).List(context.TODO(), options) + return client.ExtensionsV1beta1().DaemonSets(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().DaemonSets(namespace).Watch(context.TODO(), options) + return client.ExtensionsV1beta1().DaemonSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().DaemonSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().DaemonSets(namespace).Watch(ctx, options) }, }, &apiextensionsv1beta1.DaemonSet{}, diff --git a/informers/extensions/v1beta1/deployment.go b/informers/extensions/v1beta1/deployment.go index 1b2770ce0b..5dd957baa4 100644 --- a/informers/extensions/v1beta1/deployment.go +++ b/informers/extensions/v1beta1/deployment.go @@ -62,13 +62,25 @@ func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().Deployments(namespace).List(context.TODO(), options) + return client.ExtensionsV1beta1().Deployments(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().Deployments(namespace).Watch(context.TODO(), options) + return client.ExtensionsV1beta1().Deployments(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().Deployments(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().Deployments(namespace).Watch(ctx, options) }, }, &apiextensionsv1beta1.Deployment{}, diff --git a/informers/extensions/v1beta1/ingress.go b/informers/extensions/v1beta1/ingress.go index 63e7340604..935f6868c2 100644 --- a/informers/extensions/v1beta1/ingress.go +++ b/informers/extensions/v1beta1/ingress.go @@ -62,13 +62,25 @@ func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().Ingresses(namespace).List(context.TODO(), options) + return client.ExtensionsV1beta1().Ingresses(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().Ingresses(namespace).Watch(context.TODO(), options) + return client.ExtensionsV1beta1().Ingresses(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().Ingresses(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().Ingresses(namespace).Watch(ctx, options) }, }, &apiextensionsv1beta1.Ingress{}, diff --git a/informers/extensions/v1beta1/networkpolicy.go b/informers/extensions/v1beta1/networkpolicy.go index 024653af2e..f485f3149c 100644 --- a/informers/extensions/v1beta1/networkpolicy.go +++ b/informers/extensions/v1beta1/networkpolicy.go @@ -62,13 +62,25 @@ func NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace str if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().NetworkPolicies(namespace).List(context.TODO(), options) + return client.ExtensionsV1beta1().NetworkPolicies(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().NetworkPolicies(namespace).Watch(context.TODO(), options) + return client.ExtensionsV1beta1().NetworkPolicies(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().NetworkPolicies(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().NetworkPolicies(namespace).Watch(ctx, options) }, }, &apiextensionsv1beta1.NetworkPolicy{}, diff --git a/informers/extensions/v1beta1/replicaset.go b/informers/extensions/v1beta1/replicaset.go index 392ccef861..4b1be5421c 100644 --- a/informers/extensions/v1beta1/replicaset.go +++ b/informers/extensions/v1beta1/replicaset.go @@ -62,13 +62,25 @@ func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().ReplicaSets(namespace).List(context.TODO(), options) + return client.ExtensionsV1beta1().ReplicaSets(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ExtensionsV1beta1().ReplicaSets(namespace).Watch(context.TODO(), options) + return client.ExtensionsV1beta1().ReplicaSets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().ReplicaSets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ExtensionsV1beta1().ReplicaSets(namespace).Watch(ctx, options) }, }, &apiextensionsv1beta1.ReplicaSet{}, diff --git a/informers/flowcontrol/v1/flowschema.go b/informers/flowcontrol/v1/flowschema.go index 945bc351ef..f8918dcf72 100644 --- a/informers/flowcontrol/v1/flowschema.go +++ b/informers/flowcontrol/v1/flowschema.go @@ -61,13 +61,25 @@ func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod tim if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1().FlowSchemas().List(context.TODO(), options) + return client.FlowcontrolV1().FlowSchemas().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1().FlowSchemas().Watch(context.TODO(), options) + return client.FlowcontrolV1().FlowSchemas().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1().FlowSchemas().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1().FlowSchemas().Watch(ctx, options) }, }, &apiflowcontrolv1.FlowSchema{}, diff --git a/informers/flowcontrol/v1/prioritylevelconfiguration.go b/informers/flowcontrol/v1/prioritylevelconfiguration.go index eec6388b29..2ec4f39887 100644 --- a/informers/flowcontrol/v1/prioritylevelconfiguration.go +++ b/informers/flowcontrol/v1/prioritylevelconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1().PriorityLevelConfigurations().List(context.TODO(), options) + return client.FlowcontrolV1().PriorityLevelConfigurations().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1().PriorityLevelConfigurations().Watch(context.TODO(), options) + return client.FlowcontrolV1().PriorityLevelConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1().PriorityLevelConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1().PriorityLevelConfigurations().Watch(ctx, options) }, }, &apiflowcontrolv1.PriorityLevelConfiguration{}, diff --git a/informers/flowcontrol/v1beta1/flowschema.go b/informers/flowcontrol/v1beta1/flowschema.go index 30d0997739..322fa31813 100644 --- a/informers/flowcontrol/v1beta1/flowschema.go +++ b/informers/flowcontrol/v1beta1/flowschema.go @@ -61,13 +61,25 @@ func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod tim if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta1().FlowSchemas().List(context.TODO(), options) + return client.FlowcontrolV1beta1().FlowSchemas().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta1().FlowSchemas().Watch(context.TODO(), options) + return client.FlowcontrolV1beta1().FlowSchemas().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta1().FlowSchemas().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta1().FlowSchemas().Watch(ctx, options) }, }, &apiflowcontrolv1beta1.FlowSchema{}, diff --git a/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go b/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go index 2a8a867c43..aebc788f7e 100644 --- a/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go +++ b/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta1().PriorityLevelConfigurations().List(context.TODO(), options) + return client.FlowcontrolV1beta1().PriorityLevelConfigurations().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta1().PriorityLevelConfigurations().Watch(context.TODO(), options) + return client.FlowcontrolV1beta1().PriorityLevelConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta1().PriorityLevelConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta1().PriorityLevelConfigurations().Watch(ctx, options) }, }, &apiflowcontrolv1beta1.PriorityLevelConfiguration{}, diff --git a/informers/flowcontrol/v1beta2/flowschema.go b/informers/flowcontrol/v1beta2/flowschema.go index edfed12c5c..522e24b7b5 100644 --- a/informers/flowcontrol/v1beta2/flowschema.go +++ b/informers/flowcontrol/v1beta2/flowschema.go @@ -61,13 +61,25 @@ func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod tim if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta2().FlowSchemas().List(context.TODO(), options) + return client.FlowcontrolV1beta2().FlowSchemas().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta2().FlowSchemas().Watch(context.TODO(), options) + return client.FlowcontrolV1beta2().FlowSchemas().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta2().FlowSchemas().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta2().FlowSchemas().Watch(ctx, options) }, }, &apiflowcontrolv1beta2.FlowSchema{}, diff --git a/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go b/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go index 624e0373e8..0ee0506e25 100644 --- a/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go +++ b/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta2().PriorityLevelConfigurations().List(context.TODO(), options) + return client.FlowcontrolV1beta2().PriorityLevelConfigurations().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta2().PriorityLevelConfigurations().Watch(context.TODO(), options) + return client.FlowcontrolV1beta2().PriorityLevelConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta2().PriorityLevelConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta2().PriorityLevelConfigurations().Watch(ctx, options) }, }, &apiflowcontrolv1beta2.PriorityLevelConfiguration{}, diff --git a/informers/flowcontrol/v1beta3/flowschema.go b/informers/flowcontrol/v1beta3/flowschema.go index bd3f5e6edb..3b0dca3cc2 100644 --- a/informers/flowcontrol/v1beta3/flowschema.go +++ b/informers/flowcontrol/v1beta3/flowschema.go @@ -61,13 +61,25 @@ func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod tim if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta3().FlowSchemas().List(context.TODO(), options) + return client.FlowcontrolV1beta3().FlowSchemas().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta3().FlowSchemas().Watch(context.TODO(), options) + return client.FlowcontrolV1beta3().FlowSchemas().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta3().FlowSchemas().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta3().FlowSchemas().Watch(ctx, options) }, }, &apiflowcontrolv1beta3.FlowSchema{}, diff --git a/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go b/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go index 5695d5d4dd..77ff4e4e7c 100644 --- a/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go +++ b/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go @@ -61,13 +61,25 @@ func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta3().PriorityLevelConfigurations().List(context.TODO(), options) + return client.FlowcontrolV1beta3().PriorityLevelConfigurations().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.FlowcontrolV1beta3().PriorityLevelConfigurations().Watch(context.TODO(), options) + return client.FlowcontrolV1beta3().PriorityLevelConfigurations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta3().PriorityLevelConfigurations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.FlowcontrolV1beta3().PriorityLevelConfigurations().Watch(ctx, options) }, }, &apiflowcontrolv1beta3.PriorityLevelConfiguration{}, diff --git a/informers/generic.go b/informers/generic.go index fd331686d5..9659553545 100644 --- a/informers/generic.go +++ b/informers/generic.go @@ -63,6 +63,7 @@ import ( rbacv1beta1 "k8s.io/api/rbac/v1beta1" v1alpha3 "k8s.io/api/resource/v1alpha3" resourcev1beta1 "k8s.io/api/resource/v1beta1" + resourcev1beta2 "k8s.io/api/resource/v1beta2" schedulingv1 "k8s.io/api/scheduling/v1" schedulingv1alpha1 "k8s.io/api/scheduling/v1alpha1" schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" @@ -199,6 +200,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource // Group=certificates.k8s.io, Version=v1beta1 case certificatesv1beta1.SchemeGroupVersion.WithResource("certificatesigningrequests"): return &genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1beta1().CertificateSigningRequests().Informer()}, nil + case certificatesv1beta1.SchemeGroupVersion.WithResource("clustertrustbundles"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1beta1().ClusterTrustBundles().Informer()}, nil // Group=coordination.k8s.io, Version=v1 case coordinationv1.SchemeGroupVersion.WithResource("leases"): @@ -211,6 +214,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource // Group=coordination.k8s.io, Version=v1beta1 case coordinationv1beta1.SchemeGroupVersion.WithResource("leases"): return &genericInformer{resource: resource.GroupResource(), informer: f.Coordination().V1beta1().Leases().Informer()}, nil + case coordinationv1beta1.SchemeGroupVersion.WithResource("leasecandidates"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Coordination().V1beta1().LeaseCandidates().Informer()}, nil // Group=core, Version=v1 case corev1.SchemeGroupVersion.WithResource("componentstatuses"): @@ -303,12 +308,16 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Internal().V1alpha1().StorageVersions().Informer()}, nil // Group=networking.k8s.io, Version=v1 + case networkingv1.SchemeGroupVersion.WithResource("ipaddresses"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().IPAddresses().Informer()}, nil case networkingv1.SchemeGroupVersion.WithResource("ingresses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().Ingresses().Informer()}, nil case networkingv1.SchemeGroupVersion.WithResource("ingressclasses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().IngressClasses().Informer()}, nil case networkingv1.SchemeGroupVersion.WithResource("networkpolicies"): return &genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().NetworkPolicies().Informer()}, nil + case networkingv1.SchemeGroupVersion.WithResource("servicecidrs"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().ServiceCIDRs().Informer()}, nil // Group=networking.k8s.io, Version=v1alpha1 case networkingv1alpha1.SchemeGroupVersion.WithResource("ipaddresses"): @@ -379,6 +388,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource // Group=resource.k8s.io, Version=v1alpha3 case v1alpha3.SchemeGroupVersion.WithResource("deviceclasses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1alpha3().DeviceClasses().Informer()}, nil + case v1alpha3.SchemeGroupVersion.WithResource("devicetaintrules"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1alpha3().DeviceTaintRules().Informer()}, nil case v1alpha3.SchemeGroupVersion.WithResource("resourceclaims"): return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1alpha3().ResourceClaims().Informer()}, nil case v1alpha3.SchemeGroupVersion.WithResource("resourceclaimtemplates"): @@ -396,6 +407,16 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case resourcev1beta1.SchemeGroupVersion.WithResource("resourceslices"): return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1beta1().ResourceSlices().Informer()}, nil + // Group=resource.k8s.io, Version=v1beta2 + case resourcev1beta2.SchemeGroupVersion.WithResource("deviceclasses"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1beta2().DeviceClasses().Informer()}, nil + case resourcev1beta2.SchemeGroupVersion.WithResource("resourceclaims"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1beta2().ResourceClaims().Informer()}, nil + case resourcev1beta2.SchemeGroupVersion.WithResource("resourceclaimtemplates"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1beta2().ResourceClaimTemplates().Informer()}, nil + case resourcev1beta2.SchemeGroupVersion.WithResource("resourceslices"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1beta2().ResourceSlices().Informer()}, nil + // Group=scheduling.k8s.io, Version=v1 case schedulingv1.SchemeGroupVersion.WithResource("priorityclasses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1().PriorityClasses().Informer()}, nil diff --git a/informers/networking/v1/ingress.go b/informers/networking/v1/ingress.go index a0deccf16e..6f1b0b7816 100644 --- a/informers/networking/v1/ingress.go +++ b/informers/networking/v1/ingress.go @@ -62,13 +62,25 @@ func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1().Ingresses(namespace).List(context.TODO(), options) + return client.NetworkingV1().Ingresses(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1().Ingresses(namespace).Watch(context.TODO(), options) + return client.NetworkingV1().Ingresses(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().Ingresses(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().Ingresses(namespace).Watch(ctx, options) }, }, &apinetworkingv1.Ingress{}, diff --git a/informers/networking/v1/ingressclass.go b/informers/networking/v1/ingressclass.go index 7eb1745169..b0d4803d89 100644 --- a/informers/networking/v1/ingressclass.go +++ b/informers/networking/v1/ingressclass.go @@ -61,13 +61,25 @@ func NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod t if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1().IngressClasses().List(context.TODO(), options) + return client.NetworkingV1().IngressClasses().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1().IngressClasses().Watch(context.TODO(), options) + return client.NetworkingV1().IngressClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().IngressClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().IngressClasses().Watch(ctx, options) }, }, &apinetworkingv1.IngressClass{}, diff --git a/informers/networking/v1/interface.go b/informers/networking/v1/interface.go index a48d92c4ef..09634929b3 100644 --- a/informers/networking/v1/interface.go +++ b/informers/networking/v1/interface.go @@ -24,12 +24,16 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { + // IPAddresses returns a IPAddressInformer. + IPAddresses() IPAddressInformer // Ingresses returns a IngressInformer. Ingresses() IngressInformer // IngressClasses returns a IngressClassInformer. IngressClasses() IngressClassInformer // NetworkPolicies returns a NetworkPolicyInformer. NetworkPolicies() NetworkPolicyInformer + // ServiceCIDRs returns a ServiceCIDRInformer. + ServiceCIDRs() ServiceCIDRInformer } type version struct { @@ -43,6 +47,11 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } +// IPAddresses returns a IPAddressInformer. +func (v *version) IPAddresses() IPAddressInformer { + return &iPAddressInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} + // Ingresses returns a IngressInformer. func (v *version) Ingresses() IngressInformer { return &ingressInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} @@ -57,3 +66,8 @@ func (v *version) IngressClasses() IngressClassInformer { func (v *version) NetworkPolicies() NetworkPolicyInformer { return &networkPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } + +// ServiceCIDRs returns a ServiceCIDRInformer. +func (v *version) ServiceCIDRs() ServiceCIDRInformer { + return &serviceCIDRInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} diff --git a/informers/networking/v1/ipaddress.go b/informers/networking/v1/ipaddress.go new file mode 100644 index 0000000000..e3459e72ba --- /dev/null +++ b/informers/networking/v1/ipaddress.go @@ -0,0 +1,101 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + time "time" + + apinetworkingv1 "k8s.io/api/networking/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + networkingv1 "k8s.io/client-go/listers/networking/v1" + cache "k8s.io/client-go/tools/cache" +) + +// IPAddressInformer provides access to a shared informer and lister for +// IPAddresses. +type IPAddressInformer interface { + Informer() cache.SharedIndexInformer + Lister() networkingv1.IPAddressLister +} + +type iPAddressInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewIPAddressInformer constructs a new informer for IPAddress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredIPAddressInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredIPAddressInformer constructs a new informer for IPAddress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().IPAddresses().List(context.Background(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().IPAddresses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().IPAddresses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().IPAddresses().Watch(ctx, options) + }, + }, + &apinetworkingv1.IPAddress{}, + resyncPeriod, + indexers, + ) +} + +func (f *iPAddressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredIPAddressInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *iPAddressInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apinetworkingv1.IPAddress{}, f.defaultInformer) +} + +func (f *iPAddressInformer) Lister() networkingv1.IPAddressLister { + return networkingv1.NewIPAddressLister(f.Informer().GetIndexer()) +} diff --git a/informers/networking/v1/networkpolicy.go b/informers/networking/v1/networkpolicy.go index d4bac29112..0dba59c5ef 100644 --- a/informers/networking/v1/networkpolicy.go +++ b/informers/networking/v1/networkpolicy.go @@ -62,13 +62,25 @@ func NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace str if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1().NetworkPolicies(namespace).List(context.TODO(), options) + return client.NetworkingV1().NetworkPolicies(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1().NetworkPolicies(namespace).Watch(context.TODO(), options) + return client.NetworkingV1().NetworkPolicies(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().NetworkPolicies(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().NetworkPolicies(namespace).Watch(ctx, options) }, }, &apinetworkingv1.NetworkPolicy{}, diff --git a/informers/networking/v1/servicecidr.go b/informers/networking/v1/servicecidr.go new file mode 100644 index 0000000000..039cdc7539 --- /dev/null +++ b/informers/networking/v1/servicecidr.go @@ -0,0 +1,101 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + time "time" + + apinetworkingv1 "k8s.io/api/networking/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + networkingv1 "k8s.io/client-go/listers/networking/v1" + cache "k8s.io/client-go/tools/cache" +) + +// ServiceCIDRInformer provides access to a shared informer and lister for +// ServiceCIDRs. +type ServiceCIDRInformer interface { + Informer() cache.SharedIndexInformer + Lister() networkingv1.ServiceCIDRLister +} + +type serviceCIDRInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewServiceCIDRInformer constructs a new informer for ServiceCIDR type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredServiceCIDRInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredServiceCIDRInformer constructs a new informer for ServiceCIDR type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().ServiceCIDRs().List(context.Background(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().ServiceCIDRs().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().ServiceCIDRs().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1().ServiceCIDRs().Watch(ctx, options) + }, + }, + &apinetworkingv1.ServiceCIDR{}, + resyncPeriod, + indexers, + ) +} + +func (f *serviceCIDRInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredServiceCIDRInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *serviceCIDRInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apinetworkingv1.ServiceCIDR{}, f.defaultInformer) +} + +func (f *serviceCIDRInformer) Lister() networkingv1.ServiceCIDRLister { + return networkingv1.NewServiceCIDRLister(f.Informer().GetIndexer()) +} diff --git a/informers/networking/v1alpha1/ipaddress.go b/informers/networking/v1alpha1/ipaddress.go index f04c14535e..f357be93b8 100644 --- a/informers/networking/v1alpha1/ipaddress.go +++ b/informers/networking/v1alpha1/ipaddress.go @@ -61,13 +61,25 @@ func NewFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1alpha1().IPAddresses().List(context.TODO(), options) + return client.NetworkingV1alpha1().IPAddresses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1alpha1().IPAddresses().Watch(context.TODO(), options) + return client.NetworkingV1alpha1().IPAddresses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1alpha1().IPAddresses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1alpha1().IPAddresses().Watch(ctx, options) }, }, &apinetworkingv1alpha1.IPAddress{}, diff --git a/informers/networking/v1alpha1/servicecidr.go b/informers/networking/v1alpha1/servicecidr.go index 86af6d226d..30cb61a653 100644 --- a/informers/networking/v1alpha1/servicecidr.go +++ b/informers/networking/v1alpha1/servicecidr.go @@ -61,13 +61,25 @@ func NewFilteredServiceCIDRInformer(client kubernetes.Interface, resyncPeriod ti if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1alpha1().ServiceCIDRs().List(context.TODO(), options) + return client.NetworkingV1alpha1().ServiceCIDRs().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1alpha1().ServiceCIDRs().Watch(context.TODO(), options) + return client.NetworkingV1alpha1().ServiceCIDRs().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1alpha1().ServiceCIDRs().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1alpha1().ServiceCIDRs().Watch(ctx, options) }, }, &apinetworkingv1alpha1.ServiceCIDR{}, diff --git a/informers/networking/v1beta1/ingress.go b/informers/networking/v1beta1/ingress.go index aa337d8e7f..6c616b902b 100644 --- a/informers/networking/v1beta1/ingress.go +++ b/informers/networking/v1beta1/ingress.go @@ -62,13 +62,25 @@ func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, r if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().Ingresses(namespace).List(context.TODO(), options) + return client.NetworkingV1beta1().Ingresses(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().Ingresses(namespace).Watch(context.TODO(), options) + return client.NetworkingV1beta1().Ingresses(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().Ingresses(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().Ingresses(namespace).Watch(ctx, options) }, }, &apinetworkingv1beta1.Ingress{}, diff --git a/informers/networking/v1beta1/ingressclass.go b/informers/networking/v1beta1/ingressclass.go index 6ff9d51695..dd3a9aa7c5 100644 --- a/informers/networking/v1beta1/ingressclass.go +++ b/informers/networking/v1beta1/ingressclass.go @@ -61,13 +61,25 @@ func NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod t if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().IngressClasses().List(context.TODO(), options) + return client.NetworkingV1beta1().IngressClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().IngressClasses().Watch(context.TODO(), options) + return client.NetworkingV1beta1().IngressClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().IngressClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().IngressClasses().Watch(ctx, options) }, }, &apinetworkingv1beta1.IngressClass{}, diff --git a/informers/networking/v1beta1/ipaddress.go b/informers/networking/v1beta1/ipaddress.go index 401ecd7cba..32ce3c4a8a 100644 --- a/informers/networking/v1beta1/ipaddress.go +++ b/informers/networking/v1beta1/ipaddress.go @@ -61,13 +61,25 @@ func NewFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().IPAddresses().List(context.TODO(), options) + return client.NetworkingV1beta1().IPAddresses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().IPAddresses().Watch(context.TODO(), options) + return client.NetworkingV1beta1().IPAddresses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().IPAddresses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().IPAddresses().Watch(ctx, options) }, }, &apinetworkingv1beta1.IPAddress{}, diff --git a/informers/networking/v1beta1/servicecidr.go b/informers/networking/v1beta1/servicecidr.go index ff40692f29..25843d2fef 100644 --- a/informers/networking/v1beta1/servicecidr.go +++ b/informers/networking/v1beta1/servicecidr.go @@ -61,13 +61,25 @@ func NewFilteredServiceCIDRInformer(client kubernetes.Interface, resyncPeriod ti if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().ServiceCIDRs().List(context.TODO(), options) + return client.NetworkingV1beta1().ServiceCIDRs().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NetworkingV1beta1().ServiceCIDRs().Watch(context.TODO(), options) + return client.NetworkingV1beta1().ServiceCIDRs().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().ServiceCIDRs().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NetworkingV1beta1().ServiceCIDRs().Watch(ctx, options) }, }, &apinetworkingv1beta1.ServiceCIDR{}, diff --git a/informers/node/v1/runtimeclass.go b/informers/node/v1/runtimeclass.go index 7fef7e3328..85625e3e01 100644 --- a/informers/node/v1/runtimeclass.go +++ b/informers/node/v1/runtimeclass.go @@ -61,13 +61,25 @@ func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod t if tweakListOptions != nil { tweakListOptions(&options) } - return client.NodeV1().RuntimeClasses().List(context.TODO(), options) + return client.NodeV1().RuntimeClasses().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NodeV1().RuntimeClasses().Watch(context.TODO(), options) + return client.NodeV1().RuntimeClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NodeV1().RuntimeClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NodeV1().RuntimeClasses().Watch(ctx, options) }, }, &apinodev1.RuntimeClass{}, diff --git a/informers/node/v1alpha1/runtimeclass.go b/informers/node/v1alpha1/runtimeclass.go index aee61406f1..b3ac2e2a22 100644 --- a/informers/node/v1alpha1/runtimeclass.go +++ b/informers/node/v1alpha1/runtimeclass.go @@ -61,13 +61,25 @@ func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod t if tweakListOptions != nil { tweakListOptions(&options) } - return client.NodeV1alpha1().RuntimeClasses().List(context.TODO(), options) + return client.NodeV1alpha1().RuntimeClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NodeV1alpha1().RuntimeClasses().Watch(context.TODO(), options) + return client.NodeV1alpha1().RuntimeClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NodeV1alpha1().RuntimeClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NodeV1alpha1().RuntimeClasses().Watch(ctx, options) }, }, &apinodev1alpha1.RuntimeClass{}, diff --git a/informers/node/v1beta1/runtimeclass.go b/informers/node/v1beta1/runtimeclass.go index ab9b8e0eee..b562476d48 100644 --- a/informers/node/v1beta1/runtimeclass.go +++ b/informers/node/v1beta1/runtimeclass.go @@ -61,13 +61,25 @@ func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod t if tweakListOptions != nil { tweakListOptions(&options) } - return client.NodeV1beta1().RuntimeClasses().List(context.TODO(), options) + return client.NodeV1beta1().RuntimeClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.NodeV1beta1().RuntimeClasses().Watch(context.TODO(), options) + return client.NodeV1beta1().RuntimeClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NodeV1beta1().RuntimeClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.NodeV1beta1().RuntimeClasses().Watch(ctx, options) }, }, &apinodev1beta1.RuntimeClass{}, diff --git a/informers/policy/v1/poddisruptionbudget.go b/informers/policy/v1/poddisruptionbudget.go index baacb59daa..f80d7dd914 100644 --- a/informers/policy/v1/poddisruptionbudget.go +++ b/informers/policy/v1/poddisruptionbudget.go @@ -62,13 +62,25 @@ func NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespa if tweakListOptions != nil { tweakListOptions(&options) } - return client.PolicyV1().PodDisruptionBudgets(namespace).List(context.TODO(), options) + return client.PolicyV1().PodDisruptionBudgets(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.PolicyV1().PodDisruptionBudgets(namespace).Watch(context.TODO(), options) + return client.PolicyV1().PodDisruptionBudgets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.PolicyV1().PodDisruptionBudgets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.PolicyV1().PodDisruptionBudgets(namespace).Watch(ctx, options) }, }, &apipolicyv1.PodDisruptionBudget{}, diff --git a/informers/policy/v1beta1/poddisruptionbudget.go b/informers/policy/v1beta1/poddisruptionbudget.go index 081b2e08e4..92e37d0eb7 100644 --- a/informers/policy/v1beta1/poddisruptionbudget.go +++ b/informers/policy/v1beta1/poddisruptionbudget.go @@ -62,13 +62,25 @@ func NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespa if tweakListOptions != nil { tweakListOptions(&options) } - return client.PolicyV1beta1().PodDisruptionBudgets(namespace).List(context.TODO(), options) + return client.PolicyV1beta1().PodDisruptionBudgets(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.PolicyV1beta1().PodDisruptionBudgets(namespace).Watch(context.TODO(), options) + return client.PolicyV1beta1().PodDisruptionBudgets(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.PolicyV1beta1().PodDisruptionBudgets(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.PolicyV1beta1().PodDisruptionBudgets(namespace).Watch(ctx, options) }, }, &apipolicyv1beta1.PodDisruptionBudget{}, diff --git a/informers/rbac/v1/clusterrole.go b/informers/rbac/v1/clusterrole.go index 0606fb4646..4118bffff6 100644 --- a/informers/rbac/v1/clusterrole.go +++ b/informers/rbac/v1/clusterrole.go @@ -61,13 +61,25 @@ func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod ti if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().ClusterRoles().List(context.TODO(), options) + return client.RbacV1().ClusterRoles().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().ClusterRoles().Watch(context.TODO(), options) + return client.RbacV1().ClusterRoles().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().ClusterRoles().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().ClusterRoles().Watch(ctx, options) }, }, &apirbacv1.ClusterRole{}, diff --git a/informers/rbac/v1/clusterrolebinding.go b/informers/rbac/v1/clusterrolebinding.go index dca087c9d2..67c06d6012 100644 --- a/informers/rbac/v1/clusterrolebinding.go +++ b/informers/rbac/v1/clusterrolebinding.go @@ -61,13 +61,25 @@ func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPe if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().ClusterRoleBindings().List(context.TODO(), options) + return client.RbacV1().ClusterRoleBindings().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().ClusterRoleBindings().Watch(context.TODO(), options) + return client.RbacV1().ClusterRoleBindings().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().ClusterRoleBindings().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().ClusterRoleBindings().Watch(ctx, options) }, }, &apirbacv1.ClusterRoleBinding{}, diff --git a/informers/rbac/v1/role.go b/informers/rbac/v1/role.go index 66f9c3f23c..e931d23962 100644 --- a/informers/rbac/v1/role.go +++ b/informers/rbac/v1/role.go @@ -62,13 +62,25 @@ func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resy if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().Roles(namespace).List(context.TODO(), options) + return client.RbacV1().Roles(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().Roles(namespace).Watch(context.TODO(), options) + return client.RbacV1().Roles(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().Roles(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().Roles(namespace).Watch(ctx, options) }, }, &apirbacv1.Role{}, diff --git a/informers/rbac/v1/rolebinding.go b/informers/rbac/v1/rolebinding.go index 6d72601a48..89b11efff2 100644 --- a/informers/rbac/v1/rolebinding.go +++ b/informers/rbac/v1/rolebinding.go @@ -62,13 +62,25 @@ func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace strin if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().RoleBindings(namespace).List(context.TODO(), options) + return client.RbacV1().RoleBindings(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1().RoleBindings(namespace).Watch(context.TODO(), options) + return client.RbacV1().RoleBindings(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().RoleBindings(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1().RoleBindings(namespace).Watch(ctx, options) }, }, &apirbacv1.RoleBinding{}, diff --git a/informers/rbac/v1alpha1/clusterrole.go b/informers/rbac/v1alpha1/clusterrole.go index 52249f6b4e..ff95f62ff9 100644 --- a/informers/rbac/v1alpha1/clusterrole.go +++ b/informers/rbac/v1alpha1/clusterrole.go @@ -61,13 +61,25 @@ func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod ti if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().ClusterRoles().List(context.TODO(), options) + return client.RbacV1alpha1().ClusterRoles().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().ClusterRoles().Watch(context.TODO(), options) + return client.RbacV1alpha1().ClusterRoles().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().ClusterRoles().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().ClusterRoles().Watch(ctx, options) }, }, &apirbacv1alpha1.ClusterRole{}, diff --git a/informers/rbac/v1alpha1/clusterrolebinding.go b/informers/rbac/v1alpha1/clusterrolebinding.go index c8f7c4c10e..1002f16300 100644 --- a/informers/rbac/v1alpha1/clusterrolebinding.go +++ b/informers/rbac/v1alpha1/clusterrolebinding.go @@ -61,13 +61,25 @@ func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPe if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().ClusterRoleBindings().List(context.TODO(), options) + return client.RbacV1alpha1().ClusterRoleBindings().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().ClusterRoleBindings().Watch(context.TODO(), options) + return client.RbacV1alpha1().ClusterRoleBindings().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().ClusterRoleBindings().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().ClusterRoleBindings().Watch(ctx, options) }, }, &apirbacv1alpha1.ClusterRoleBinding{}, diff --git a/informers/rbac/v1alpha1/role.go b/informers/rbac/v1alpha1/role.go index dcdddc0576..ad7b1c0b8b 100644 --- a/informers/rbac/v1alpha1/role.go +++ b/informers/rbac/v1alpha1/role.go @@ -62,13 +62,25 @@ func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resy if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().Roles(namespace).List(context.TODO(), options) + return client.RbacV1alpha1().Roles(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().Roles(namespace).Watch(context.TODO(), options) + return client.RbacV1alpha1().Roles(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().Roles(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().Roles(namespace).Watch(ctx, options) }, }, &apirbacv1alpha1.Role{}, diff --git a/informers/rbac/v1alpha1/rolebinding.go b/informers/rbac/v1alpha1/rolebinding.go index 9184a5baf4..c5d915d23a 100644 --- a/informers/rbac/v1alpha1/rolebinding.go +++ b/informers/rbac/v1alpha1/rolebinding.go @@ -62,13 +62,25 @@ func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace strin if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().RoleBindings(namespace).List(context.TODO(), options) + return client.RbacV1alpha1().RoleBindings(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1alpha1().RoleBindings(namespace).Watch(context.TODO(), options) + return client.RbacV1alpha1().RoleBindings(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().RoleBindings(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1alpha1().RoleBindings(namespace).Watch(ctx, options) }, }, &apirbacv1alpha1.RoleBinding{}, diff --git a/informers/rbac/v1beta1/clusterrole.go b/informers/rbac/v1beta1/clusterrole.go index d86dd771ab..24aad0b826 100644 --- a/informers/rbac/v1beta1/clusterrole.go +++ b/informers/rbac/v1beta1/clusterrole.go @@ -61,13 +61,25 @@ func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod ti if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().ClusterRoles().List(context.TODO(), options) + return client.RbacV1beta1().ClusterRoles().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().ClusterRoles().Watch(context.TODO(), options) + return client.RbacV1beta1().ClusterRoles().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().ClusterRoles().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().ClusterRoles().Watch(ctx, options) }, }, &apirbacv1beta1.ClusterRole{}, diff --git a/informers/rbac/v1beta1/clusterrolebinding.go b/informers/rbac/v1beta1/clusterrolebinding.go index 70c1cd9842..3506b79722 100644 --- a/informers/rbac/v1beta1/clusterrolebinding.go +++ b/informers/rbac/v1beta1/clusterrolebinding.go @@ -61,13 +61,25 @@ func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPe if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().ClusterRoleBindings().List(context.TODO(), options) + return client.RbacV1beta1().ClusterRoleBindings().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().ClusterRoleBindings().Watch(context.TODO(), options) + return client.RbacV1beta1().ClusterRoleBindings().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().ClusterRoleBindings().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().ClusterRoleBindings().Watch(ctx, options) }, }, &apirbacv1beta1.ClusterRoleBinding{}, diff --git a/informers/rbac/v1beta1/role.go b/informers/rbac/v1beta1/role.go index 2995e1e63e..119a601f09 100644 --- a/informers/rbac/v1beta1/role.go +++ b/informers/rbac/v1beta1/role.go @@ -62,13 +62,25 @@ func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resy if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().Roles(namespace).List(context.TODO(), options) + return client.RbacV1beta1().Roles(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().Roles(namespace).Watch(context.TODO(), options) + return client.RbacV1beta1().Roles(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().Roles(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().Roles(namespace).Watch(ctx, options) }, }, &apirbacv1beta1.Role{}, diff --git a/informers/rbac/v1beta1/rolebinding.go b/informers/rbac/v1beta1/rolebinding.go index 11854f38de..c36c295c0c 100644 --- a/informers/rbac/v1beta1/rolebinding.go +++ b/informers/rbac/v1beta1/rolebinding.go @@ -62,13 +62,25 @@ func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace strin if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().RoleBindings(namespace).List(context.TODO(), options) + return client.RbacV1beta1().RoleBindings(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.RbacV1beta1().RoleBindings(namespace).Watch(context.TODO(), options) + return client.RbacV1beta1().RoleBindings(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().RoleBindings(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.RbacV1beta1().RoleBindings(namespace).Watch(ctx, options) }, }, &apirbacv1beta1.RoleBinding{}, diff --git a/informers/resource/interface.go b/informers/resource/interface.go index 0d75732af6..f4bcd92706 100644 --- a/informers/resource/interface.go +++ b/informers/resource/interface.go @@ -22,6 +22,7 @@ import ( internalinterfaces "k8s.io/client-go/informers/internalinterfaces" v1alpha3 "k8s.io/client-go/informers/resource/v1alpha3" v1beta1 "k8s.io/client-go/informers/resource/v1beta1" + v1beta2 "k8s.io/client-go/informers/resource/v1beta2" ) // Interface provides access to each of this group's versions. @@ -30,6 +31,8 @@ type Interface interface { V1alpha3() v1alpha3.Interface // V1beta1 provides access to shared informers for resources in V1beta1. V1beta1() v1beta1.Interface + // V1beta2 provides access to shared informers for resources in V1beta2. + V1beta2() v1beta2.Interface } type group struct { @@ -52,3 +55,8 @@ func (g *group) V1alpha3() v1alpha3.Interface { func (g *group) V1beta1() v1beta1.Interface { return v1beta1.New(g.factory, g.namespace, g.tweakListOptions) } + +// V1beta2 returns a new v1beta2.Interface. +func (g *group) V1beta2() v1beta2.Interface { + return v1beta2.New(g.factory, g.namespace, g.tweakListOptions) +} diff --git a/informers/resource/v1alpha3/deviceclass.go b/informers/resource/v1alpha3/deviceclass.go index da322c8d04..cff6279196 100644 --- a/informers/resource/v1alpha3/deviceclass.go +++ b/informers/resource/v1alpha3/deviceclass.go @@ -61,13 +61,25 @@ func NewFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod ti if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().DeviceClasses().List(context.TODO(), options) + return client.ResourceV1alpha3().DeviceClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().DeviceClasses().Watch(context.TODO(), options) + return client.ResourceV1alpha3().DeviceClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().DeviceClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().DeviceClasses().Watch(ctx, options) }, }, &apiresourcev1alpha3.DeviceClass{}, diff --git a/informers/resource/v1alpha3/devicetaintrule.go b/informers/resource/v1alpha3/devicetaintrule.go new file mode 100644 index 0000000000..9a07c8f4e5 --- /dev/null +++ b/informers/resource/v1alpha3/devicetaintrule.go @@ -0,0 +1,101 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + context "context" + time "time" + + apiresourcev1alpha3 "k8s.io/api/resource/v1alpha3" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + resourcev1alpha3 "k8s.io/client-go/listers/resource/v1alpha3" + cache "k8s.io/client-go/tools/cache" +) + +// DeviceTaintRuleInformer provides access to a shared informer and lister for +// DeviceTaintRules. +type DeviceTaintRuleInformer interface { + Informer() cache.SharedIndexInformer + Lister() resourcev1alpha3.DeviceTaintRuleLister +} + +type deviceTaintRuleInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredDeviceTaintRuleInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().DeviceTaintRules().List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().DeviceTaintRules().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().DeviceTaintRules().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().DeviceTaintRules().Watch(ctx, options) + }, + }, + &apiresourcev1alpha3.DeviceTaintRule{}, + resyncPeriod, + indexers, + ) +} + +func (f *deviceTaintRuleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredDeviceTaintRuleInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *deviceTaintRuleInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apiresourcev1alpha3.DeviceTaintRule{}, f.defaultInformer) +} + +func (f *deviceTaintRuleInformer) Lister() resourcev1alpha3.DeviceTaintRuleLister { + return resourcev1alpha3.NewDeviceTaintRuleLister(f.Informer().GetIndexer()) +} diff --git a/informers/resource/v1alpha3/interface.go b/informers/resource/v1alpha3/interface.go index 356c46179d..11c7f849af 100644 --- a/informers/resource/v1alpha3/interface.go +++ b/informers/resource/v1alpha3/interface.go @@ -26,6 +26,8 @@ import ( type Interface interface { // DeviceClasses returns a DeviceClassInformer. DeviceClasses() DeviceClassInformer + // DeviceTaintRules returns a DeviceTaintRuleInformer. + DeviceTaintRules() DeviceTaintRuleInformer // ResourceClaims returns a ResourceClaimInformer. ResourceClaims() ResourceClaimInformer // ResourceClaimTemplates returns a ResourceClaimTemplateInformer. @@ -50,6 +52,11 @@ func (v *version) DeviceClasses() DeviceClassInformer { return &deviceClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } +// DeviceTaintRules returns a DeviceTaintRuleInformer. +func (v *version) DeviceTaintRules() DeviceTaintRuleInformer { + return &deviceTaintRuleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} + // ResourceClaims returns a ResourceClaimInformer. func (v *version) ResourceClaims() ResourceClaimInformer { return &resourceClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/informers/resource/v1alpha3/resourceclaim.go b/informers/resource/v1alpha3/resourceclaim.go index 822d145bcb..2ee78d35d6 100644 --- a/informers/resource/v1alpha3/resourceclaim.go +++ b/informers/resource/v1alpha3/resourceclaim.go @@ -62,13 +62,25 @@ func NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace str if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().ResourceClaims(namespace).List(context.TODO(), options) + return client.ResourceV1alpha3().ResourceClaims(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().ResourceClaims(namespace).Watch(context.TODO(), options) + return client.ResourceV1alpha3().ResourceClaims(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().ResourceClaims(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().ResourceClaims(namespace).Watch(ctx, options) }, }, &apiresourcev1alpha3.ResourceClaim{}, diff --git a/informers/resource/v1alpha3/resourceclaimtemplate.go b/informers/resource/v1alpha3/resourceclaimtemplate.go index 94680730af..bd1e7abefc 100644 --- a/informers/resource/v1alpha3/resourceclaimtemplate.go +++ b/informers/resource/v1alpha3/resourceclaimtemplate.go @@ -62,13 +62,25 @@ func NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, names if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().ResourceClaimTemplates(namespace).List(context.TODO(), options) + return client.ResourceV1alpha3().ResourceClaimTemplates(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().ResourceClaimTemplates(namespace).Watch(context.TODO(), options) + return client.ResourceV1alpha3().ResourceClaimTemplates(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().ResourceClaimTemplates(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().ResourceClaimTemplates(namespace).Watch(ctx, options) }, }, &apiresourcev1alpha3.ResourceClaimTemplate{}, diff --git a/informers/resource/v1alpha3/resourceslice.go b/informers/resource/v1alpha3/resourceslice.go index 15394575f5..9b6422e96e 100644 --- a/informers/resource/v1alpha3/resourceslice.go +++ b/informers/resource/v1alpha3/resourceslice.go @@ -61,13 +61,25 @@ func NewFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().ResourceSlices().List(context.TODO(), options) + return client.ResourceV1alpha3().ResourceSlices().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1alpha3().ResourceSlices().Watch(context.TODO(), options) + return client.ResourceV1alpha3().ResourceSlices().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().ResourceSlices().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1alpha3().ResourceSlices().Watch(ctx, options) }, }, &apiresourcev1alpha3.ResourceSlice{}, diff --git a/informers/resource/v1beta1/deviceclass.go b/informers/resource/v1beta1/deviceclass.go index 9623788c48..bb0b28245b 100644 --- a/informers/resource/v1beta1/deviceclass.go +++ b/informers/resource/v1beta1/deviceclass.go @@ -61,13 +61,25 @@ func NewFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod ti if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().DeviceClasses().List(context.TODO(), options) + return client.ResourceV1beta1().DeviceClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().DeviceClasses().Watch(context.TODO(), options) + return client.ResourceV1beta1().DeviceClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().DeviceClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().DeviceClasses().Watch(ctx, options) }, }, &apiresourcev1beta1.DeviceClass{}, diff --git a/informers/resource/v1beta1/resourceclaim.go b/informers/resource/v1beta1/resourceclaim.go index 107b7fda7d..5e13b79732 100644 --- a/informers/resource/v1beta1/resourceclaim.go +++ b/informers/resource/v1beta1/resourceclaim.go @@ -62,13 +62,25 @@ func NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace str if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().ResourceClaims(namespace).List(context.TODO(), options) + return client.ResourceV1beta1().ResourceClaims(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().ResourceClaims(namespace).Watch(context.TODO(), options) + return client.ResourceV1beta1().ResourceClaims(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().ResourceClaims(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().ResourceClaims(namespace).Watch(ctx, options) }, }, &apiresourcev1beta1.ResourceClaim{}, diff --git a/informers/resource/v1beta1/resourceclaimtemplate.go b/informers/resource/v1beta1/resourceclaimtemplate.go index 9ae634ad0b..86c13a8f21 100644 --- a/informers/resource/v1beta1/resourceclaimtemplate.go +++ b/informers/resource/v1beta1/resourceclaimtemplate.go @@ -62,13 +62,25 @@ func NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, names if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().ResourceClaimTemplates(namespace).List(context.TODO(), options) + return client.ResourceV1beta1().ResourceClaimTemplates(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().ResourceClaimTemplates(namespace).Watch(context.TODO(), options) + return client.ResourceV1beta1().ResourceClaimTemplates(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().ResourceClaimTemplates(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().ResourceClaimTemplates(namespace).Watch(ctx, options) }, }, &apiresourcev1beta1.ResourceClaimTemplate{}, diff --git a/informers/resource/v1beta1/resourceslice.go b/informers/resource/v1beta1/resourceslice.go index 8ab6cb4fcb..6cc3c65fdf 100644 --- a/informers/resource/v1beta1/resourceslice.go +++ b/informers/resource/v1beta1/resourceslice.go @@ -61,13 +61,25 @@ func NewFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().ResourceSlices().List(context.TODO(), options) + return client.ResourceV1beta1().ResourceSlices().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.ResourceV1beta1().ResourceSlices().Watch(context.TODO(), options) + return client.ResourceV1beta1().ResourceSlices().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().ResourceSlices().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta1().ResourceSlices().Watch(ctx, options) }, }, &apiresourcev1beta1.ResourceSlice{}, diff --git a/informers/resource/v1beta2/deviceclass.go b/informers/resource/v1beta2/deviceclass.go new file mode 100644 index 0000000000..372d35d8aa --- /dev/null +++ b/informers/resource/v1beta2/deviceclass.go @@ -0,0 +1,101 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + time "time" + + apiresourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + resourcev1beta2 "k8s.io/client-go/listers/resource/v1beta2" + cache "k8s.io/client-go/tools/cache" +) + +// DeviceClassInformer provides access to a shared informer and lister for +// DeviceClasses. +type DeviceClassInformer interface { + Informer() cache.SharedIndexInformer + Lister() resourcev1beta2.DeviceClassLister +} + +type deviceClassInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredDeviceClassInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().DeviceClasses().List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().DeviceClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().DeviceClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().DeviceClasses().Watch(ctx, options) + }, + }, + &apiresourcev1beta2.DeviceClass{}, + resyncPeriod, + indexers, + ) +} + +func (f *deviceClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredDeviceClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *deviceClassInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apiresourcev1beta2.DeviceClass{}, f.defaultInformer) +} + +func (f *deviceClassInformer) Lister() resourcev1beta2.DeviceClassLister { + return resourcev1beta2.NewDeviceClassLister(f.Informer().GetIndexer()) +} diff --git a/informers/resource/v1beta2/interface.go b/informers/resource/v1beta2/interface.go new file mode 100644 index 0000000000..4627d6f3e2 --- /dev/null +++ b/informers/resource/v1beta2/interface.go @@ -0,0 +1,66 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta2 + +import ( + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // DeviceClasses returns a DeviceClassInformer. + DeviceClasses() DeviceClassInformer + // ResourceClaims returns a ResourceClaimInformer. + ResourceClaims() ResourceClaimInformer + // ResourceClaimTemplates returns a ResourceClaimTemplateInformer. + ResourceClaimTemplates() ResourceClaimTemplateInformer + // ResourceSlices returns a ResourceSliceInformer. + ResourceSlices() ResourceSliceInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// DeviceClasses returns a DeviceClassInformer. +func (v *version) DeviceClasses() DeviceClassInformer { + return &deviceClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} + +// ResourceClaims returns a ResourceClaimInformer. +func (v *version) ResourceClaims() ResourceClaimInformer { + return &resourceClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// ResourceClaimTemplates returns a ResourceClaimTemplateInformer. +func (v *version) ResourceClaimTemplates() ResourceClaimTemplateInformer { + return &resourceClaimTemplateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// ResourceSlices returns a ResourceSliceInformer. +func (v *version) ResourceSlices() ResourceSliceInformer { + return &resourceSliceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} diff --git a/informers/resource/v1beta2/resourceclaim.go b/informers/resource/v1beta2/resourceclaim.go new file mode 100644 index 0000000000..e245d998c1 --- /dev/null +++ b/informers/resource/v1beta2/resourceclaim.go @@ -0,0 +1,102 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + time "time" + + apiresourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + resourcev1beta2 "k8s.io/client-go/listers/resource/v1beta2" + cache "k8s.io/client-go/tools/cache" +) + +// ResourceClaimInformer provides access to a shared informer and lister for +// ResourceClaims. +type ResourceClaimInformer interface { + Informer() cache.SharedIndexInformer + Lister() resourcev1beta2.ResourceClaimLister +} + +type resourceClaimInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredResourceClaimInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaims(namespace).List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaims(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaims(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaims(namespace).Watch(ctx, options) + }, + }, + &apiresourcev1beta2.ResourceClaim{}, + resyncPeriod, + indexers, + ) +} + +func (f *resourceClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredResourceClaimInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *resourceClaimInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apiresourcev1beta2.ResourceClaim{}, f.defaultInformer) +} + +func (f *resourceClaimInformer) Lister() resourcev1beta2.ResourceClaimLister { + return resourcev1beta2.NewResourceClaimLister(f.Informer().GetIndexer()) +} diff --git a/informers/resource/v1beta2/resourceclaimtemplate.go b/informers/resource/v1beta2/resourceclaimtemplate.go new file mode 100644 index 0000000000..4b973bd969 --- /dev/null +++ b/informers/resource/v1beta2/resourceclaimtemplate.go @@ -0,0 +1,102 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + time "time" + + apiresourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + resourcev1beta2 "k8s.io/client-go/listers/resource/v1beta2" + cache "k8s.io/client-go/tools/cache" +) + +// ResourceClaimTemplateInformer provides access to a shared informer and lister for +// ResourceClaimTemplates. +type ResourceClaimTemplateInformer interface { + Informer() cache.SharedIndexInformer + Lister() resourcev1beta2.ResourceClaimTemplateLister +} + +type resourceClaimTemplateInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredResourceClaimTemplateInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaimTemplates(namespace).List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaimTemplates(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaimTemplates(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceClaimTemplates(namespace).Watch(ctx, options) + }, + }, + &apiresourcev1beta2.ResourceClaimTemplate{}, + resyncPeriod, + indexers, + ) +} + +func (f *resourceClaimTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredResourceClaimTemplateInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *resourceClaimTemplateInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apiresourcev1beta2.ResourceClaimTemplate{}, f.defaultInformer) +} + +func (f *resourceClaimTemplateInformer) Lister() resourcev1beta2.ResourceClaimTemplateLister { + return resourcev1beta2.NewResourceClaimTemplateLister(f.Informer().GetIndexer()) +} diff --git a/informers/resource/v1beta2/resourceslice.go b/informers/resource/v1beta2/resourceslice.go new file mode 100644 index 0000000000..c0cdc67a83 --- /dev/null +++ b/informers/resource/v1beta2/resourceslice.go @@ -0,0 +1,101 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + time "time" + + apiresourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + resourcev1beta2 "k8s.io/client-go/listers/resource/v1beta2" + cache "k8s.io/client-go/tools/cache" +) + +// ResourceSliceInformer provides access to a shared informer and lister for +// ResourceSlices. +type ResourceSliceInformer interface { + Informer() cache.SharedIndexInformer + Lister() resourcev1beta2.ResourceSliceLister +} + +type resourceSliceInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredResourceSliceInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceSlices().List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceSlices().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceSlices().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ResourceV1beta2().ResourceSlices().Watch(ctx, options) + }, + }, + &apiresourcev1beta2.ResourceSlice{}, + resyncPeriod, + indexers, + ) +} + +func (f *resourceSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredResourceSliceInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *resourceSliceInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apiresourcev1beta2.ResourceSlice{}, f.defaultInformer) +} + +func (f *resourceSliceInformer) Lister() resourcev1beta2.ResourceSliceLister { + return resourcev1beta2.NewResourceSliceLister(f.Informer().GetIndexer()) +} diff --git a/informers/scheduling/v1/priorityclass.go b/informers/scheduling/v1/priorityclass.go index 20b9fc0dc4..df42636632 100644 --- a/informers/scheduling/v1/priorityclass.go +++ b/informers/scheduling/v1/priorityclass.go @@ -61,13 +61,25 @@ func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod if tweakListOptions != nil { tweakListOptions(&options) } - return client.SchedulingV1().PriorityClasses().List(context.TODO(), options) + return client.SchedulingV1().PriorityClasses().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.SchedulingV1().PriorityClasses().Watch(context.TODO(), options) + return client.SchedulingV1().PriorityClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SchedulingV1().PriorityClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SchedulingV1().PriorityClasses().Watch(ctx, options) }, }, &apischedulingv1.PriorityClass{}, diff --git a/informers/scheduling/v1alpha1/priorityclass.go b/informers/scheduling/v1alpha1/priorityclass.go index 904bc6c4ee..228240af12 100644 --- a/informers/scheduling/v1alpha1/priorityclass.go +++ b/informers/scheduling/v1alpha1/priorityclass.go @@ -61,13 +61,25 @@ func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod if tweakListOptions != nil { tweakListOptions(&options) } - return client.SchedulingV1alpha1().PriorityClasses().List(context.TODO(), options) + return client.SchedulingV1alpha1().PriorityClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.SchedulingV1alpha1().PriorityClasses().Watch(context.TODO(), options) + return client.SchedulingV1alpha1().PriorityClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SchedulingV1alpha1().PriorityClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SchedulingV1alpha1().PriorityClasses().Watch(ctx, options) }, }, &apischedulingv1alpha1.PriorityClass{}, diff --git a/informers/scheduling/v1beta1/priorityclass.go b/informers/scheduling/v1beta1/priorityclass.go index 299d376737..fd40bd0860 100644 --- a/informers/scheduling/v1beta1/priorityclass.go +++ b/informers/scheduling/v1beta1/priorityclass.go @@ -61,13 +61,25 @@ func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod if tweakListOptions != nil { tweakListOptions(&options) } - return client.SchedulingV1beta1().PriorityClasses().List(context.TODO(), options) + return client.SchedulingV1beta1().PriorityClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.SchedulingV1beta1().PriorityClasses().Watch(context.TODO(), options) + return client.SchedulingV1beta1().PriorityClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SchedulingV1beta1().PriorityClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SchedulingV1beta1().PriorityClasses().Watch(ctx, options) }, }, &apischedulingv1beta1.PriorityClass{}, diff --git a/informers/storage/v1/csidriver.go b/informers/storage/v1/csidriver.go index 79282873bb..b79a51ca00 100644 --- a/informers/storage/v1/csidriver.go +++ b/informers/storage/v1/csidriver.go @@ -61,13 +61,25 @@ func NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().CSIDrivers().List(context.TODO(), options) + return client.StorageV1().CSIDrivers().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().CSIDrivers().Watch(context.TODO(), options) + return client.StorageV1().CSIDrivers().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().CSIDrivers().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().CSIDrivers().Watch(ctx, options) }, }, &apistoragev1.CSIDriver{}, diff --git a/informers/storage/v1/csinode.go b/informers/storage/v1/csinode.go index 00345f897a..7a6040795e 100644 --- a/informers/storage/v1/csinode.go +++ b/informers/storage/v1/csinode.go @@ -61,13 +61,25 @@ func NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.D if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().CSINodes().List(context.TODO(), options) + return client.StorageV1().CSINodes().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().CSINodes().Watch(context.TODO(), options) + return client.StorageV1().CSINodes().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().CSINodes().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().CSINodes().Watch(ctx, options) }, }, &apistoragev1.CSINode{}, diff --git a/informers/storage/v1/csistoragecapacity.go b/informers/storage/v1/csistoragecapacity.go index 5a72272fcb..84ef70f2e7 100644 --- a/informers/storage/v1/csistoragecapacity.go +++ b/informers/storage/v1/csistoragecapacity.go @@ -62,13 +62,25 @@ func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespac if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().CSIStorageCapacities(namespace).List(context.TODO(), options) + return client.StorageV1().CSIStorageCapacities(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().CSIStorageCapacities(namespace).Watch(context.TODO(), options) + return client.StorageV1().CSIStorageCapacities(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().CSIStorageCapacities(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().CSIStorageCapacities(namespace).Watch(ctx, options) }, }, &apistoragev1.CSIStorageCapacity{}, diff --git a/informers/storage/v1/storageclass.go b/informers/storage/v1/storageclass.go index 6eecc50f74..7f17ecf8c7 100644 --- a/informers/storage/v1/storageclass.go +++ b/informers/storage/v1/storageclass.go @@ -61,13 +61,25 @@ func NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod t if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().StorageClasses().List(context.TODO(), options) + return client.StorageV1().StorageClasses().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().StorageClasses().Watch(context.TODO(), options) + return client.StorageV1().StorageClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().StorageClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().StorageClasses().Watch(ctx, options) }, }, &apistoragev1.StorageClass{}, diff --git a/informers/storage/v1/volumeattachment.go b/informers/storage/v1/volumeattachment.go index deca09cdac..3dee340d52 100644 --- a/informers/storage/v1/volumeattachment.go +++ b/informers/storage/v1/volumeattachment.go @@ -61,13 +61,25 @@ func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeri if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().VolumeAttachments().List(context.TODO(), options) + return client.StorageV1().VolumeAttachments().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1().VolumeAttachments().Watch(context.TODO(), options) + return client.StorageV1().VolumeAttachments().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().VolumeAttachments().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1().VolumeAttachments().Watch(ctx, options) }, }, &apistoragev1.VolumeAttachment{}, diff --git a/informers/storage/v1alpha1/csistoragecapacity.go b/informers/storage/v1alpha1/csistoragecapacity.go index 2253f700e6..794de10db1 100644 --- a/informers/storage/v1alpha1/csistoragecapacity.go +++ b/informers/storage/v1alpha1/csistoragecapacity.go @@ -62,13 +62,25 @@ func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespac if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1alpha1().CSIStorageCapacities(namespace).List(context.TODO(), options) + return client.StorageV1alpha1().CSIStorageCapacities(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1alpha1().CSIStorageCapacities(namespace).Watch(context.TODO(), options) + return client.StorageV1alpha1().CSIStorageCapacities(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1alpha1().CSIStorageCapacities(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1alpha1().CSIStorageCapacities(namespace).Watch(ctx, options) }, }, &apistoragev1alpha1.CSIStorageCapacity{}, diff --git a/informers/storage/v1alpha1/volumeattachment.go b/informers/storage/v1alpha1/volumeattachment.go index f319899530..dc68be2344 100644 --- a/informers/storage/v1alpha1/volumeattachment.go +++ b/informers/storage/v1alpha1/volumeattachment.go @@ -61,13 +61,25 @@ func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeri if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1alpha1().VolumeAttachments().List(context.TODO(), options) + return client.StorageV1alpha1().VolumeAttachments().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1alpha1().VolumeAttachments().Watch(context.TODO(), options) + return client.StorageV1alpha1().VolumeAttachments().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1alpha1().VolumeAttachments().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1alpha1().VolumeAttachments().Watch(ctx, options) }, }, &apistoragev1alpha1.VolumeAttachment{}, diff --git a/informers/storage/v1alpha1/volumeattributesclass.go b/informers/storage/v1alpha1/volumeattributesclass.go index 8a688312a9..5210ea79a9 100644 --- a/informers/storage/v1alpha1/volumeattributesclass.go +++ b/informers/storage/v1alpha1/volumeattributesclass.go @@ -61,13 +61,25 @@ func NewFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyn if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1alpha1().VolumeAttributesClasses().List(context.TODO(), options) + return client.StorageV1alpha1().VolumeAttributesClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1alpha1().VolumeAttributesClasses().Watch(context.TODO(), options) + return client.StorageV1alpha1().VolumeAttributesClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1alpha1().VolumeAttributesClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1alpha1().VolumeAttributesClasses().Watch(ctx, options) }, }, &apistoragev1alpha1.VolumeAttributesClass{}, diff --git a/informers/storage/v1beta1/csidriver.go b/informers/storage/v1beta1/csidriver.go index f538deed51..a21dc94ff8 100644 --- a/informers/storage/v1beta1/csidriver.go +++ b/informers/storage/v1beta1/csidriver.go @@ -61,13 +61,25 @@ func NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().CSIDrivers().List(context.TODO(), options) + return client.StorageV1beta1().CSIDrivers().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().CSIDrivers().Watch(context.TODO(), options) + return client.StorageV1beta1().CSIDrivers().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().CSIDrivers().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().CSIDrivers().Watch(ctx, options) }, }, &apistoragev1beta1.CSIDriver{}, diff --git a/informers/storage/v1beta1/csinode.go b/informers/storage/v1beta1/csinode.go index 5d26cffdcf..e789fe3096 100644 --- a/informers/storage/v1beta1/csinode.go +++ b/informers/storage/v1beta1/csinode.go @@ -61,13 +61,25 @@ func NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.D if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().CSINodes().List(context.TODO(), options) + return client.StorageV1beta1().CSINodes().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().CSINodes().Watch(context.TODO(), options) + return client.StorageV1beta1().CSINodes().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().CSINodes().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().CSINodes().Watch(ctx, options) }, }, &apistoragev1beta1.CSINode{}, diff --git a/informers/storage/v1beta1/csistoragecapacity.go b/informers/storage/v1beta1/csistoragecapacity.go index 9ad42e9f83..fa75b0b4f9 100644 --- a/informers/storage/v1beta1/csistoragecapacity.go +++ b/informers/storage/v1beta1/csistoragecapacity.go @@ -62,13 +62,25 @@ func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespac if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().CSIStorageCapacities(namespace).List(context.TODO(), options) + return client.StorageV1beta1().CSIStorageCapacities(namespace).List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().CSIStorageCapacities(namespace).Watch(context.TODO(), options) + return client.StorageV1beta1().CSIStorageCapacities(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().CSIStorageCapacities(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().CSIStorageCapacities(namespace).Watch(ctx, options) }, }, &apistoragev1beta1.CSIStorageCapacity{}, diff --git a/informers/storage/v1beta1/storageclass.go b/informers/storage/v1beta1/storageclass.go index 2d8649e9b8..23d7ca4fc7 100644 --- a/informers/storage/v1beta1/storageclass.go +++ b/informers/storage/v1beta1/storageclass.go @@ -61,13 +61,25 @@ func NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod t if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().StorageClasses().List(context.TODO(), options) + return client.StorageV1beta1().StorageClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().StorageClasses().Watch(context.TODO(), options) + return client.StorageV1beta1().StorageClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().StorageClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().StorageClasses().Watch(ctx, options) }, }, &apistoragev1beta1.StorageClass{}, diff --git a/informers/storage/v1beta1/volumeattachment.go b/informers/storage/v1beta1/volumeattachment.go index 93d3826936..691b2c6d12 100644 --- a/informers/storage/v1beta1/volumeattachment.go +++ b/informers/storage/v1beta1/volumeattachment.go @@ -61,13 +61,25 @@ func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeri if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().VolumeAttachments().List(context.TODO(), options) + return client.StorageV1beta1().VolumeAttachments().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().VolumeAttachments().Watch(context.TODO(), options) + return client.StorageV1beta1().VolumeAttachments().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().VolumeAttachments().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().VolumeAttachments().Watch(ctx, options) }, }, &apistoragev1beta1.VolumeAttachment{}, diff --git a/informers/storage/v1beta1/volumeattributesclass.go b/informers/storage/v1beta1/volumeattributesclass.go index dd9734bdc6..7d66c58156 100644 --- a/informers/storage/v1beta1/volumeattributesclass.go +++ b/informers/storage/v1beta1/volumeattributesclass.go @@ -61,13 +61,25 @@ func NewFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyn if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().VolumeAttributesClasses().List(context.TODO(), options) + return client.StorageV1beta1().VolumeAttributesClasses().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StorageV1beta1().VolumeAttributesClasses().Watch(context.TODO(), options) + return client.StorageV1beta1().VolumeAttributesClasses().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().VolumeAttributesClasses().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StorageV1beta1().VolumeAttributesClasses().Watch(ctx, options) }, }, &apistoragev1beta1.VolumeAttributesClass{}, diff --git a/informers/storagemigration/v1alpha1/storageversionmigration.go b/informers/storagemigration/v1alpha1/storageversionmigration.go index 49d6dd2e5b..4debb5eef9 100644 --- a/informers/storagemigration/v1alpha1/storageversionmigration.go +++ b/informers/storagemigration/v1alpha1/storageversionmigration.go @@ -61,13 +61,25 @@ func NewFilteredStorageVersionMigrationInformer(client kubernetes.Interface, res if tweakListOptions != nil { tweakListOptions(&options) } - return client.StoragemigrationV1alpha1().StorageVersionMigrations().List(context.TODO(), options) + return client.StoragemigrationV1alpha1().StorageVersionMigrations().List(context.Background(), options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.StoragemigrationV1alpha1().StorageVersionMigrations().Watch(context.TODO(), options) + return client.StoragemigrationV1alpha1().StorageVersionMigrations().Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StoragemigrationV1alpha1().StorageVersionMigrations().List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.StoragemigrationV1alpha1().StorageVersionMigrations().Watch(ctx, options) }, }, &apistoragemigrationv1alpha1.StorageVersionMigration{}, diff --git a/kubernetes/clientset.go b/kubernetes/clientset.go index a6dbc23a9c..b333d6b8a1 100644 --- a/kubernetes/clientset.go +++ b/kubernetes/clientset.go @@ -70,6 +70,7 @@ import ( rbacv1beta1 "k8s.io/client-go/kubernetes/typed/rbac/v1beta1" resourcev1alpha3 "k8s.io/client-go/kubernetes/typed/resource/v1alpha3" resourcev1beta1 "k8s.io/client-go/kubernetes/typed/resource/v1beta1" + resourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" schedulingv1 "k8s.io/client-go/kubernetes/typed/scheduling/v1" schedulingv1alpha1 "k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1" schedulingv1beta1 "k8s.io/client-go/kubernetes/typed/scheduling/v1beta1" @@ -128,6 +129,7 @@ type Interface interface { RbacV1() rbacv1.RbacV1Interface RbacV1beta1() rbacv1beta1.RbacV1beta1Interface RbacV1alpha1() rbacv1alpha1.RbacV1alpha1Interface + ResourceV1beta2() resourcev1beta2.ResourceV1beta2Interface ResourceV1beta1() resourcev1beta1.ResourceV1beta1Interface ResourceV1alpha3() resourcev1alpha3.ResourceV1alpha3Interface SchedulingV1alpha1() schedulingv1alpha1.SchedulingV1alpha1Interface @@ -187,6 +189,7 @@ type Clientset struct { rbacV1 *rbacv1.RbacV1Client rbacV1beta1 *rbacv1beta1.RbacV1beta1Client rbacV1alpha1 *rbacv1alpha1.RbacV1alpha1Client + resourceV1beta2 *resourcev1beta2.ResourceV1beta2Client resourceV1beta1 *resourcev1beta1.ResourceV1beta1Client resourceV1alpha3 *resourcev1alpha3.ResourceV1alpha3Client schedulingV1alpha1 *schedulingv1alpha1.SchedulingV1alpha1Client @@ -423,6 +426,11 @@ func (c *Clientset) RbacV1alpha1() rbacv1alpha1.RbacV1alpha1Interface { return c.rbacV1alpha1 } +// ResourceV1beta2 retrieves the ResourceV1beta2Client +func (c *Clientset) ResourceV1beta2() resourcev1beta2.ResourceV1beta2Interface { + return c.resourceV1beta2 +} + // ResourceV1beta1 retrieves the ResourceV1beta1Client func (c *Clientset) ResourceV1beta1() resourcev1beta1.ResourceV1beta1Interface { return c.resourceV1beta1 @@ -692,6 +700,10 @@ func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, if err != nil { return nil, err } + cs.resourceV1beta2, err = resourcev1beta2.NewForConfigAndClient(&configShallowCopy, httpClient) + if err != nil { + return nil, err + } cs.resourceV1beta1, err = resourcev1beta1.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err @@ -794,6 +806,7 @@ func New(c rest.Interface) *Clientset { cs.rbacV1 = rbacv1.New(c) cs.rbacV1beta1 = rbacv1beta1.New(c) cs.rbacV1alpha1 = rbacv1alpha1.New(c) + cs.resourceV1beta2 = resourcev1beta2.New(c) cs.resourceV1beta1 = resourcev1beta1.New(c) cs.resourceV1alpha3 = resourcev1alpha3.New(c) cs.schedulingV1alpha1 = schedulingv1alpha1.New(c) diff --git a/kubernetes/doc.go b/kubernetes/doc.go index e052f81b85..9cef4242f2 100644 --- a/kubernetes/doc.go +++ b/kubernetes/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package kubernetes holds packages which implement a clientset for Kubernetes // APIs. -package kubernetes // import "k8s.io/client-go/kubernetes" +package kubernetes diff --git a/kubernetes/fake/clientset_generated.go b/kubernetes/fake/clientset_generated.go index 6b583818b6..a454c6f191 100644 --- a/kubernetes/fake/clientset_generated.go +++ b/kubernetes/fake/clientset_generated.go @@ -19,6 +19,7 @@ limitations under the License. package fake import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" applyconfigurations "k8s.io/client-go/applyconfigurations" @@ -119,6 +120,8 @@ import ( fakeresourcev1alpha3 "k8s.io/client-go/kubernetes/typed/resource/v1alpha3/fake" resourcev1beta1 "k8s.io/client-go/kubernetes/typed/resource/v1beta1" fakeresourcev1beta1 "k8s.io/client-go/kubernetes/typed/resource/v1beta1/fake" + resourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" + fakeresourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2/fake" schedulingv1 "k8s.io/client-go/kubernetes/typed/scheduling/v1" fakeschedulingv1 "k8s.io/client-go/kubernetes/typed/scheduling/v1/fake" schedulingv1alpha1 "k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1" @@ -156,9 +159,13 @@ func NewSimpleClientset(objects ...runtime.Object) *Clientset { cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} cs.AddReactor("*", "*", testing.ObjectReaction(o)) cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { + var opts metav1.ListOptions + if watchActcion, ok := action.(testing.WatchActionImpl); ok { + opts = watchActcion.ListOptions + } gvr := action.GetResource() ns := action.GetNamespace() - watch, err := o.Watch(gvr, ns) + watch, err := o.Watch(gvr, ns, opts) if err != nil { return false, nil, err } @@ -205,9 +212,13 @@ func NewClientset(objects ...runtime.Object) *Clientset { cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} cs.AddReactor("*", "*", testing.ObjectReaction(o)) cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { + var opts metav1.ListOptions + if watchActcion, ok := action.(testing.WatchActionImpl); ok { + opts = watchActcion.ListOptions + } gvr := action.GetResource() ns := action.GetNamespace() - watch, err := o.Watch(gvr, ns) + watch, err := o.Watch(gvr, ns, opts) if err != nil { return false, nil, err } @@ -447,6 +458,11 @@ func (c *Clientset) RbacV1alpha1() rbacv1alpha1.RbacV1alpha1Interface { return &fakerbacv1alpha1.FakeRbacV1alpha1{Fake: &c.Fake} } +// ResourceV1beta2 retrieves the ResourceV1beta2Client +func (c *Clientset) ResourceV1beta2() resourcev1beta2.ResourceV1beta2Interface { + return &fakeresourcev1beta2.FakeResourceV1beta2{Fake: &c.Fake} +} + // ResourceV1beta1 retrieves the ResourceV1beta1Client func (c *Clientset) ResourceV1beta1() resourcev1beta1.ResourceV1beta1Interface { return &fakeresourcev1beta1.FakeResourceV1beta1{Fake: &c.Fake} diff --git a/kubernetes/fake/clientset_generated_test.go b/kubernetes/fake/clientset_generated_test.go index 54c1b265e6..4187cf0ae9 100644 --- a/kubernetes/fake/clientset_generated_test.go +++ b/kubernetes/fake/clientset_generated_test.go @@ -18,9 +18,11 @@ package fake import ( "context" - "github.com/stretchr/testify/assert" "testing" + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/require" + v1 "k8s.io/api/core/v1" policy "k8s.io/api/policy/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -29,35 +31,36 @@ import ( func TestNewSimpleClientset(t *testing.T) { client := NewSimpleClientset() - client.CoreV1().Pods("default").Create(context.Background(), &v1.Pod{ + expectedPods := []*v1.Pod{} + + pod, err := client.CoreV1().Pods("default").Create(context.Background(), &v1.Pod{ ObjectMeta: meta_v1.ObjectMeta{ Name: "pod-1", Namespace: "default", }, }, meta_v1.CreateOptions{}) - client.CoreV1().Pods("default").Create(context.Background(), &v1.Pod{ + require.NoError(t, err) + expectedPods = append(expectedPods, pod) + + pod, err = client.CoreV1().Pods("default").Create(context.Background(), &v1.Pod{ ObjectMeta: meta_v1.ObjectMeta{ Name: "pod-2", Namespace: "default", }, }, meta_v1.CreateOptions{}) - err := client.CoreV1().Pods("default").EvictV1(context.Background(), &policy.Eviction{ + require.NoError(t, err) + expectedPods = append(expectedPods, pod) + + err = client.CoreV1().Pods("default").EvictV1(context.Background(), &policy.Eviction{ ObjectMeta: meta_v1.ObjectMeta{ Name: "pod-2", }, }) - - if err != nil { - t.Errorf("TestNewSimpleClientset() res = %v", err.Error()) - } + require.NoError(t, err) pods, err := client.CoreV1().Pods("default").List(context.Background(), meta_v1.ListOptions{}) - // err: item[0]: can't assign or convert v1beta1.Eviction into v1.Pod - if err != nil { - t.Errorf("TestNewSimpleClientset() res = %v", err.Error()) - } else { - t.Logf("TestNewSimpleClientset() res = %v", pods) - } + require.NoError(t, err) + cmp.Equal(expectedPods, pods.Items) } func TestManagedFieldClientset(t *testing.T) { @@ -69,58 +72,47 @@ func TestManagedFieldClientset(t *testing.T) { ObjectMeta: meta_v1.ObjectMeta{Name: name, Namespace: namespace}, Data: map[string]string{"k0": "v0"}, }, meta_v1.CreateOptions{FieldManager: "test-manager-0"}) - if err != nil { - t.Errorf("Failed to create pod: %v", err) - } - assert.Equal(t, map[string]string{"k0": "v0"}, cm.Data) + require.NoError(t, err) + require.Equal(t, map[string]string{"k0": "v0"}, cm.Data) // Apply with test-manager-1 // Expect data to be shared with initial create cm, err = client.CoreV1().ConfigMaps("default").Apply(context.Background(), v1ac.ConfigMap(name, namespace).WithData(map[string]string{"k1": "v1"}), meta_v1.ApplyOptions{FieldManager: "test-manager-1"}) - if err != nil { - t.Errorf("Failed to create pod: %v", err) - } - assert.Equal(t, map[string]string{"k0": "v0", "k1": "v1"}, cm.Data) + require.NoError(t, err) + require.Equal(t, map[string]string{"k0": "v0", "k1": "v1"}, cm.Data) // Apply conflicting with test-manager-2, expect apply to fail _, err = client.CoreV1().ConfigMaps("default").Apply(context.Background(), v1ac.ConfigMap(name, namespace).WithData(map[string]string{"k1": "xyz"}), meta_v1.ApplyOptions{FieldManager: "test-manager-2"}) - if assert.Error(t, err) { - assert.Equal(t, "Apply failed with 1 conflict: conflict with \"test-manager-1\": .data.k1", err.Error()) - } + require.Error(t, err) + require.Equal(t, "Apply failed with 1 conflict: conflict with \"test-manager-1\": .data.k1", err.Error()) // Apply with test-manager-2 // Expect data to be shared with initial create and test-manager-1 cm, err = client.CoreV1().ConfigMaps("default").Apply(context.Background(), v1ac.ConfigMap(name, namespace).WithData(map[string]string{"k2": "v2"}), meta_v1.ApplyOptions{FieldManager: "test-manager-2"}) - if err != nil { - t.Errorf("Failed to create pod: %v", err) - } - assert.Equal(t, map[string]string{"k0": "v0", "k1": "v1", "k2": "v2"}, cm.Data) + require.NoError(t, err) + require.Equal(t, map[string]string{"k0": "v0", "k1": "v1", "k2": "v2"}, cm.Data) // Apply with test-manager-1 // Expect owned data to be updated cm, err = client.CoreV1().ConfigMaps("default").Apply(context.Background(), v1ac.ConfigMap(name, namespace).WithData(map[string]string{"k1": "v101"}), meta_v1.ApplyOptions{FieldManager: "test-manager-1"}) - if err != nil { - t.Errorf("Failed to create pod: %v", err) - } - assert.Equal(t, map[string]string{"k0": "v0", "k1": "v101", "k2": "v2"}, cm.Data) + require.NoError(t, err) + require.Equal(t, map[string]string{"k0": "v0", "k1": "v101", "k2": "v2"}, cm.Data) // Force apply with test-manager-2 // Expect data owned by test-manager-1 to be updated, expect data already owned but not in apply configuration to be removed cm, err = client.CoreV1().ConfigMaps("default").Apply(context.Background(), v1ac.ConfigMap(name, namespace).WithData(map[string]string{"k1": "v202"}), meta_v1.ApplyOptions{FieldManager: "test-manager-2", Force: true}) - if err != nil { - t.Errorf("Failed to create pod: %v", err) - } - assert.Equal(t, map[string]string{"k0": "v0", "k1": "v202"}, cm.Data) + require.NoError(t, err) + require.Equal(t, map[string]string{"k0": "v0", "k1": "v202"}, cm.Data) // Update with test-manager-1 to perform a force update of the entire resource cm, err = client.CoreV1().ConfigMaps("default").Update(context.Background(), @@ -137,8 +129,6 @@ func TestManagedFieldClientset(t *testing.T) { "k99": "v99", }, }, meta_v1.UpdateOptions{FieldManager: "test-manager-0"}) - if err != nil { - t.Errorf("Failed to update pod: %v", err) - } - assert.Equal(t, map[string]string{"k99": "v99"}, cm.Data) + require.NoError(t, err) + require.Equal(t, map[string]string{"k99": "v99"}, cm.Data) } diff --git a/kubernetes/fake/register.go b/kubernetes/fake/register.go index 849b1ac900..1332509c1d 100644 --- a/kubernetes/fake/register.go +++ b/kubernetes/fake/register.go @@ -66,6 +66,7 @@ import ( rbacv1beta1 "k8s.io/api/rbac/v1beta1" resourcev1alpha3 "k8s.io/api/resource/v1alpha3" resourcev1beta1 "k8s.io/api/resource/v1beta1" + resourcev1beta2 "k8s.io/api/resource/v1beta2" schedulingv1 "k8s.io/api/scheduling/v1" schedulingv1alpha1 "k8s.io/api/scheduling/v1alpha1" schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" @@ -129,6 +130,7 @@ var localSchemeBuilder = runtime.SchemeBuilder{ rbacv1.AddToScheme, rbacv1beta1.AddToScheme, rbacv1alpha1.AddToScheme, + resourcev1beta2.AddToScheme, resourcev1beta1.AddToScheme, resourcev1alpha3.AddToScheme, schedulingv1alpha1.AddToScheme, diff --git a/kubernetes/import.go b/kubernetes/import.go index c4f9a91bcf..93f3e4c6e8 100644 --- a/kubernetes/import.go +++ b/kubernetes/import.go @@ -16,4 +16,4 @@ limitations under the License. // This file exists to enforce this clientset's vanity import path. -package kubernetes // import "k8s.io/client-go/kubernetes" +package kubernetes diff --git a/kubernetes/scheme/register.go b/kubernetes/scheme/register.go index a9a5d8eb7d..e0dfc986f1 100644 --- a/kubernetes/scheme/register.go +++ b/kubernetes/scheme/register.go @@ -66,6 +66,7 @@ import ( rbacv1beta1 "k8s.io/api/rbac/v1beta1" resourcev1alpha3 "k8s.io/api/resource/v1alpha3" resourcev1beta1 "k8s.io/api/resource/v1beta1" + resourcev1beta2 "k8s.io/api/resource/v1beta2" schedulingv1 "k8s.io/api/scheduling/v1" schedulingv1alpha1 "k8s.io/api/scheduling/v1alpha1" schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" @@ -129,6 +130,7 @@ var localSchemeBuilder = runtime.SchemeBuilder{ rbacv1.AddToScheme, rbacv1beta1.AddToScheme, rbacv1alpha1.AddToScheme, + resourcev1beta2.AddToScheme, resourcev1beta1.AddToScheme, resourcev1alpha3.AddToScheme, schedulingv1alpha1.AddToScheme, diff --git a/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go b/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go index 74d2967f66..859ad913b9 100644 --- a/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go +++ b/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go @@ -60,9 +60,7 @@ func (c *AdmissionregistrationV1Client) ValidatingWebhookConfigurations() Valida // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AdmissionregistrationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*AdmissionregistrationV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *AdmissionregistrationV1Client { return &AdmissionregistrationV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := admissionregistrationv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go b/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go index f8a67c6d89..8ffb7da7fd 100644 --- a/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go +++ b/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go @@ -60,9 +60,7 @@ func (c *AdmissionregistrationV1alpha1Client) ValidatingAdmissionPolicyBindings( // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AdmissionregistrationV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*AdmissionregistrationV1alpha1Client, error) // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *AdmissionregistrationV1alpha1Client { return &AdmissionregistrationV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := admissionregistrationv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go b/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go index 16c42b0ec6..cfb825359b 100644 --- a/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go +++ b/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go @@ -60,9 +60,7 @@ func (c *AdmissionregistrationV1beta1Client) ValidatingWebhookConfigurations() V // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AdmissionregistrationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*AdmissionregistrationV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *AdmissionregistrationV1beta1Client { return &AdmissionregistrationV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := admissionregistrationv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go b/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go index b76fadf91b..2ea2568bfe 100644 --- a/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go +++ b/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go @@ -45,9 +45,7 @@ func (c *InternalV1alpha1Client) StorageVersions() StorageVersionInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*InternalV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*InternalV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*InternalV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *InternalV1alpha1Client { return &InternalV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := apiserverinternalv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/apps/v1/apps_client.go b/kubernetes/typed/apps/v1/apps_client.go index cb0bf87bad..7371f6265c 100644 --- a/kubernetes/typed/apps/v1/apps_client.go +++ b/kubernetes/typed/apps/v1/apps_client.go @@ -65,9 +65,7 @@ func (c *AppsV1Client) StatefulSets(namespace string) StatefulSetInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AppsV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -79,9 +77,7 @@ func NewForConfig(c *rest.Config) (*AppsV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -104,7 +100,7 @@ func New(c rest.Interface) *AppsV1Client { return &AppsV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := appsv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -113,8 +109,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/apps/v1beta1/apps_client.go b/kubernetes/typed/apps/v1beta1/apps_client.go index 72bde633bf..02e09bdda2 100644 --- a/kubernetes/typed/apps/v1beta1/apps_client.go +++ b/kubernetes/typed/apps/v1beta1/apps_client.go @@ -55,9 +55,7 @@ func (c *AppsV1beta1Client) StatefulSets(namespace string) StatefulSetInterface // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AppsV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -69,9 +67,7 @@ func NewForConfig(c *rest.Config) (*AppsV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -94,7 +90,7 @@ func New(c rest.Interface) *AppsV1beta1Client { return &AppsV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := appsv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -103,8 +99,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/apps/v1beta2/apps_client.go b/kubernetes/typed/apps/v1beta2/apps_client.go index e13d12a763..28309fa6a1 100644 --- a/kubernetes/typed/apps/v1beta2/apps_client.go +++ b/kubernetes/typed/apps/v1beta2/apps_client.go @@ -65,9 +65,7 @@ func (c *AppsV1beta2Client) StatefulSets(namespace string) StatefulSetInterface // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AppsV1beta2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -79,9 +77,7 @@ func NewForConfig(c *rest.Config) (*AppsV1beta2Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1beta2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -104,7 +100,7 @@ func New(c rest.Interface) *AppsV1beta2Client { return &AppsV1beta2Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := appsv1beta2.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -113,8 +109,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/authentication/v1/authentication_client.go b/kubernetes/typed/authentication/v1/authentication_client.go index bd5df77983..d030dae320 100644 --- a/kubernetes/typed/authentication/v1/authentication_client.go +++ b/kubernetes/typed/authentication/v1/authentication_client.go @@ -50,9 +50,7 @@ func (c *AuthenticationV1Client) TokenReviews() TokenReviewInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AuthenticationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*AuthenticationV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *AuthenticationV1Client { return &AuthenticationV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := authenticationv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/authentication/v1alpha1/authentication_client.go b/kubernetes/typed/authentication/v1alpha1/authentication_client.go index 8212658591..d317d7f9bc 100644 --- a/kubernetes/typed/authentication/v1alpha1/authentication_client.go +++ b/kubernetes/typed/authentication/v1alpha1/authentication_client.go @@ -45,9 +45,7 @@ func (c *AuthenticationV1alpha1Client) SelfSubjectReviews() SelfSubjectReviewInt // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AuthenticationV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*AuthenticationV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *AuthenticationV1alpha1Client { return &AuthenticationV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := authenticationv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/authentication/v1beta1/authentication_client.go b/kubernetes/typed/authentication/v1beta1/authentication_client.go index 7b22e46e31..b8c8eab7f3 100644 --- a/kubernetes/typed/authentication/v1beta1/authentication_client.go +++ b/kubernetes/typed/authentication/v1beta1/authentication_client.go @@ -50,9 +50,7 @@ func (c *AuthenticationV1beta1Client) TokenReviews() TokenReviewInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AuthenticationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*AuthenticationV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *AuthenticationV1beta1Client { return &AuthenticationV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := authenticationv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/authorization/v1/authorization_client.go b/kubernetes/typed/authorization/v1/authorization_client.go index 71fb89b383..5c290f9f32 100644 --- a/kubernetes/typed/authorization/v1/authorization_client.go +++ b/kubernetes/typed/authorization/v1/authorization_client.go @@ -60,9 +60,7 @@ func (c *AuthorizationV1Client) SubjectAccessReviews() SubjectAccessReviewInterf // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AuthorizationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*AuthorizationV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthorizationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *AuthorizationV1Client { return &AuthorizationV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := authorizationv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/authorization/v1beta1/authorization_client.go b/kubernetes/typed/authorization/v1beta1/authorization_client.go index f33619eb38..648e692259 100644 --- a/kubernetes/typed/authorization/v1beta1/authorization_client.go +++ b/kubernetes/typed/authorization/v1beta1/authorization_client.go @@ -60,9 +60,7 @@ func (c *AuthorizationV1beta1Client) SubjectAccessReviews() SubjectAccessReviewI // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AuthorizationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*AuthorizationV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthorizationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *AuthorizationV1beta1Client { return &AuthorizationV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := authorizationv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/autoscaling/v1/autoscaling_client.go b/kubernetes/typed/autoscaling/v1/autoscaling_client.go index 6ceaaf82af..4f7de82a01 100644 --- a/kubernetes/typed/autoscaling/v1/autoscaling_client.go +++ b/kubernetes/typed/autoscaling/v1/autoscaling_client.go @@ -45,9 +45,7 @@ func (c *AutoscalingV1Client) HorizontalPodAutoscalers(namespace string) Horizon // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AutoscalingV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*AutoscalingV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *AutoscalingV1Client { return &AutoscalingV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := autoscalingv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/autoscaling/v2/autoscaling_client.go b/kubernetes/typed/autoscaling/v2/autoscaling_client.go index 78a2609bf4..bedc3d8a17 100644 --- a/kubernetes/typed/autoscaling/v2/autoscaling_client.go +++ b/kubernetes/typed/autoscaling/v2/autoscaling_client.go @@ -45,9 +45,7 @@ func (c *AutoscalingV2Client) HorizontalPodAutoscalers(namespace string) Horizon // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AutoscalingV2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*AutoscalingV2Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *AutoscalingV2Client { return &AutoscalingV2Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := autoscalingv2.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go b/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go index 1fcda17c81..25e38f371d 100644 --- a/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go +++ b/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go @@ -45,9 +45,7 @@ func (c *AutoscalingV2beta1Client) HorizontalPodAutoscalers(namespace string) Ho // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AutoscalingV2beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*AutoscalingV2beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *AutoscalingV2beta1Client { return &AutoscalingV2beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := autoscalingv2beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go b/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go index 62f5b743c7..21626e5ce7 100644 --- a/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go +++ b/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go @@ -45,9 +45,7 @@ func (c *AutoscalingV2beta2Client) HorizontalPodAutoscalers(namespace string) Ho // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*AutoscalingV2beta2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*AutoscalingV2beta2Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2beta2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *AutoscalingV2beta2Client { return &AutoscalingV2beta2Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := autoscalingv2beta2.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/batch/v1/batch_client.go b/kubernetes/typed/batch/v1/batch_client.go index 614d049f3b..56deda20ce 100644 --- a/kubernetes/typed/batch/v1/batch_client.go +++ b/kubernetes/typed/batch/v1/batch_client.go @@ -50,9 +50,7 @@ func (c *BatchV1Client) Jobs(namespace string) JobInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*BatchV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*BatchV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*BatchV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *BatchV1Client { return &BatchV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := batchv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/batch/v1beta1/batch_client.go b/kubernetes/typed/batch/v1beta1/batch_client.go index 2da9e41350..9de08074fc 100644 --- a/kubernetes/typed/batch/v1beta1/batch_client.go +++ b/kubernetes/typed/batch/v1beta1/batch_client.go @@ -45,9 +45,7 @@ func (c *BatchV1beta1Client) CronJobs(namespace string) CronJobInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*BatchV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*BatchV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*BatchV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *BatchV1beta1Client { return &BatchV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := batchv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/certificates/v1/certificates_client.go b/kubernetes/typed/certificates/v1/certificates_client.go index 60337cd23f..a13c3559db 100644 --- a/kubernetes/typed/certificates/v1/certificates_client.go +++ b/kubernetes/typed/certificates/v1/certificates_client.go @@ -45,9 +45,7 @@ func (c *CertificatesV1Client) CertificateSigningRequests() CertificateSigningRe // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*CertificatesV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*CertificatesV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *CertificatesV1Client { return &CertificatesV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := certificatesv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/certificates/v1alpha1/certificates_client.go b/kubernetes/typed/certificates/v1alpha1/certificates_client.go index 36e08253af..163ddad017 100644 --- a/kubernetes/typed/certificates/v1alpha1/certificates_client.go +++ b/kubernetes/typed/certificates/v1alpha1/certificates_client.go @@ -45,9 +45,7 @@ func (c *CertificatesV1alpha1Client) ClusterTrustBundles() ClusterTrustBundleInt // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*CertificatesV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*CertificatesV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *CertificatesV1alpha1Client { return &CertificatesV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := certificatesv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/certificates/v1beta1/certificates_client.go b/kubernetes/typed/certificates/v1beta1/certificates_client.go index f040e7664e..8de95609f5 100644 --- a/kubernetes/typed/certificates/v1beta1/certificates_client.go +++ b/kubernetes/typed/certificates/v1beta1/certificates_client.go @@ -29,6 +29,7 @@ import ( type CertificatesV1beta1Interface interface { RESTClient() rest.Interface CertificateSigningRequestsGetter + ClusterTrustBundlesGetter } // CertificatesV1beta1Client is used to interact with features provided by the certificates.k8s.io group. @@ -40,14 +41,16 @@ func (c *CertificatesV1beta1Client) CertificateSigningRequests() CertificateSign return newCertificateSigningRequests(c) } +func (c *CertificatesV1beta1Client) ClusterTrustBundles() ClusterTrustBundleInterface { + return newClusterTrustBundles(c) +} + // NewForConfig creates a new CertificatesV1beta1Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +62,7 @@ func NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +85,7 @@ func New(c rest.Interface) *CertificatesV1beta1Client { return &CertificatesV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := certificatesv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/certificates/v1beta1/clustertrustbundle.go b/kubernetes/typed/certificates/v1beta1/clustertrustbundle.go new file mode 100644 index 0000000000..c4d93d7b22 --- /dev/null +++ b/kubernetes/typed/certificates/v1beta1/clustertrustbundle.go @@ -0,0 +1,73 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + + certificatesv1beta1 "k8s.io/api/certificates/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationscertificatesv1beta1 "k8s.io/client-go/applyconfigurations/certificates/v1beta1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// ClusterTrustBundlesGetter has a method to return a ClusterTrustBundleInterface. +// A group's client should implement this interface. +type ClusterTrustBundlesGetter interface { + ClusterTrustBundles() ClusterTrustBundleInterface +} + +// ClusterTrustBundleInterface has methods to work with ClusterTrustBundle resources. +type ClusterTrustBundleInterface interface { + Create(ctx context.Context, clusterTrustBundle *certificatesv1beta1.ClusterTrustBundle, opts v1.CreateOptions) (*certificatesv1beta1.ClusterTrustBundle, error) + Update(ctx context.Context, clusterTrustBundle *certificatesv1beta1.ClusterTrustBundle, opts v1.UpdateOptions) (*certificatesv1beta1.ClusterTrustBundle, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*certificatesv1beta1.ClusterTrustBundle, error) + List(ctx context.Context, opts v1.ListOptions) (*certificatesv1beta1.ClusterTrustBundleList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *certificatesv1beta1.ClusterTrustBundle, err error) + Apply(ctx context.Context, clusterTrustBundle *applyconfigurationscertificatesv1beta1.ClusterTrustBundleApplyConfiguration, opts v1.ApplyOptions) (result *certificatesv1beta1.ClusterTrustBundle, err error) + ClusterTrustBundleExpansion +} + +// clusterTrustBundles implements ClusterTrustBundleInterface +type clusterTrustBundles struct { + *gentype.ClientWithListAndApply[*certificatesv1beta1.ClusterTrustBundle, *certificatesv1beta1.ClusterTrustBundleList, *applyconfigurationscertificatesv1beta1.ClusterTrustBundleApplyConfiguration] +} + +// newClusterTrustBundles returns a ClusterTrustBundles +func newClusterTrustBundles(c *CertificatesV1beta1Client) *clusterTrustBundles { + return &clusterTrustBundles{ + gentype.NewClientWithListAndApply[*certificatesv1beta1.ClusterTrustBundle, *certificatesv1beta1.ClusterTrustBundleList, *applyconfigurationscertificatesv1beta1.ClusterTrustBundleApplyConfiguration]( + "clustertrustbundles", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *certificatesv1beta1.ClusterTrustBundle { return &certificatesv1beta1.ClusterTrustBundle{} }, + func() *certificatesv1beta1.ClusterTrustBundleList { + return &certificatesv1beta1.ClusterTrustBundleList{} + }, + gentype.PrefersProtobuf[*certificatesv1beta1.ClusterTrustBundle](), + ), + } +} diff --git a/kubernetes/typed/certificates/v1beta1/fake/fake_certificates_client.go b/kubernetes/typed/certificates/v1beta1/fake/fake_certificates_client.go index 313df7abd2..fba168ea18 100644 --- a/kubernetes/typed/certificates/v1beta1/fake/fake_certificates_client.go +++ b/kubernetes/typed/certificates/v1beta1/fake/fake_certificates_client.go @@ -32,6 +32,10 @@ func (c *FakeCertificatesV1beta1) CertificateSigningRequests() v1beta1.Certifica return newFakeCertificateSigningRequests(c) } +func (c *FakeCertificatesV1beta1) ClusterTrustBundles() v1beta1.ClusterTrustBundleInterface { + return newFakeClusterTrustBundles(c) +} + // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *FakeCertificatesV1beta1) RESTClient() rest.Interface { diff --git a/kubernetes/typed/certificates/v1beta1/fake/fake_clustertrustbundle.go b/kubernetes/typed/certificates/v1beta1/fake/fake_clustertrustbundle.go new file mode 100644 index 0000000000..ff88f73538 --- /dev/null +++ b/kubernetes/typed/certificates/v1beta1/fake/fake_clustertrustbundle.go @@ -0,0 +1,53 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta1 "k8s.io/api/certificates/v1beta1" + certificatesv1beta1 "k8s.io/client-go/applyconfigurations/certificates/v1beta1" + gentype "k8s.io/client-go/gentype" + typedcertificatesv1beta1 "k8s.io/client-go/kubernetes/typed/certificates/v1beta1" +) + +// fakeClusterTrustBundles implements ClusterTrustBundleInterface +type fakeClusterTrustBundles struct { + *gentype.FakeClientWithListAndApply[*v1beta1.ClusterTrustBundle, *v1beta1.ClusterTrustBundleList, *certificatesv1beta1.ClusterTrustBundleApplyConfiguration] + Fake *FakeCertificatesV1beta1 +} + +func newFakeClusterTrustBundles(fake *FakeCertificatesV1beta1) typedcertificatesv1beta1.ClusterTrustBundleInterface { + return &fakeClusterTrustBundles{ + gentype.NewFakeClientWithListAndApply[*v1beta1.ClusterTrustBundle, *v1beta1.ClusterTrustBundleList, *certificatesv1beta1.ClusterTrustBundleApplyConfiguration]( + fake.Fake, + "", + v1beta1.SchemeGroupVersion.WithResource("clustertrustbundles"), + v1beta1.SchemeGroupVersion.WithKind("ClusterTrustBundle"), + func() *v1beta1.ClusterTrustBundle { return &v1beta1.ClusterTrustBundle{} }, + func() *v1beta1.ClusterTrustBundleList { return &v1beta1.ClusterTrustBundleList{} }, + func(dst, src *v1beta1.ClusterTrustBundleList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.ClusterTrustBundleList) []*v1beta1.ClusterTrustBundle { + return gentype.ToPointerSlice(list.Items) + }, + func(list *v1beta1.ClusterTrustBundleList, items []*v1beta1.ClusterTrustBundle) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/kubernetes/typed/certificates/v1beta1/generated_expansion.go b/kubernetes/typed/certificates/v1beta1/generated_expansion.go index f6df769632..408936e06b 100644 --- a/kubernetes/typed/certificates/v1beta1/generated_expansion.go +++ b/kubernetes/typed/certificates/v1beta1/generated_expansion.go @@ -17,3 +17,5 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. package v1beta1 + +type ClusterTrustBundleExpansion interface{} diff --git a/kubernetes/typed/coordination/v1/coordination_client.go b/kubernetes/typed/coordination/v1/coordination_client.go index 427cb7e936..52cfcca052 100644 --- a/kubernetes/typed/coordination/v1/coordination_client.go +++ b/kubernetes/typed/coordination/v1/coordination_client.go @@ -45,9 +45,7 @@ func (c *CoordinationV1Client) Leases(namespace string) LeaseInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*CoordinationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*CoordinationV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoordinationV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *CoordinationV1Client { return &CoordinationV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := coordinationv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/coordination/v1alpha2/coordination_client.go b/kubernetes/typed/coordination/v1alpha2/coordination_client.go index 4c286d4632..2fd87f68e4 100644 --- a/kubernetes/typed/coordination/v1alpha2/coordination_client.go +++ b/kubernetes/typed/coordination/v1alpha2/coordination_client.go @@ -45,9 +45,7 @@ func (c *CoordinationV1alpha2Client) LeaseCandidates(namespace string) LeaseCand // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*CoordinationV1alpha2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*CoordinationV1alpha2Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoordinationV1alpha2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *CoordinationV1alpha2Client { return &CoordinationV1alpha2Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := coordinationv1alpha2.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/coordination/v1beta1/coordination_client.go b/kubernetes/typed/coordination/v1beta1/coordination_client.go index 1f1afba240..fa0af1c0a5 100644 --- a/kubernetes/typed/coordination/v1beta1/coordination_client.go +++ b/kubernetes/typed/coordination/v1beta1/coordination_client.go @@ -29,6 +29,7 @@ import ( type CoordinationV1beta1Interface interface { RESTClient() rest.Interface LeasesGetter + LeaseCandidatesGetter } // CoordinationV1beta1Client is used to interact with features provided by the coordination.k8s.io group. @@ -40,14 +41,16 @@ func (c *CoordinationV1beta1Client) Leases(namespace string) LeaseInterface { return newLeases(c, namespace) } +func (c *CoordinationV1beta1Client) LeaseCandidates(namespace string) LeaseCandidateInterface { + return newLeaseCandidates(c, namespace) +} + // NewForConfig creates a new CoordinationV1beta1Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*CoordinationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +62,7 @@ func NewForConfig(c *rest.Config) (*CoordinationV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoordinationV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +85,7 @@ func New(c rest.Interface) *CoordinationV1beta1Client { return &CoordinationV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := coordinationv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/coordination/v1beta1/fake/fake_coordination_client.go b/kubernetes/typed/coordination/v1beta1/fake/fake_coordination_client.go index 41b3ce06bf..c4eca7ecd1 100644 --- a/kubernetes/typed/coordination/v1beta1/fake/fake_coordination_client.go +++ b/kubernetes/typed/coordination/v1beta1/fake/fake_coordination_client.go @@ -32,6 +32,10 @@ func (c *FakeCoordinationV1beta1) Leases(namespace string) v1beta1.LeaseInterfac return newFakeLeases(c, namespace) } +func (c *FakeCoordinationV1beta1) LeaseCandidates(namespace string) v1beta1.LeaseCandidateInterface { + return newFakeLeaseCandidates(c, namespace) +} + // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *FakeCoordinationV1beta1) RESTClient() rest.Interface { diff --git a/kubernetes/typed/coordination/v1beta1/fake/fake_leasecandidate.go b/kubernetes/typed/coordination/v1beta1/fake/fake_leasecandidate.go new file mode 100644 index 0000000000..bd5587b924 --- /dev/null +++ b/kubernetes/typed/coordination/v1beta1/fake/fake_leasecandidate.go @@ -0,0 +1,53 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta1 "k8s.io/api/coordination/v1beta1" + coordinationv1beta1 "k8s.io/client-go/applyconfigurations/coordination/v1beta1" + gentype "k8s.io/client-go/gentype" + typedcoordinationv1beta1 "k8s.io/client-go/kubernetes/typed/coordination/v1beta1" +) + +// fakeLeaseCandidates implements LeaseCandidateInterface +type fakeLeaseCandidates struct { + *gentype.FakeClientWithListAndApply[*v1beta1.LeaseCandidate, *v1beta1.LeaseCandidateList, *coordinationv1beta1.LeaseCandidateApplyConfiguration] + Fake *FakeCoordinationV1beta1 +} + +func newFakeLeaseCandidates(fake *FakeCoordinationV1beta1, namespace string) typedcoordinationv1beta1.LeaseCandidateInterface { + return &fakeLeaseCandidates{ + gentype.NewFakeClientWithListAndApply[*v1beta1.LeaseCandidate, *v1beta1.LeaseCandidateList, *coordinationv1beta1.LeaseCandidateApplyConfiguration]( + fake.Fake, + namespace, + v1beta1.SchemeGroupVersion.WithResource("leasecandidates"), + v1beta1.SchemeGroupVersion.WithKind("LeaseCandidate"), + func() *v1beta1.LeaseCandidate { return &v1beta1.LeaseCandidate{} }, + func() *v1beta1.LeaseCandidateList { return &v1beta1.LeaseCandidateList{} }, + func(dst, src *v1beta1.LeaseCandidateList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta1.LeaseCandidateList) []*v1beta1.LeaseCandidate { + return gentype.ToPointerSlice(list.Items) + }, + func(list *v1beta1.LeaseCandidateList, items []*v1beta1.LeaseCandidate) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/kubernetes/typed/coordination/v1beta1/generated_expansion.go b/kubernetes/typed/coordination/v1beta1/generated_expansion.go index dfd180daf3..a341e2aff3 100644 --- a/kubernetes/typed/coordination/v1beta1/generated_expansion.go +++ b/kubernetes/typed/coordination/v1beta1/generated_expansion.go @@ -19,3 +19,5 @@ limitations under the License. package v1beta1 type LeaseExpansion interface{} + +type LeaseCandidateExpansion interface{} diff --git a/kubernetes/typed/coordination/v1beta1/leasecandidate.go b/kubernetes/typed/coordination/v1beta1/leasecandidate.go new file mode 100644 index 0000000000..505be1be0d --- /dev/null +++ b/kubernetes/typed/coordination/v1beta1/leasecandidate.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + + coordinationv1beta1 "k8s.io/api/coordination/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationscoordinationv1beta1 "k8s.io/client-go/applyconfigurations/coordination/v1beta1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// LeaseCandidatesGetter has a method to return a LeaseCandidateInterface. +// A group's client should implement this interface. +type LeaseCandidatesGetter interface { + LeaseCandidates(namespace string) LeaseCandidateInterface +} + +// LeaseCandidateInterface has methods to work with LeaseCandidate resources. +type LeaseCandidateInterface interface { + Create(ctx context.Context, leaseCandidate *coordinationv1beta1.LeaseCandidate, opts v1.CreateOptions) (*coordinationv1beta1.LeaseCandidate, error) + Update(ctx context.Context, leaseCandidate *coordinationv1beta1.LeaseCandidate, opts v1.UpdateOptions) (*coordinationv1beta1.LeaseCandidate, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*coordinationv1beta1.LeaseCandidate, error) + List(ctx context.Context, opts v1.ListOptions) (*coordinationv1beta1.LeaseCandidateList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *coordinationv1beta1.LeaseCandidate, err error) + Apply(ctx context.Context, leaseCandidate *applyconfigurationscoordinationv1beta1.LeaseCandidateApplyConfiguration, opts v1.ApplyOptions) (result *coordinationv1beta1.LeaseCandidate, err error) + LeaseCandidateExpansion +} + +// leaseCandidates implements LeaseCandidateInterface +type leaseCandidates struct { + *gentype.ClientWithListAndApply[*coordinationv1beta1.LeaseCandidate, *coordinationv1beta1.LeaseCandidateList, *applyconfigurationscoordinationv1beta1.LeaseCandidateApplyConfiguration] +} + +// newLeaseCandidates returns a LeaseCandidates +func newLeaseCandidates(c *CoordinationV1beta1Client, namespace string) *leaseCandidates { + return &leaseCandidates{ + gentype.NewClientWithListAndApply[*coordinationv1beta1.LeaseCandidate, *coordinationv1beta1.LeaseCandidateList, *applyconfigurationscoordinationv1beta1.LeaseCandidateApplyConfiguration]( + "leasecandidates", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *coordinationv1beta1.LeaseCandidate { return &coordinationv1beta1.LeaseCandidate{} }, + func() *coordinationv1beta1.LeaseCandidateList { return &coordinationv1beta1.LeaseCandidateList{} }, + gentype.PrefersProtobuf[*coordinationv1beta1.LeaseCandidate](), + ), + } +} diff --git a/kubernetes/typed/core/v1/core_client.go b/kubernetes/typed/core/v1/core_client.go index abf85cba64..0a9380cf82 100644 --- a/kubernetes/typed/core/v1/core_client.go +++ b/kubernetes/typed/core/v1/core_client.go @@ -120,9 +120,7 @@ func (c *CoreV1Client) ServiceAccounts(namespace string) ServiceAccountInterface // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*CoreV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -134,9 +132,7 @@ func NewForConfig(c *rest.Config) (*CoreV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoreV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -159,7 +155,7 @@ func New(c rest.Interface) *CoreV1Client { return &CoreV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := corev1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/api" @@ -168,8 +164,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/core/v1/event_expansion.go b/kubernetes/typed/core/v1/event_expansion.go index 4243572328..ddecf93b1e 100644 --- a/kubernetes/typed/core/v1/event_expansion.go +++ b/kubernetes/typed/core/v1/event_expansion.go @@ -31,13 +31,29 @@ import ( // The EventExpansion interface allows manually adding extra methods to the EventInterface. type EventExpansion interface { // CreateWithEventNamespace is the same as a Create, except that it sends the request to the event.Namespace. + // + // Deprecated: use CreateWithEventNamespaceWithContext instead. CreateWithEventNamespace(event *v1.Event) (*v1.Event, error) // UpdateWithEventNamespace is the same as a Update, except that it sends the request to the event.Namespace. + // + // Deprecated: use UpdateWithEventNamespaceWithContext instead. UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error) // PatchWithEventNamespace is the same as a Patch, except that it sends the request to the event.Namespace. + // + // Deprecated: use PatchWithEventNamespaceWithContext instead. PatchWithEventNamespace(event *v1.Event, data []byte) (*v1.Event, error) // Search finds events about the specified object + // + // Deprecated: use SearchWithContext instead. Search(scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) + // CreateWithEventNamespaceWithContext is the same as a Create, except that it sends the request to the event.Namespace. + CreateWithEventNamespaceWithContext(ctx context.Context, event *v1.Event) (*v1.Event, error) + // UpdateWithEventNamespaceWithContext is the same as a Update, except that it sends the request to the event.Namespace. + UpdateWithEventNamespaceWithContext(ctx context.Context, event *v1.Event) (*v1.Event, error) + // PatchWithEventNamespaceWithContext is the same as a Patch, except that it sends the request to the event.Namespace. + PatchWithEventNamespaceWithContext(ctx context.Context, event *v1.Event, data []byte) (*v1.Event, error) + // SearchWithContext finds events about the specified object + SearchWithContext(ctx context.Context, scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) // Returns the appropriate field selector based on the API version being used to communicate with the server. // The returned field selector can be used with List and Watch to filter desired events. GetFieldSelector(involvedObjectName, involvedObjectNamespace, involvedObjectKind, involvedObjectUID *string) fields.Selector @@ -47,7 +63,17 @@ type EventExpansion interface { // or an error. The namespace to create the event within is deduced from the // event; it must either match this event client's namespace, or this event // client must have been created with the "" namespace. +// +// Deprecated: use CreateWithEventNamespaceWithContext instead. func (e *events) CreateWithEventNamespace(event *v1.Event) (*v1.Event, error) { + return e.CreateWithEventNamespaceWithContext(context.Background(), event) +} + +// CreateWithEventNamespaceWithContext makes a new event. Returns the copy of the event the server returns, +// or an error. The namespace to create the event within is deduced from the +// event; it must either match this event client's namespace, or this event +// client must have been created with the "" namespace. +func (e *events) CreateWithEventNamespaceWithContext(ctx context.Context, event *v1.Event) (*v1.Event, error) { if e.GetNamespace() != "" && event.Namespace != e.GetNamespace() { return nil, fmt.Errorf("can't create an event with namespace '%v' in namespace '%v'", event.Namespace, e.GetNamespace()) } @@ -56,7 +82,7 @@ func (e *events) CreateWithEventNamespace(event *v1.Event) (*v1.Event, error) { NamespaceIfScoped(event.Namespace, len(event.Namespace) > 0). Resource("events"). Body(event). - Do(context.TODO()). + Do(ctx). Into(result) return result, err } @@ -66,7 +92,18 @@ func (e *events) CreateWithEventNamespace(event *v1.Event) (*v1.Event, error) { // namespace must either match this event client's namespace, or this event client must have been // created with the "" namespace. Update also requires the ResourceVersion to be set in the event // object. +// +// Deprecated: use UpdateWithEventNamespaceWithContext instead. func (e *events) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error) { + return e.UpdateWithEventNamespaceWithContext(context.Background(), event) +} + +// UpdateWithEventNamespaceWithContext modifies an existing event. It returns the copy of the event that the server returns, +// or an error. The namespace and key to update the event within is deduced from the event. The +// namespace must either match this event client's namespace, or this event client must have been +// created with the "" namespace. Update also requires the ResourceVersion to be set in the event +// object. +func (e *events) UpdateWithEventNamespaceWithContext(ctx context.Context, event *v1.Event) (*v1.Event, error) { if e.GetNamespace() != "" && event.Namespace != e.GetNamespace() { return nil, fmt.Errorf("can't update an event with namespace '%v' in namespace '%v'", event.Namespace, e.GetNamespace()) } @@ -76,7 +113,7 @@ func (e *events) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error) { Resource("events"). Name(event.Name). Body(event). - Do(context.TODO()). + Do(ctx). Into(result) return result, err } @@ -86,7 +123,18 @@ func (e *events) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error) { // target event is deduced from the incompleteEvent. The namespace must either // match this event client's namespace, or this event client must have been // created with the "" namespace. +// +// Deprecated: use PatchWithEventNamespaceWithContext instead. func (e *events) PatchWithEventNamespace(incompleteEvent *v1.Event, data []byte) (*v1.Event, error) { + return e.PatchWithEventNamespaceWithContext(context.Background(), incompleteEvent, data) +} + +// PatchWithEventNamespaceWithContext modifies an existing event. It returns the copy of +// the event that the server returns, or an error. The namespace and name of the +// target event is deduced from the incompleteEvent. The namespace must either +// match this event client's namespace, or this event client must have been +// created with the "" namespace. +func (e *events) PatchWithEventNamespaceWithContext(ctx context.Context, incompleteEvent *v1.Event, data []byte) (*v1.Event, error) { if e.GetNamespace() != "" && incompleteEvent.Namespace != e.GetNamespace() { return nil, fmt.Errorf("can't patch an event with namespace '%v' in namespace '%v'", incompleteEvent.Namespace, e.GetNamespace()) } @@ -96,7 +144,7 @@ func (e *events) PatchWithEventNamespace(incompleteEvent *v1.Event, data []byte) Resource("events"). Name(incompleteEvent.Name). Body(data). - Do(context.TODO()). + Do(ctx). Into(result) return result, err } @@ -104,7 +152,16 @@ func (e *events) PatchWithEventNamespace(incompleteEvent *v1.Event, data []byte) // Search finds events about the specified object. The namespace of the // object must match this event's client namespace unless the event client // was made with the "" namespace. +// +// Deprecated: use SearchWithContext instead. func (e *events) Search(scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) { + return e.SearchWithContext(context.Background(), scheme, objOrRef) +} + +// SearchWithContext finds events about the specified object. The namespace of the +// object must match this event's client namespace unless the event client +// was made with the "" namespace. +func (e *events) SearchWithContext(ctx context.Context, scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) { ref, err := ref.GetReference(scheme, objOrRef) if err != nil { return nil, err @@ -123,7 +180,7 @@ func (e *events) Search(scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.Ev refUID = &stringRefUID } fieldSelector := e.GetFieldSelector(&ref.Name, &ref.Namespace, refKind, refUID) - return e.List(context.TODO(), metav1.ListOptions{FieldSelector: fieldSelector.String()}) + return e.List(ctx, metav1.ListOptions{FieldSelector: fieldSelector.String()}) } // Returns the appropriate field selector based on the API version being used to communicate with the server. diff --git a/kubernetes/typed/core/v1/fake/fake_event_expansion.go b/kubernetes/typed/core/v1/fake/fake_event_expansion.go index 3840f6323c..944d6808de 100644 --- a/kubernetes/typed/core/v1/fake/fake_event_expansion.go +++ b/kubernetes/typed/core/v1/fake/fake_event_expansion.go @@ -17,6 +17,8 @@ limitations under the License. package fake import ( + "context" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -25,7 +27,12 @@ import ( core "k8s.io/client-go/testing" ) +// Deprecated: use CreateWithEventNamespaceWithContext instead. func (c *fakeEvents) CreateWithEventNamespace(event *v1.Event) (*v1.Event, error) { + return c.CreateWithEventNamespaceWithContext(context.Background(), event) +} + +func (c *fakeEvents) CreateWithEventNamespaceWithContext(_ context.Context, event *v1.Event) (*v1.Event, error) { var action core.CreateActionImpl if c.Namespace() != "" { action = core.NewCreateAction(c.Resource(), c.Namespace(), event) @@ -41,7 +48,14 @@ func (c *fakeEvents) CreateWithEventNamespace(event *v1.Event) (*v1.Event, error } // Update replaces an existing event. Returns the copy of the event the server returns, or an error. +// +// Deprecated: use UpdateWithEventNamespaceWithContext instead. func (c *fakeEvents) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error) { + return c.UpdateWithEventNamespaceWithContext(context.Background(), event) +} + +// Update replaces an existing event. Returns the copy of the event the server returns, or an error. +func (c *fakeEvents) UpdateWithEventNamespaceWithContext(_ context.Context, event *v1.Event) (*v1.Event, error) { var action core.UpdateActionImpl if c.Namespace() != "" { action = core.NewUpdateAction(c.Resource(), c.Namespace(), event) @@ -58,7 +72,15 @@ func (c *fakeEvents) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error // PatchWithEventNamespace patches an existing event. Returns the copy of the event the server returns, or an error. // TODO: Should take a PatchType as an argument probably. +// +// Deprecated: use PatchWithEventNamespaceWithContext instead. func (c *fakeEvents) PatchWithEventNamespace(event *v1.Event, data []byte) (*v1.Event, error) { + return c.PatchWithEventNamespaceWithContext(context.Background(), event, data) +} + +// PatchWithEventNamespaceWithContext patches an existing event. Returns the copy of the event the server returns, or an error. +// TODO: Should take a PatchType as an argument probably. +func (c *fakeEvents) PatchWithEventNamespaceWithContext(_ context.Context, event *v1.Event, data []byte) (*v1.Event, error) { // TODO: Should be configurable to support additional patch strategies. pt := types.StrategicMergePatchType var action core.PatchActionImpl @@ -76,7 +98,14 @@ func (c *fakeEvents) PatchWithEventNamespace(event *v1.Event, data []byte) (*v1. } // Search returns a list of events matching the specified object. +// +// Deprecated: use SearchWithContext instead. func (c *fakeEvents) Search(scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) { + return c.SearchWithContext(context.Background(), scheme, objOrRef) +} + +// SearchWithContext returns a list of events matching the specified object. +func (c *fakeEvents) SearchWithContext(_ context.Context, scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) { var action core.ListActionImpl if c.Namespace() != "" { action = core.NewListAction(c.Resource(), c.Kind(), c.Namespace(), metav1.ListOptions{}) diff --git a/kubernetes/typed/discovery/v1/discovery_client.go b/kubernetes/typed/discovery/v1/discovery_client.go index fbc685df82..876058d7a2 100644 --- a/kubernetes/typed/discovery/v1/discovery_client.go +++ b/kubernetes/typed/discovery/v1/discovery_client.go @@ -45,9 +45,7 @@ func (c *DiscoveryV1Client) EndpointSlices(namespace string) EndpointSliceInterf // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*DiscoveryV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*DiscoveryV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*DiscoveryV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *DiscoveryV1Client { return &DiscoveryV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := discoveryv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/discovery/v1beta1/discovery_client.go b/kubernetes/typed/discovery/v1beta1/discovery_client.go index 908446c6d5..d37de40506 100644 --- a/kubernetes/typed/discovery/v1beta1/discovery_client.go +++ b/kubernetes/typed/discovery/v1beta1/discovery_client.go @@ -45,9 +45,7 @@ func (c *DiscoveryV1beta1Client) EndpointSlices(namespace string) EndpointSliceI // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*DiscoveryV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*DiscoveryV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*DiscoveryV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *DiscoveryV1beta1Client { return &DiscoveryV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := discoveryv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/events/v1/events_client.go b/kubernetes/typed/events/v1/events_client.go index 959ff5f81a..6d7f7553b6 100644 --- a/kubernetes/typed/events/v1/events_client.go +++ b/kubernetes/typed/events/v1/events_client.go @@ -45,9 +45,7 @@ func (c *EventsV1Client) Events(namespace string) EventInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*EventsV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*EventsV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*EventsV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *EventsV1Client { return &EventsV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := eventsv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/events/v1beta1/event_expansion.go b/kubernetes/typed/events/v1beta1/event_expansion.go index 4ddbaa31af..bdade2c7fe 100644 --- a/kubernetes/typed/events/v1beta1/event_expansion.go +++ b/kubernetes/typed/events/v1beta1/event_expansion.go @@ -52,7 +52,7 @@ func (e *events) CreateWithEventNamespace(event *v1beta1.Event) (*v1beta1.Event, NamespaceIfScoped(event.Namespace, len(event.Namespace) > 0). Resource("events"). Body(event). - Do(context.TODO()). + Do(context.Background() /* Nothing to do here, v1beta1 will be removed eventually. */). Into(result) return result, err } @@ -73,7 +73,7 @@ func (e *events) UpdateWithEventNamespace(event *v1beta1.Event) (*v1beta1.Event, Resource("events"). Name(event.Name). Body(event). - Do(context.TODO()). + Do(context.Background() /* Nothing to do here, v1beta1 will be removed eventually. */). Into(result) return result, err } @@ -93,7 +93,7 @@ func (e *events) PatchWithEventNamespace(event *v1beta1.Event, data []byte) (*v1 Resource("events"). Name(event.Name). Body(data). - Do(context.TODO()). + Do(context.Background() /* Nothing to do here, v1beta1 will be removed eventually. */). Into(result) return result, err } diff --git a/kubernetes/typed/events/v1beta1/events_client.go b/kubernetes/typed/events/v1beta1/events_client.go index 0bfc3cb607..6670d57cd1 100644 --- a/kubernetes/typed/events/v1beta1/events_client.go +++ b/kubernetes/typed/events/v1beta1/events_client.go @@ -45,9 +45,7 @@ func (c *EventsV1beta1Client) Events(namespace string) EventInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*EventsV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *EventsV1beta1Client { return &EventsV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := eventsv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/extensions/v1beta1/extensions_client.go b/kubernetes/typed/extensions/v1beta1/extensions_client.go index 88f2279bb0..ccbd29637d 100644 --- a/kubernetes/typed/extensions/v1beta1/extensions_client.go +++ b/kubernetes/typed/extensions/v1beta1/extensions_client.go @@ -65,9 +65,7 @@ func (c *ExtensionsV1beta1Client) ReplicaSets(namespace string) ReplicaSetInterf // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*ExtensionsV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -79,9 +77,7 @@ func NewForConfig(c *rest.Config) (*ExtensionsV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ExtensionsV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -104,7 +100,7 @@ func New(c rest.Interface) *ExtensionsV1beta1Client { return &ExtensionsV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := extensionsv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -113,8 +109,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/flowcontrol/v1/flowcontrol_client.go b/kubernetes/typed/flowcontrol/v1/flowcontrol_client.go index 3b19586e91..a8af7106a3 100644 --- a/kubernetes/typed/flowcontrol/v1/flowcontrol_client.go +++ b/kubernetes/typed/flowcontrol/v1/flowcontrol_client.go @@ -50,9 +50,7 @@ func (c *FlowcontrolV1Client) PriorityLevelConfigurations() PriorityLevelConfigu // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*FlowcontrolV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*FlowcontrolV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *FlowcontrolV1Client { return &FlowcontrolV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := flowcontrolv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go b/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go index ac3f5ffe81..d7517f9868 100644 --- a/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go +++ b/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go @@ -50,9 +50,7 @@ func (c *FlowcontrolV1beta1Client) PriorityLevelConfigurations() PriorityLevelCo // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*FlowcontrolV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*FlowcontrolV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *FlowcontrolV1beta1Client { return &FlowcontrolV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := flowcontrolv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go b/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go index 7652d4f39b..6cac8b89a9 100644 --- a/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go +++ b/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go @@ -50,9 +50,7 @@ func (c *FlowcontrolV1beta2Client) PriorityLevelConfigurations() PriorityLevelCo // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*FlowcontrolV1beta2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*FlowcontrolV1beta2Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta2Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *FlowcontrolV1beta2Client { return &FlowcontrolV1beta2Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := flowcontrolv1beta2.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go b/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go index b32dc911c7..340cedd67a 100644 --- a/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go +++ b/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go @@ -50,9 +50,7 @@ func (c *FlowcontrolV1beta3Client) PriorityLevelConfigurations() PriorityLevelCo // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*FlowcontrolV1beta3Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*FlowcontrolV1beta3Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta3Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *FlowcontrolV1beta3Client { return &FlowcontrolV1beta3Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := flowcontrolv1beta3.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/networking/v1/fake/fake_ipaddress.go b/kubernetes/typed/networking/v1/fake/fake_ipaddress.go new file mode 100644 index 0000000000..15f4e3c1ce --- /dev/null +++ b/kubernetes/typed/networking/v1/fake/fake_ipaddress.go @@ -0,0 +1,49 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1 "k8s.io/api/networking/v1" + networkingv1 "k8s.io/client-go/applyconfigurations/networking/v1" + gentype "k8s.io/client-go/gentype" + typednetworkingv1 "k8s.io/client-go/kubernetes/typed/networking/v1" +) + +// fakeIPAddresses implements IPAddressInterface +type fakeIPAddresses struct { + *gentype.FakeClientWithListAndApply[*v1.IPAddress, *v1.IPAddressList, *networkingv1.IPAddressApplyConfiguration] + Fake *FakeNetworkingV1 +} + +func newFakeIPAddresses(fake *FakeNetworkingV1) typednetworkingv1.IPAddressInterface { + return &fakeIPAddresses{ + gentype.NewFakeClientWithListAndApply[*v1.IPAddress, *v1.IPAddressList, *networkingv1.IPAddressApplyConfiguration]( + fake.Fake, + "", + v1.SchemeGroupVersion.WithResource("ipaddresses"), + v1.SchemeGroupVersion.WithKind("IPAddress"), + func() *v1.IPAddress { return &v1.IPAddress{} }, + func() *v1.IPAddressList { return &v1.IPAddressList{} }, + func(dst, src *v1.IPAddressList) { dst.ListMeta = src.ListMeta }, + func(list *v1.IPAddressList) []*v1.IPAddress { return gentype.ToPointerSlice(list.Items) }, + func(list *v1.IPAddressList, items []*v1.IPAddress) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, + } +} diff --git a/kubernetes/typed/networking/v1/fake/fake_networking_client.go b/kubernetes/typed/networking/v1/fake/fake_networking_client.go index 3b6a36ffee..ba61689e60 100644 --- a/kubernetes/typed/networking/v1/fake/fake_networking_client.go +++ b/kubernetes/typed/networking/v1/fake/fake_networking_client.go @@ -28,6 +28,10 @@ type FakeNetworkingV1 struct { *testing.Fake } +func (c *FakeNetworkingV1) IPAddresses() v1.IPAddressInterface { + return newFakeIPAddresses(c) +} + func (c *FakeNetworkingV1) Ingresses(namespace string) v1.IngressInterface { return newFakeIngresses(c, namespace) } @@ -40,6 +44,10 @@ func (c *FakeNetworkingV1) NetworkPolicies(namespace string) v1.NetworkPolicyInt return newFakeNetworkPolicies(c, namespace) } +func (c *FakeNetworkingV1) ServiceCIDRs() v1.ServiceCIDRInterface { + return newFakeServiceCIDRs(c) +} + // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *FakeNetworkingV1) RESTClient() rest.Interface { diff --git a/kubernetes/typed/networking/v1/fake/fake_servicecidr.go b/kubernetes/typed/networking/v1/fake/fake_servicecidr.go new file mode 100644 index 0000000000..c82391fb40 --- /dev/null +++ b/kubernetes/typed/networking/v1/fake/fake_servicecidr.go @@ -0,0 +1,49 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1 "k8s.io/api/networking/v1" + networkingv1 "k8s.io/client-go/applyconfigurations/networking/v1" + gentype "k8s.io/client-go/gentype" + typednetworkingv1 "k8s.io/client-go/kubernetes/typed/networking/v1" +) + +// fakeServiceCIDRs implements ServiceCIDRInterface +type fakeServiceCIDRs struct { + *gentype.FakeClientWithListAndApply[*v1.ServiceCIDR, *v1.ServiceCIDRList, *networkingv1.ServiceCIDRApplyConfiguration] + Fake *FakeNetworkingV1 +} + +func newFakeServiceCIDRs(fake *FakeNetworkingV1) typednetworkingv1.ServiceCIDRInterface { + return &fakeServiceCIDRs{ + gentype.NewFakeClientWithListAndApply[*v1.ServiceCIDR, *v1.ServiceCIDRList, *networkingv1.ServiceCIDRApplyConfiguration]( + fake.Fake, + "", + v1.SchemeGroupVersion.WithResource("servicecidrs"), + v1.SchemeGroupVersion.WithKind("ServiceCIDR"), + func() *v1.ServiceCIDR { return &v1.ServiceCIDR{} }, + func() *v1.ServiceCIDRList { return &v1.ServiceCIDRList{} }, + func(dst, src *v1.ServiceCIDRList) { dst.ListMeta = src.ListMeta }, + func(list *v1.ServiceCIDRList) []*v1.ServiceCIDR { return gentype.ToPointerSlice(list.Items) }, + func(list *v1.ServiceCIDRList, items []*v1.ServiceCIDR) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, + } +} diff --git a/kubernetes/typed/networking/v1/generated_expansion.go b/kubernetes/typed/networking/v1/generated_expansion.go index 52b70c514e..88f0f9f673 100644 --- a/kubernetes/typed/networking/v1/generated_expansion.go +++ b/kubernetes/typed/networking/v1/generated_expansion.go @@ -18,8 +18,12 @@ limitations under the License. package v1 +type IPAddressExpansion interface{} + type IngressExpansion interface{} type IngressClassExpansion interface{} type NetworkPolicyExpansion interface{} + +type ServiceCIDRExpansion interface{} diff --git a/kubernetes/typed/networking/v1/ipaddress.go b/kubernetes/typed/networking/v1/ipaddress.go new file mode 100644 index 0000000000..c3328cc3d7 --- /dev/null +++ b/kubernetes/typed/networking/v1/ipaddress.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + + networkingv1 "k8s.io/api/networking/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsnetworkingv1 "k8s.io/client-go/applyconfigurations/networking/v1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// IPAddressesGetter has a method to return a IPAddressInterface. +// A group's client should implement this interface. +type IPAddressesGetter interface { + IPAddresses() IPAddressInterface +} + +// IPAddressInterface has methods to work with IPAddress resources. +type IPAddressInterface interface { + Create(ctx context.Context, iPAddress *networkingv1.IPAddress, opts metav1.CreateOptions) (*networkingv1.IPAddress, error) + Update(ctx context.Context, iPAddress *networkingv1.IPAddress, opts metav1.UpdateOptions) (*networkingv1.IPAddress, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*networkingv1.IPAddress, error) + List(ctx context.Context, opts metav1.ListOptions) (*networkingv1.IPAddressList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *networkingv1.IPAddress, err error) + Apply(ctx context.Context, iPAddress *applyconfigurationsnetworkingv1.IPAddressApplyConfiguration, opts metav1.ApplyOptions) (result *networkingv1.IPAddress, err error) + IPAddressExpansion +} + +// iPAddresses implements IPAddressInterface +type iPAddresses struct { + *gentype.ClientWithListAndApply[*networkingv1.IPAddress, *networkingv1.IPAddressList, *applyconfigurationsnetworkingv1.IPAddressApplyConfiguration] +} + +// newIPAddresses returns a IPAddresses +func newIPAddresses(c *NetworkingV1Client) *iPAddresses { + return &iPAddresses{ + gentype.NewClientWithListAndApply[*networkingv1.IPAddress, *networkingv1.IPAddressList, *applyconfigurationsnetworkingv1.IPAddressApplyConfiguration]( + "ipaddresses", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *networkingv1.IPAddress { return &networkingv1.IPAddress{} }, + func() *networkingv1.IPAddressList { return &networkingv1.IPAddressList{} }, + gentype.PrefersProtobuf[*networkingv1.IPAddress](), + ), + } +} diff --git a/kubernetes/typed/networking/v1/networking_client.go b/kubernetes/typed/networking/v1/networking_client.go index 692b52f025..3411c053bb 100644 --- a/kubernetes/typed/networking/v1/networking_client.go +++ b/kubernetes/typed/networking/v1/networking_client.go @@ -28,9 +28,11 @@ import ( type NetworkingV1Interface interface { RESTClient() rest.Interface + IPAddressesGetter IngressesGetter IngressClassesGetter NetworkPoliciesGetter + ServiceCIDRsGetter } // NetworkingV1Client is used to interact with features provided by the networking.k8s.io group. @@ -38,6 +40,10 @@ type NetworkingV1Client struct { restClient rest.Interface } +func (c *NetworkingV1Client) IPAddresses() IPAddressInterface { + return newIPAddresses(c) +} + func (c *NetworkingV1Client) Ingresses(namespace string) IngressInterface { return newIngresses(c, namespace) } @@ -50,14 +56,16 @@ func (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInte return newNetworkPolicies(c, namespace) } +func (c *NetworkingV1Client) ServiceCIDRs() ServiceCIDRInterface { + return newServiceCIDRs(c) +} + // NewForConfig creates a new NetworkingV1Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*NetworkingV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -69,9 +77,7 @@ func NewForConfig(c *rest.Config) (*NetworkingV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -94,7 +100,7 @@ func New(c rest.Interface) *NetworkingV1Client { return &NetworkingV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := networkingv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -103,8 +109,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/networking/v1/servicecidr.go b/kubernetes/typed/networking/v1/servicecidr.go new file mode 100644 index 0000000000..b22f30c2ca --- /dev/null +++ b/kubernetes/typed/networking/v1/servicecidr.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + + networkingv1 "k8s.io/api/networking/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsnetworkingv1 "k8s.io/client-go/applyconfigurations/networking/v1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// ServiceCIDRsGetter has a method to return a ServiceCIDRInterface. +// A group's client should implement this interface. +type ServiceCIDRsGetter interface { + ServiceCIDRs() ServiceCIDRInterface +} + +// ServiceCIDRInterface has methods to work with ServiceCIDR resources. +type ServiceCIDRInterface interface { + Create(ctx context.Context, serviceCIDR *networkingv1.ServiceCIDR, opts metav1.CreateOptions) (*networkingv1.ServiceCIDR, error) + Update(ctx context.Context, serviceCIDR *networkingv1.ServiceCIDR, opts metav1.UpdateOptions) (*networkingv1.ServiceCIDR, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, serviceCIDR *networkingv1.ServiceCIDR, opts metav1.UpdateOptions) (*networkingv1.ServiceCIDR, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*networkingv1.ServiceCIDR, error) + List(ctx context.Context, opts metav1.ListOptions) (*networkingv1.ServiceCIDRList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *networkingv1.ServiceCIDR, err error) + Apply(ctx context.Context, serviceCIDR *applyconfigurationsnetworkingv1.ServiceCIDRApplyConfiguration, opts metav1.ApplyOptions) (result *networkingv1.ServiceCIDR, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, serviceCIDR *applyconfigurationsnetworkingv1.ServiceCIDRApplyConfiguration, opts metav1.ApplyOptions) (result *networkingv1.ServiceCIDR, err error) + ServiceCIDRExpansion +} + +// serviceCIDRs implements ServiceCIDRInterface +type serviceCIDRs struct { + *gentype.ClientWithListAndApply[*networkingv1.ServiceCIDR, *networkingv1.ServiceCIDRList, *applyconfigurationsnetworkingv1.ServiceCIDRApplyConfiguration] +} + +// newServiceCIDRs returns a ServiceCIDRs +func newServiceCIDRs(c *NetworkingV1Client) *serviceCIDRs { + return &serviceCIDRs{ + gentype.NewClientWithListAndApply[*networkingv1.ServiceCIDR, *networkingv1.ServiceCIDRList, *applyconfigurationsnetworkingv1.ServiceCIDRApplyConfiguration]( + "servicecidrs", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *networkingv1.ServiceCIDR { return &networkingv1.ServiceCIDR{} }, + func() *networkingv1.ServiceCIDRList { return &networkingv1.ServiceCIDRList{} }, + gentype.PrefersProtobuf[*networkingv1.ServiceCIDR](), + ), + } +} diff --git a/kubernetes/typed/networking/v1alpha1/networking_client.go b/kubernetes/typed/networking/v1alpha1/networking_client.go index 9e1b3064d8..c9d1dfd299 100644 --- a/kubernetes/typed/networking/v1alpha1/networking_client.go +++ b/kubernetes/typed/networking/v1alpha1/networking_client.go @@ -50,9 +50,7 @@ func (c *NetworkingV1alpha1Client) ServiceCIDRs() ServiceCIDRInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *NetworkingV1alpha1Client { return &NetworkingV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := networkingv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/networking/v1beta1/networking_client.go b/kubernetes/typed/networking/v1beta1/networking_client.go index cb4b0c601b..c30acf0a2b 100644 --- a/kubernetes/typed/networking/v1beta1/networking_client.go +++ b/kubernetes/typed/networking/v1beta1/networking_client.go @@ -60,9 +60,7 @@ func (c *NetworkingV1beta1Client) ServiceCIDRs() ServiceCIDRInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*NetworkingV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*NetworkingV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *NetworkingV1beta1Client { return &NetworkingV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := networkingv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/node/v1/node_client.go b/kubernetes/typed/node/v1/node_client.go index 3bde211713..b1b2f7c07b 100644 --- a/kubernetes/typed/node/v1/node_client.go +++ b/kubernetes/typed/node/v1/node_client.go @@ -45,9 +45,7 @@ func (c *NodeV1Client) RuntimeClasses() RuntimeClassInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*NodeV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*NodeV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *NodeV1Client { return &NodeV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := nodev1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/node/v1alpha1/node_client.go b/kubernetes/typed/node/v1alpha1/node_client.go index e47ef35485..e11398de46 100644 --- a/kubernetes/typed/node/v1alpha1/node_client.go +++ b/kubernetes/typed/node/v1alpha1/node_client.go @@ -45,9 +45,7 @@ func (c *NodeV1alpha1Client) RuntimeClasses() RuntimeClassInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*NodeV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*NodeV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *NodeV1alpha1Client { return &NodeV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := nodev1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/node/v1beta1/node_client.go b/kubernetes/typed/node/v1beta1/node_client.go index c7864a4796..bc9b1f6a29 100644 --- a/kubernetes/typed/node/v1beta1/node_client.go +++ b/kubernetes/typed/node/v1beta1/node_client.go @@ -45,9 +45,7 @@ func (c *NodeV1beta1Client) RuntimeClasses() RuntimeClassInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*NodeV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*NodeV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *NodeV1beta1Client { return &NodeV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := nodev1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/policy/v1/policy_client.go b/kubernetes/typed/policy/v1/policy_client.go index 8d84f460b0..fdbbc922b6 100644 --- a/kubernetes/typed/policy/v1/policy_client.go +++ b/kubernetes/typed/policy/v1/policy_client.go @@ -50,9 +50,7 @@ func (c *PolicyV1Client) PodDisruptionBudgets(namespace string) PodDisruptionBud // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*PolicyV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*PolicyV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*PolicyV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *PolicyV1Client { return &PolicyV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := policyv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/policy/v1beta1/policy_client.go b/kubernetes/typed/policy/v1beta1/policy_client.go index d8e78627e1..666e1b7f87 100644 --- a/kubernetes/typed/policy/v1beta1/policy_client.go +++ b/kubernetes/typed/policy/v1beta1/policy_client.go @@ -50,9 +50,7 @@ func (c *PolicyV1beta1Client) PodDisruptionBudgets(namespace string) PodDisrupti // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*PolicyV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -64,9 +62,7 @@ func NewForConfig(c *rest.Config) (*PolicyV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*PolicyV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -89,7 +85,7 @@ func New(c rest.Interface) *PolicyV1beta1Client { return &PolicyV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := policyv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -98,8 +94,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/rbac/v1/rbac_client.go b/kubernetes/typed/rbac/v1/rbac_client.go index c586ee638b..8eee912fc2 100644 --- a/kubernetes/typed/rbac/v1/rbac_client.go +++ b/kubernetes/typed/rbac/v1/rbac_client.go @@ -60,9 +60,7 @@ func (c *RbacV1Client) RoleBindings(namespace string) RoleBindingInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*RbacV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*RbacV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *RbacV1Client { return &RbacV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := rbacv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/rbac/v1alpha1/rbac_client.go b/kubernetes/typed/rbac/v1alpha1/rbac_client.go index df46fc3aaa..2e7dc98420 100644 --- a/kubernetes/typed/rbac/v1alpha1/rbac_client.go +++ b/kubernetes/typed/rbac/v1alpha1/rbac_client.go @@ -60,9 +60,7 @@ func (c *RbacV1alpha1Client) RoleBindings(namespace string) RoleBindingInterface // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*RbacV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*RbacV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *RbacV1alpha1Client { return &RbacV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := rbacv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/rbac/v1beta1/rbac_client.go b/kubernetes/typed/rbac/v1beta1/rbac_client.go index 5739bb289e..69f464147a 100644 --- a/kubernetes/typed/rbac/v1beta1/rbac_client.go +++ b/kubernetes/typed/rbac/v1beta1/rbac_client.go @@ -60,9 +60,7 @@ func (c *RbacV1beta1Client) RoleBindings(namespace string) RoleBindingInterface // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*RbacV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*RbacV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *RbacV1beta1Client { return &RbacV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := rbacv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/resource/v1alpha3/devicetaintrule.go b/kubernetes/typed/resource/v1alpha3/devicetaintrule.go new file mode 100644 index 0000000000..77e26b6e3a --- /dev/null +++ b/kubernetes/typed/resource/v1alpha3/devicetaintrule.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + context "context" + + resourcev1alpha3 "k8s.io/api/resource/v1alpha3" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsresourcev1alpha3 "k8s.io/client-go/applyconfigurations/resource/v1alpha3" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// DeviceTaintRulesGetter has a method to return a DeviceTaintRuleInterface. +// A group's client should implement this interface. +type DeviceTaintRulesGetter interface { + DeviceTaintRules() DeviceTaintRuleInterface +} + +// DeviceTaintRuleInterface has methods to work with DeviceTaintRule resources. +type DeviceTaintRuleInterface interface { + Create(ctx context.Context, deviceTaintRule *resourcev1alpha3.DeviceTaintRule, opts v1.CreateOptions) (*resourcev1alpha3.DeviceTaintRule, error) + Update(ctx context.Context, deviceTaintRule *resourcev1alpha3.DeviceTaintRule, opts v1.UpdateOptions) (*resourcev1alpha3.DeviceTaintRule, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*resourcev1alpha3.DeviceTaintRule, error) + List(ctx context.Context, opts v1.ListOptions) (*resourcev1alpha3.DeviceTaintRuleList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *resourcev1alpha3.DeviceTaintRule, err error) + Apply(ctx context.Context, deviceTaintRule *applyconfigurationsresourcev1alpha3.DeviceTaintRuleApplyConfiguration, opts v1.ApplyOptions) (result *resourcev1alpha3.DeviceTaintRule, err error) + DeviceTaintRuleExpansion +} + +// deviceTaintRules implements DeviceTaintRuleInterface +type deviceTaintRules struct { + *gentype.ClientWithListAndApply[*resourcev1alpha3.DeviceTaintRule, *resourcev1alpha3.DeviceTaintRuleList, *applyconfigurationsresourcev1alpha3.DeviceTaintRuleApplyConfiguration] +} + +// newDeviceTaintRules returns a DeviceTaintRules +func newDeviceTaintRules(c *ResourceV1alpha3Client) *deviceTaintRules { + return &deviceTaintRules{ + gentype.NewClientWithListAndApply[*resourcev1alpha3.DeviceTaintRule, *resourcev1alpha3.DeviceTaintRuleList, *applyconfigurationsresourcev1alpha3.DeviceTaintRuleApplyConfiguration]( + "devicetaintrules", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *resourcev1alpha3.DeviceTaintRule { return &resourcev1alpha3.DeviceTaintRule{} }, + func() *resourcev1alpha3.DeviceTaintRuleList { return &resourcev1alpha3.DeviceTaintRuleList{} }, + gentype.PrefersProtobuf[*resourcev1alpha3.DeviceTaintRule](), + ), + } +} diff --git a/kubernetes/typed/resource/v1alpha3/fake/fake_devicetaintrule.go b/kubernetes/typed/resource/v1alpha3/fake/fake_devicetaintrule.go new file mode 100644 index 0000000000..62a55561f3 --- /dev/null +++ b/kubernetes/typed/resource/v1alpha3/fake/fake_devicetaintrule.go @@ -0,0 +1,53 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1alpha3 "k8s.io/api/resource/v1alpha3" + resourcev1alpha3 "k8s.io/client-go/applyconfigurations/resource/v1alpha3" + gentype "k8s.io/client-go/gentype" + typedresourcev1alpha3 "k8s.io/client-go/kubernetes/typed/resource/v1alpha3" +) + +// fakeDeviceTaintRules implements DeviceTaintRuleInterface +type fakeDeviceTaintRules struct { + *gentype.FakeClientWithListAndApply[*v1alpha3.DeviceTaintRule, *v1alpha3.DeviceTaintRuleList, *resourcev1alpha3.DeviceTaintRuleApplyConfiguration] + Fake *FakeResourceV1alpha3 +} + +func newFakeDeviceTaintRules(fake *FakeResourceV1alpha3) typedresourcev1alpha3.DeviceTaintRuleInterface { + return &fakeDeviceTaintRules{ + gentype.NewFakeClientWithListAndApply[*v1alpha3.DeviceTaintRule, *v1alpha3.DeviceTaintRuleList, *resourcev1alpha3.DeviceTaintRuleApplyConfiguration]( + fake.Fake, + "", + v1alpha3.SchemeGroupVersion.WithResource("devicetaintrules"), + v1alpha3.SchemeGroupVersion.WithKind("DeviceTaintRule"), + func() *v1alpha3.DeviceTaintRule { return &v1alpha3.DeviceTaintRule{} }, + func() *v1alpha3.DeviceTaintRuleList { return &v1alpha3.DeviceTaintRuleList{} }, + func(dst, src *v1alpha3.DeviceTaintRuleList) { dst.ListMeta = src.ListMeta }, + func(list *v1alpha3.DeviceTaintRuleList) []*v1alpha3.DeviceTaintRule { + return gentype.ToPointerSlice(list.Items) + }, + func(list *v1alpha3.DeviceTaintRuleList, items []*v1alpha3.DeviceTaintRule) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/kubernetes/typed/resource/v1alpha3/fake/fake_resource_client.go b/kubernetes/typed/resource/v1alpha3/fake/fake_resource_client.go index 83dfdb2b93..d6d872d85d 100644 --- a/kubernetes/typed/resource/v1alpha3/fake/fake_resource_client.go +++ b/kubernetes/typed/resource/v1alpha3/fake/fake_resource_client.go @@ -32,6 +32,10 @@ func (c *FakeResourceV1alpha3) DeviceClasses() v1alpha3.DeviceClassInterface { return newFakeDeviceClasses(c) } +func (c *FakeResourceV1alpha3) DeviceTaintRules() v1alpha3.DeviceTaintRuleInterface { + return newFakeDeviceTaintRules(c) +} + func (c *FakeResourceV1alpha3) ResourceClaims(namespace string) v1alpha3.ResourceClaimInterface { return newFakeResourceClaims(c, namespace) } diff --git a/kubernetes/typed/resource/v1alpha3/generated_expansion.go b/kubernetes/typed/resource/v1alpha3/generated_expansion.go index cd8862ea84..6a7ffeda81 100644 --- a/kubernetes/typed/resource/v1alpha3/generated_expansion.go +++ b/kubernetes/typed/resource/v1alpha3/generated_expansion.go @@ -20,6 +20,8 @@ package v1alpha3 type DeviceClassExpansion interface{} +type DeviceTaintRuleExpansion interface{} + type ResourceClaimExpansion interface{} type ResourceClaimTemplateExpansion interface{} diff --git a/kubernetes/typed/resource/v1alpha3/resource_client.go b/kubernetes/typed/resource/v1alpha3/resource_client.go index acc9b97c22..7e16ac1540 100644 --- a/kubernetes/typed/resource/v1alpha3/resource_client.go +++ b/kubernetes/typed/resource/v1alpha3/resource_client.go @@ -29,6 +29,7 @@ import ( type ResourceV1alpha3Interface interface { RESTClient() rest.Interface DeviceClassesGetter + DeviceTaintRulesGetter ResourceClaimsGetter ResourceClaimTemplatesGetter ResourceSlicesGetter @@ -43,6 +44,10 @@ func (c *ResourceV1alpha3Client) DeviceClasses() DeviceClassInterface { return newDeviceClasses(c) } +func (c *ResourceV1alpha3Client) DeviceTaintRules() DeviceTaintRuleInterface { + return newDeviceTaintRules(c) +} + func (c *ResourceV1alpha3Client) ResourceClaims(namespace string) ResourceClaimInterface { return newResourceClaims(c, namespace) } @@ -60,9 +65,7 @@ func (c *ResourceV1alpha3Client) ResourceSlices() ResourceSliceInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*ResourceV1alpha3Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +77,7 @@ func NewForConfig(c *rest.Config) (*ResourceV1alpha3Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ResourceV1alpha3Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +100,7 @@ func New(c rest.Interface) *ResourceV1alpha3Client { return &ResourceV1alpha3Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := resourcev1alpha3.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +109,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/resource/v1beta1/resource_client.go b/kubernetes/typed/resource/v1beta1/resource_client.go index c6a3b28369..789d34a91f 100644 --- a/kubernetes/typed/resource/v1beta1/resource_client.go +++ b/kubernetes/typed/resource/v1beta1/resource_client.go @@ -60,9 +60,7 @@ func (c *ResourceV1beta1Client) ResourceSlices() ResourceSliceInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*ResourceV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -74,9 +72,7 @@ func NewForConfig(c *rest.Config) (*ResourceV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ResourceV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -99,7 +95,7 @@ func New(c rest.Interface) *ResourceV1beta1Client { return &ResourceV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := resourcev1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -108,8 +104,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/resource/v1beta2/deviceclass.go b/kubernetes/typed/resource/v1beta2/deviceclass.go new file mode 100644 index 0000000000..0943193f67 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/deviceclass.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + + resourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsresourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// DeviceClassesGetter has a method to return a DeviceClassInterface. +// A group's client should implement this interface. +type DeviceClassesGetter interface { + DeviceClasses() DeviceClassInterface +} + +// DeviceClassInterface has methods to work with DeviceClass resources. +type DeviceClassInterface interface { + Create(ctx context.Context, deviceClass *resourcev1beta2.DeviceClass, opts v1.CreateOptions) (*resourcev1beta2.DeviceClass, error) + Update(ctx context.Context, deviceClass *resourcev1beta2.DeviceClass, opts v1.UpdateOptions) (*resourcev1beta2.DeviceClass, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*resourcev1beta2.DeviceClass, error) + List(ctx context.Context, opts v1.ListOptions) (*resourcev1beta2.DeviceClassList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *resourcev1beta2.DeviceClass, err error) + Apply(ctx context.Context, deviceClass *applyconfigurationsresourcev1beta2.DeviceClassApplyConfiguration, opts v1.ApplyOptions) (result *resourcev1beta2.DeviceClass, err error) + DeviceClassExpansion +} + +// deviceClasses implements DeviceClassInterface +type deviceClasses struct { + *gentype.ClientWithListAndApply[*resourcev1beta2.DeviceClass, *resourcev1beta2.DeviceClassList, *applyconfigurationsresourcev1beta2.DeviceClassApplyConfiguration] +} + +// newDeviceClasses returns a DeviceClasses +func newDeviceClasses(c *ResourceV1beta2Client) *deviceClasses { + return &deviceClasses{ + gentype.NewClientWithListAndApply[*resourcev1beta2.DeviceClass, *resourcev1beta2.DeviceClassList, *applyconfigurationsresourcev1beta2.DeviceClassApplyConfiguration]( + "deviceclasses", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *resourcev1beta2.DeviceClass { return &resourcev1beta2.DeviceClass{} }, + func() *resourcev1beta2.DeviceClassList { return &resourcev1beta2.DeviceClassList{} }, + gentype.PrefersProtobuf[*resourcev1beta2.DeviceClass](), + ), + } +} diff --git a/kubernetes/typed/resource/v1beta2/doc.go b/kubernetes/typed/resource/v1beta2/doc.go new file mode 100644 index 0000000000..56518ef7f2 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/doc.go @@ -0,0 +1,20 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v1beta2 diff --git a/kubernetes/typed/resource/v1beta2/fake/doc.go b/kubernetes/typed/resource/v1beta2/fake/doc.go new file mode 100644 index 0000000000..16f4439906 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/fake/doc.go @@ -0,0 +1,20 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// Package fake has the automatically generated clients. +package fake diff --git a/kubernetes/typed/resource/v1beta2/fake/fake_deviceclass.go b/kubernetes/typed/resource/v1beta2/fake/fake_deviceclass.go new file mode 100644 index 0000000000..540f278ca1 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/fake/fake_deviceclass.go @@ -0,0 +1,51 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta2 "k8s.io/api/resource/v1beta2" + resourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + typedresourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" +) + +// fakeDeviceClasses implements DeviceClassInterface +type fakeDeviceClasses struct { + *gentype.FakeClientWithListAndApply[*v1beta2.DeviceClass, *v1beta2.DeviceClassList, *resourcev1beta2.DeviceClassApplyConfiguration] + Fake *FakeResourceV1beta2 +} + +func newFakeDeviceClasses(fake *FakeResourceV1beta2) typedresourcev1beta2.DeviceClassInterface { + return &fakeDeviceClasses{ + gentype.NewFakeClientWithListAndApply[*v1beta2.DeviceClass, *v1beta2.DeviceClassList, *resourcev1beta2.DeviceClassApplyConfiguration]( + fake.Fake, + "", + v1beta2.SchemeGroupVersion.WithResource("deviceclasses"), + v1beta2.SchemeGroupVersion.WithKind("DeviceClass"), + func() *v1beta2.DeviceClass { return &v1beta2.DeviceClass{} }, + func() *v1beta2.DeviceClassList { return &v1beta2.DeviceClassList{} }, + func(dst, src *v1beta2.DeviceClassList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta2.DeviceClassList) []*v1beta2.DeviceClass { return gentype.ToPointerSlice(list.Items) }, + func(list *v1beta2.DeviceClassList, items []*v1beta2.DeviceClass) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/kubernetes/typed/resource/v1beta2/fake/fake_resource_client.go b/kubernetes/typed/resource/v1beta2/fake/fake_resource_client.go new file mode 100644 index 0000000000..10c5c0e337 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/fake/fake_resource_client.go @@ -0,0 +1,52 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" + rest "k8s.io/client-go/rest" + testing "k8s.io/client-go/testing" +) + +type FakeResourceV1beta2 struct { + *testing.Fake +} + +func (c *FakeResourceV1beta2) DeviceClasses() v1beta2.DeviceClassInterface { + return newFakeDeviceClasses(c) +} + +func (c *FakeResourceV1beta2) ResourceClaims(namespace string) v1beta2.ResourceClaimInterface { + return newFakeResourceClaims(c, namespace) +} + +func (c *FakeResourceV1beta2) ResourceClaimTemplates(namespace string) v1beta2.ResourceClaimTemplateInterface { + return newFakeResourceClaimTemplates(c, namespace) +} + +func (c *FakeResourceV1beta2) ResourceSlices() v1beta2.ResourceSliceInterface { + return newFakeResourceSlices(c) +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeResourceV1beta2) RESTClient() rest.Interface { + var ret *rest.RESTClient + return ret +} diff --git a/kubernetes/typed/resource/v1beta2/fake/fake_resourceclaim.go b/kubernetes/typed/resource/v1beta2/fake/fake_resourceclaim.go new file mode 100644 index 0000000000..f093917621 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/fake/fake_resourceclaim.go @@ -0,0 +1,53 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta2 "k8s.io/api/resource/v1beta2" + resourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + typedresourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" +) + +// fakeResourceClaims implements ResourceClaimInterface +type fakeResourceClaims struct { + *gentype.FakeClientWithListAndApply[*v1beta2.ResourceClaim, *v1beta2.ResourceClaimList, *resourcev1beta2.ResourceClaimApplyConfiguration] + Fake *FakeResourceV1beta2 +} + +func newFakeResourceClaims(fake *FakeResourceV1beta2, namespace string) typedresourcev1beta2.ResourceClaimInterface { + return &fakeResourceClaims{ + gentype.NewFakeClientWithListAndApply[*v1beta2.ResourceClaim, *v1beta2.ResourceClaimList, *resourcev1beta2.ResourceClaimApplyConfiguration]( + fake.Fake, + namespace, + v1beta2.SchemeGroupVersion.WithResource("resourceclaims"), + v1beta2.SchemeGroupVersion.WithKind("ResourceClaim"), + func() *v1beta2.ResourceClaim { return &v1beta2.ResourceClaim{} }, + func() *v1beta2.ResourceClaimList { return &v1beta2.ResourceClaimList{} }, + func(dst, src *v1beta2.ResourceClaimList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta2.ResourceClaimList) []*v1beta2.ResourceClaim { + return gentype.ToPointerSlice(list.Items) + }, + func(list *v1beta2.ResourceClaimList, items []*v1beta2.ResourceClaim) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/kubernetes/typed/resource/v1beta2/fake/fake_resourceclaimtemplate.go b/kubernetes/typed/resource/v1beta2/fake/fake_resourceclaimtemplate.go new file mode 100644 index 0000000000..5c4bb111d7 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/fake/fake_resourceclaimtemplate.go @@ -0,0 +1,53 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta2 "k8s.io/api/resource/v1beta2" + resourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + typedresourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" +) + +// fakeResourceClaimTemplates implements ResourceClaimTemplateInterface +type fakeResourceClaimTemplates struct { + *gentype.FakeClientWithListAndApply[*v1beta2.ResourceClaimTemplate, *v1beta2.ResourceClaimTemplateList, *resourcev1beta2.ResourceClaimTemplateApplyConfiguration] + Fake *FakeResourceV1beta2 +} + +func newFakeResourceClaimTemplates(fake *FakeResourceV1beta2, namespace string) typedresourcev1beta2.ResourceClaimTemplateInterface { + return &fakeResourceClaimTemplates{ + gentype.NewFakeClientWithListAndApply[*v1beta2.ResourceClaimTemplate, *v1beta2.ResourceClaimTemplateList, *resourcev1beta2.ResourceClaimTemplateApplyConfiguration]( + fake.Fake, + namespace, + v1beta2.SchemeGroupVersion.WithResource("resourceclaimtemplates"), + v1beta2.SchemeGroupVersion.WithKind("ResourceClaimTemplate"), + func() *v1beta2.ResourceClaimTemplate { return &v1beta2.ResourceClaimTemplate{} }, + func() *v1beta2.ResourceClaimTemplateList { return &v1beta2.ResourceClaimTemplateList{} }, + func(dst, src *v1beta2.ResourceClaimTemplateList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta2.ResourceClaimTemplateList) []*v1beta2.ResourceClaimTemplate { + return gentype.ToPointerSlice(list.Items) + }, + func(list *v1beta2.ResourceClaimTemplateList, items []*v1beta2.ResourceClaimTemplate) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/kubernetes/typed/resource/v1beta2/fake/fake_resourceslice.go b/kubernetes/typed/resource/v1beta2/fake/fake_resourceslice.go new file mode 100644 index 0000000000..a53b6f81da --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/fake/fake_resourceslice.go @@ -0,0 +1,53 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta2 "k8s.io/api/resource/v1beta2" + resourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + typedresourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" +) + +// fakeResourceSlices implements ResourceSliceInterface +type fakeResourceSlices struct { + *gentype.FakeClientWithListAndApply[*v1beta2.ResourceSlice, *v1beta2.ResourceSliceList, *resourcev1beta2.ResourceSliceApplyConfiguration] + Fake *FakeResourceV1beta2 +} + +func newFakeResourceSlices(fake *FakeResourceV1beta2) typedresourcev1beta2.ResourceSliceInterface { + return &fakeResourceSlices{ + gentype.NewFakeClientWithListAndApply[*v1beta2.ResourceSlice, *v1beta2.ResourceSliceList, *resourcev1beta2.ResourceSliceApplyConfiguration]( + fake.Fake, + "", + v1beta2.SchemeGroupVersion.WithResource("resourceslices"), + v1beta2.SchemeGroupVersion.WithKind("ResourceSlice"), + func() *v1beta2.ResourceSlice { return &v1beta2.ResourceSlice{} }, + func() *v1beta2.ResourceSliceList { return &v1beta2.ResourceSliceList{} }, + func(dst, src *v1beta2.ResourceSliceList) { dst.ListMeta = src.ListMeta }, + func(list *v1beta2.ResourceSliceList) []*v1beta2.ResourceSlice { + return gentype.ToPointerSlice(list.Items) + }, + func(list *v1beta2.ResourceSliceList, items []*v1beta2.ResourceSlice) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/kubernetes/typed/resource/v1beta2/generated_expansion.go b/kubernetes/typed/resource/v1beta2/generated_expansion.go new file mode 100644 index 0000000000..230ab8ccd3 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/generated_expansion.go @@ -0,0 +1,27 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +type DeviceClassExpansion interface{} + +type ResourceClaimExpansion interface{} + +type ResourceClaimTemplateExpansion interface{} + +type ResourceSliceExpansion interface{} diff --git a/kubernetes/typed/resource/v1beta2/resource_client.go b/kubernetes/typed/resource/v1beta2/resource_client.go new file mode 100644 index 0000000000..aadde5be95 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/resource_client.go @@ -0,0 +1,116 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +import ( + http "net/http" + + resourcev1beta2 "k8s.io/api/resource/v1beta2" + scheme "k8s.io/client-go/kubernetes/scheme" + rest "k8s.io/client-go/rest" +) + +type ResourceV1beta2Interface interface { + RESTClient() rest.Interface + DeviceClassesGetter + ResourceClaimsGetter + ResourceClaimTemplatesGetter + ResourceSlicesGetter +} + +// ResourceV1beta2Client is used to interact with features provided by the resource.k8s.io group. +type ResourceV1beta2Client struct { + restClient rest.Interface +} + +func (c *ResourceV1beta2Client) DeviceClasses() DeviceClassInterface { + return newDeviceClasses(c) +} + +func (c *ResourceV1beta2Client) ResourceClaims(namespace string) ResourceClaimInterface { + return newResourceClaims(c, namespace) +} + +func (c *ResourceV1beta2Client) ResourceClaimTemplates(namespace string) ResourceClaimTemplateInterface { + return newResourceClaimTemplates(c, namespace) +} + +func (c *ResourceV1beta2Client) ResourceSlices() ResourceSliceInterface { + return newResourceSlices(c) +} + +// NewForConfig creates a new ResourceV1beta2Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). +func NewForConfig(c *rest.Config) (*ResourceV1beta2Client, error) { + config := *c + setConfigDefaults(&config) + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new ResourceV1beta2Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ResourceV1beta2Client, error) { + config := *c + setConfigDefaults(&config) + client, err := rest.RESTClientForConfigAndClient(&config, h) + if err != nil { + return nil, err + } + return &ResourceV1beta2Client{client}, nil +} + +// NewForConfigOrDie creates a new ResourceV1beta2Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *ResourceV1beta2Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new ResourceV1beta2Client for the given RESTClient. +func New(c rest.Interface) *ResourceV1beta2Client { + return &ResourceV1beta2Client{c} +} + +func setConfigDefaults(config *rest.Config) { + gv := resourcev1beta2.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *ResourceV1beta2Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/kubernetes/typed/resource/v1beta2/resourceclaim.go b/kubernetes/typed/resource/v1beta2/resourceclaim.go new file mode 100644 index 0000000000..47efefa9cc --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/resourceclaim.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + + resourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsresourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// ResourceClaimsGetter has a method to return a ResourceClaimInterface. +// A group's client should implement this interface. +type ResourceClaimsGetter interface { + ResourceClaims(namespace string) ResourceClaimInterface +} + +// ResourceClaimInterface has methods to work with ResourceClaim resources. +type ResourceClaimInterface interface { + Create(ctx context.Context, resourceClaim *resourcev1beta2.ResourceClaim, opts v1.CreateOptions) (*resourcev1beta2.ResourceClaim, error) + Update(ctx context.Context, resourceClaim *resourcev1beta2.ResourceClaim, opts v1.UpdateOptions) (*resourcev1beta2.ResourceClaim, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, resourceClaim *resourcev1beta2.ResourceClaim, opts v1.UpdateOptions) (*resourcev1beta2.ResourceClaim, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*resourcev1beta2.ResourceClaim, error) + List(ctx context.Context, opts v1.ListOptions) (*resourcev1beta2.ResourceClaimList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *resourcev1beta2.ResourceClaim, err error) + Apply(ctx context.Context, resourceClaim *applyconfigurationsresourcev1beta2.ResourceClaimApplyConfiguration, opts v1.ApplyOptions) (result *resourcev1beta2.ResourceClaim, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, resourceClaim *applyconfigurationsresourcev1beta2.ResourceClaimApplyConfiguration, opts v1.ApplyOptions) (result *resourcev1beta2.ResourceClaim, err error) + ResourceClaimExpansion +} + +// resourceClaims implements ResourceClaimInterface +type resourceClaims struct { + *gentype.ClientWithListAndApply[*resourcev1beta2.ResourceClaim, *resourcev1beta2.ResourceClaimList, *applyconfigurationsresourcev1beta2.ResourceClaimApplyConfiguration] +} + +// newResourceClaims returns a ResourceClaims +func newResourceClaims(c *ResourceV1beta2Client, namespace string) *resourceClaims { + return &resourceClaims{ + gentype.NewClientWithListAndApply[*resourcev1beta2.ResourceClaim, *resourcev1beta2.ResourceClaimList, *applyconfigurationsresourcev1beta2.ResourceClaimApplyConfiguration]( + "resourceclaims", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *resourcev1beta2.ResourceClaim { return &resourcev1beta2.ResourceClaim{} }, + func() *resourcev1beta2.ResourceClaimList { return &resourcev1beta2.ResourceClaimList{} }, + gentype.PrefersProtobuf[*resourcev1beta2.ResourceClaim](), + ), + } +} diff --git a/kubernetes/typed/resource/v1beta2/resourceclaimtemplate.go b/kubernetes/typed/resource/v1beta2/resourceclaimtemplate.go new file mode 100644 index 0000000000..2140a45373 --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/resourceclaimtemplate.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + + resourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsresourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// ResourceClaimTemplatesGetter has a method to return a ResourceClaimTemplateInterface. +// A group's client should implement this interface. +type ResourceClaimTemplatesGetter interface { + ResourceClaimTemplates(namespace string) ResourceClaimTemplateInterface +} + +// ResourceClaimTemplateInterface has methods to work with ResourceClaimTemplate resources. +type ResourceClaimTemplateInterface interface { + Create(ctx context.Context, resourceClaimTemplate *resourcev1beta2.ResourceClaimTemplate, opts v1.CreateOptions) (*resourcev1beta2.ResourceClaimTemplate, error) + Update(ctx context.Context, resourceClaimTemplate *resourcev1beta2.ResourceClaimTemplate, opts v1.UpdateOptions) (*resourcev1beta2.ResourceClaimTemplate, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*resourcev1beta2.ResourceClaimTemplate, error) + List(ctx context.Context, opts v1.ListOptions) (*resourcev1beta2.ResourceClaimTemplateList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *resourcev1beta2.ResourceClaimTemplate, err error) + Apply(ctx context.Context, resourceClaimTemplate *applyconfigurationsresourcev1beta2.ResourceClaimTemplateApplyConfiguration, opts v1.ApplyOptions) (result *resourcev1beta2.ResourceClaimTemplate, err error) + ResourceClaimTemplateExpansion +} + +// resourceClaimTemplates implements ResourceClaimTemplateInterface +type resourceClaimTemplates struct { + *gentype.ClientWithListAndApply[*resourcev1beta2.ResourceClaimTemplate, *resourcev1beta2.ResourceClaimTemplateList, *applyconfigurationsresourcev1beta2.ResourceClaimTemplateApplyConfiguration] +} + +// newResourceClaimTemplates returns a ResourceClaimTemplates +func newResourceClaimTemplates(c *ResourceV1beta2Client, namespace string) *resourceClaimTemplates { + return &resourceClaimTemplates{ + gentype.NewClientWithListAndApply[*resourcev1beta2.ResourceClaimTemplate, *resourcev1beta2.ResourceClaimTemplateList, *applyconfigurationsresourcev1beta2.ResourceClaimTemplateApplyConfiguration]( + "resourceclaimtemplates", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *resourcev1beta2.ResourceClaimTemplate { return &resourcev1beta2.ResourceClaimTemplate{} }, + func() *resourcev1beta2.ResourceClaimTemplateList { return &resourcev1beta2.ResourceClaimTemplateList{} }, + gentype.PrefersProtobuf[*resourcev1beta2.ResourceClaimTemplate](), + ), + } +} diff --git a/kubernetes/typed/resource/v1beta2/resourceslice.go b/kubernetes/typed/resource/v1beta2/resourceslice.go new file mode 100644 index 0000000000..c4507803fc --- /dev/null +++ b/kubernetes/typed/resource/v1beta2/resourceslice.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +import ( + context "context" + + resourcev1beta2 "k8s.io/api/resource/v1beta2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsresourcev1beta2 "k8s.io/client-go/applyconfigurations/resource/v1beta2" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// ResourceSlicesGetter has a method to return a ResourceSliceInterface. +// A group's client should implement this interface. +type ResourceSlicesGetter interface { + ResourceSlices() ResourceSliceInterface +} + +// ResourceSliceInterface has methods to work with ResourceSlice resources. +type ResourceSliceInterface interface { + Create(ctx context.Context, resourceSlice *resourcev1beta2.ResourceSlice, opts v1.CreateOptions) (*resourcev1beta2.ResourceSlice, error) + Update(ctx context.Context, resourceSlice *resourcev1beta2.ResourceSlice, opts v1.UpdateOptions) (*resourcev1beta2.ResourceSlice, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*resourcev1beta2.ResourceSlice, error) + List(ctx context.Context, opts v1.ListOptions) (*resourcev1beta2.ResourceSliceList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *resourcev1beta2.ResourceSlice, err error) + Apply(ctx context.Context, resourceSlice *applyconfigurationsresourcev1beta2.ResourceSliceApplyConfiguration, opts v1.ApplyOptions) (result *resourcev1beta2.ResourceSlice, err error) + ResourceSliceExpansion +} + +// resourceSlices implements ResourceSliceInterface +type resourceSlices struct { + *gentype.ClientWithListAndApply[*resourcev1beta2.ResourceSlice, *resourcev1beta2.ResourceSliceList, *applyconfigurationsresourcev1beta2.ResourceSliceApplyConfiguration] +} + +// newResourceSlices returns a ResourceSlices +func newResourceSlices(c *ResourceV1beta2Client) *resourceSlices { + return &resourceSlices{ + gentype.NewClientWithListAndApply[*resourcev1beta2.ResourceSlice, *resourcev1beta2.ResourceSliceList, *applyconfigurationsresourcev1beta2.ResourceSliceApplyConfiguration]( + "resourceslices", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *resourcev1beta2.ResourceSlice { return &resourcev1beta2.ResourceSlice{} }, + func() *resourcev1beta2.ResourceSliceList { return &resourcev1beta2.ResourceSliceList{} }, + gentype.PrefersProtobuf[*resourcev1beta2.ResourceSlice](), + ), + } +} diff --git a/kubernetes/typed/scheduling/v1/scheduling_client.go b/kubernetes/typed/scheduling/v1/scheduling_client.go index bbb46a9def..85ea7722e3 100644 --- a/kubernetes/typed/scheduling/v1/scheduling_client.go +++ b/kubernetes/typed/scheduling/v1/scheduling_client.go @@ -45,9 +45,7 @@ func (c *SchedulingV1Client) PriorityClasses() PriorityClassInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*SchedulingV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*SchedulingV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *SchedulingV1Client { return &SchedulingV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := schedulingv1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go b/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go index 056ab855ed..b17b182f13 100644 --- a/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go +++ b/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go @@ -45,9 +45,7 @@ func (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *SchedulingV1alpha1Client { return &SchedulingV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := schedulingv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/scheduling/v1beta1/scheduling_client.go b/kubernetes/typed/scheduling/v1beta1/scheduling_client.go index 9e383398ea..0b2aa0e1ac 100644 --- a/kubernetes/typed/scheduling/v1beta1/scheduling_client.go +++ b/kubernetes/typed/scheduling/v1beta1/scheduling_client.go @@ -45,9 +45,7 @@ func (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *SchedulingV1beta1Client { return &SchedulingV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := schedulingv1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/storage/v1/storage_client.go b/kubernetes/typed/storage/v1/storage_client.go index 70aaff169f..6ed5521201 100644 --- a/kubernetes/typed/storage/v1/storage_client.go +++ b/kubernetes/typed/storage/v1/storage_client.go @@ -65,9 +65,7 @@ func (c *StorageV1Client) VolumeAttachments() VolumeAttachmentInterface { // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*StorageV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -79,9 +77,7 @@ func NewForConfig(c *rest.Config) (*StorageV1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -104,7 +100,7 @@ func New(c rest.Interface) *StorageV1Client { return &StorageV1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := storagev1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -113,8 +109,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/storage/v1alpha1/storage_client.go b/kubernetes/typed/storage/v1alpha1/storage_client.go index 17b680d199..44e1e1a23c 100644 --- a/kubernetes/typed/storage/v1alpha1/storage_client.go +++ b/kubernetes/typed/storage/v1alpha1/storage_client.go @@ -55,9 +55,7 @@ func (c *StorageV1alpha1Client) VolumeAttributesClasses() VolumeAttributesClassI // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*StorageV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -69,9 +67,7 @@ func NewForConfig(c *rest.Config) (*StorageV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -94,7 +90,7 @@ func New(c rest.Interface) *StorageV1alpha1Client { return &StorageV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := storagev1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -103,8 +99,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/storage/v1beta1/storage_client.go b/kubernetes/typed/storage/v1beta1/storage_client.go index 63b1d42a33..02805e1b98 100644 --- a/kubernetes/typed/storage/v1beta1/storage_client.go +++ b/kubernetes/typed/storage/v1beta1/storage_client.go @@ -70,9 +70,7 @@ func (c *StorageV1beta1Client) VolumeAttributesClasses() VolumeAttributesClassIn // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*StorageV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -84,9 +82,7 @@ func NewForConfig(c *rest.Config) (*StorageV1beta1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1beta1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -109,7 +105,7 @@ func New(c rest.Interface) *StorageV1beta1Client { return &StorageV1beta1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := storagev1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -118,8 +114,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/kubernetes/typed/storagemigration/v1alpha1/storagemigration_client.go b/kubernetes/typed/storagemigration/v1alpha1/storagemigration_client.go index dcd5a4bf8c..f7b5f5a1e2 100644 --- a/kubernetes/typed/storagemigration/v1alpha1/storagemigration_client.go +++ b/kubernetes/typed/storagemigration/v1alpha1/storagemigration_client.go @@ -45,9 +45,7 @@ func (c *StoragemigrationV1alpha1Client) StorageVersionMigrations() StorageVersi // where httpClient was generated with rest.HTTPClientFor(c). func NewForConfig(c *rest.Config) (*StoragemigrationV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) if err != nil { return nil, err @@ -59,9 +57,7 @@ func NewForConfig(c *rest.Config) (*StoragemigrationV1alpha1Client, error) { // Note the http client provided takes precedence over the configured transport values. func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StoragemigrationV1alpha1Client, error) { config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } + setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err @@ -84,7 +80,7 @@ func New(c rest.Interface) *StoragemigrationV1alpha1Client { return &StoragemigrationV1alpha1Client{c} } -func setConfigDefaults(config *rest.Config) error { +func setConfigDefaults(config *rest.Config) { gv := storagemigrationv1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" @@ -93,8 +89,6 @@ func setConfigDefaults(config *rest.Config) error { if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } - - return nil } // RESTClient returns a RESTClient that is used to communicate diff --git a/listers/certificates/v1beta1/clustertrustbundle.go b/listers/certificates/v1beta1/clustertrustbundle.go new file mode 100644 index 0000000000..dfda2498b0 --- /dev/null +++ b/listers/certificates/v1beta1/clustertrustbundle.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta1 + +import ( + certificatesv1beta1 "k8s.io/api/certificates/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// ClusterTrustBundleLister helps list ClusterTrustBundles. +// All objects returned here must be treated as read-only. +type ClusterTrustBundleLister interface { + // List lists all ClusterTrustBundles in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*certificatesv1beta1.ClusterTrustBundle, err error) + // Get retrieves the ClusterTrustBundle from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*certificatesv1beta1.ClusterTrustBundle, error) + ClusterTrustBundleListerExpansion +} + +// clusterTrustBundleLister implements the ClusterTrustBundleLister interface. +type clusterTrustBundleLister struct { + listers.ResourceIndexer[*certificatesv1beta1.ClusterTrustBundle] +} + +// NewClusterTrustBundleLister returns a new ClusterTrustBundleLister. +func NewClusterTrustBundleLister(indexer cache.Indexer) ClusterTrustBundleLister { + return &clusterTrustBundleLister{listers.New[*certificatesv1beta1.ClusterTrustBundle](indexer, certificatesv1beta1.Resource("clustertrustbundle"))} +} diff --git a/listers/certificates/v1beta1/expansion_generated.go b/listers/certificates/v1beta1/expansion_generated.go index 68f993cd6e..12a2554df0 100644 --- a/listers/certificates/v1beta1/expansion_generated.go +++ b/listers/certificates/v1beta1/expansion_generated.go @@ -21,3 +21,7 @@ package v1beta1 // CertificateSigningRequestListerExpansion allows custom methods to be added to // CertificateSigningRequestLister. type CertificateSigningRequestListerExpansion interface{} + +// ClusterTrustBundleListerExpansion allows custom methods to be added to +// ClusterTrustBundleLister. +type ClusterTrustBundleListerExpansion interface{} diff --git a/listers/coordination/v1beta1/expansion_generated.go b/listers/coordination/v1beta1/expansion_generated.go index dddc53107b..d61788a322 100644 --- a/listers/coordination/v1beta1/expansion_generated.go +++ b/listers/coordination/v1beta1/expansion_generated.go @@ -25,3 +25,11 @@ type LeaseListerExpansion interface{} // LeaseNamespaceListerExpansion allows custom methods to be added to // LeaseNamespaceLister. type LeaseNamespaceListerExpansion interface{} + +// LeaseCandidateListerExpansion allows custom methods to be added to +// LeaseCandidateLister. +type LeaseCandidateListerExpansion interface{} + +// LeaseCandidateNamespaceListerExpansion allows custom methods to be added to +// LeaseCandidateNamespaceLister. +type LeaseCandidateNamespaceListerExpansion interface{} diff --git a/listers/coordination/v1beta1/leasecandidate.go b/listers/coordination/v1beta1/leasecandidate.go new file mode 100644 index 0000000000..9c176a3ec4 --- /dev/null +++ b/listers/coordination/v1beta1/leasecandidate.go @@ -0,0 +1,70 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta1 + +import ( + coordinationv1beta1 "k8s.io/api/coordination/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// LeaseCandidateLister helps list LeaseCandidates. +// All objects returned here must be treated as read-only. +type LeaseCandidateLister interface { + // List lists all LeaseCandidates in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*coordinationv1beta1.LeaseCandidate, err error) + // LeaseCandidates returns an object that can list and get LeaseCandidates. + LeaseCandidates(namespace string) LeaseCandidateNamespaceLister + LeaseCandidateListerExpansion +} + +// leaseCandidateLister implements the LeaseCandidateLister interface. +type leaseCandidateLister struct { + listers.ResourceIndexer[*coordinationv1beta1.LeaseCandidate] +} + +// NewLeaseCandidateLister returns a new LeaseCandidateLister. +func NewLeaseCandidateLister(indexer cache.Indexer) LeaseCandidateLister { + return &leaseCandidateLister{listers.New[*coordinationv1beta1.LeaseCandidate](indexer, coordinationv1beta1.Resource("leasecandidate"))} +} + +// LeaseCandidates returns an object that can list and get LeaseCandidates. +func (s *leaseCandidateLister) LeaseCandidates(namespace string) LeaseCandidateNamespaceLister { + return leaseCandidateNamespaceLister{listers.NewNamespaced[*coordinationv1beta1.LeaseCandidate](s.ResourceIndexer, namespace)} +} + +// LeaseCandidateNamespaceLister helps list and get LeaseCandidates. +// All objects returned here must be treated as read-only. +type LeaseCandidateNamespaceLister interface { + // List lists all LeaseCandidates in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*coordinationv1beta1.LeaseCandidate, err error) + // Get retrieves the LeaseCandidate from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*coordinationv1beta1.LeaseCandidate, error) + LeaseCandidateNamespaceListerExpansion +} + +// leaseCandidateNamespaceLister implements the LeaseCandidateNamespaceLister +// interface. +type leaseCandidateNamespaceLister struct { + listers.ResourceIndexer[*coordinationv1beta1.LeaseCandidate] +} diff --git a/listers/doc.go b/listers/doc.go index 96c330c931..da6a80408f 100644 --- a/listers/doc.go +++ b/listers/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package listers provides generated listers for Kubernetes APIs. -package listers // import "k8s.io/client-go/listers" +package listers diff --git a/listers/networking/v1/expansion_generated.go b/listers/networking/v1/expansion_generated.go index a380c2418f..a2d335e6bd 100644 --- a/listers/networking/v1/expansion_generated.go +++ b/listers/networking/v1/expansion_generated.go @@ -18,6 +18,10 @@ limitations under the License. package v1 +// IPAddressListerExpansion allows custom methods to be added to +// IPAddressLister. +type IPAddressListerExpansion interface{} + // IngressListerExpansion allows custom methods to be added to // IngressLister. type IngressListerExpansion interface{} @@ -37,3 +41,7 @@ type NetworkPolicyListerExpansion interface{} // NetworkPolicyNamespaceListerExpansion allows custom methods to be added to // NetworkPolicyNamespaceLister. type NetworkPolicyNamespaceListerExpansion interface{} + +// ServiceCIDRListerExpansion allows custom methods to be added to +// ServiceCIDRLister. +type ServiceCIDRListerExpansion interface{} diff --git a/listers/networking/v1/ipaddress.go b/listers/networking/v1/ipaddress.go new file mode 100644 index 0000000000..e554bd38b4 --- /dev/null +++ b/listers/networking/v1/ipaddress.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1 + +import ( + networkingv1 "k8s.io/api/networking/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// IPAddressLister helps list IPAddresses. +// All objects returned here must be treated as read-only. +type IPAddressLister interface { + // List lists all IPAddresses in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*networkingv1.IPAddress, err error) + // Get retrieves the IPAddress from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*networkingv1.IPAddress, error) + IPAddressListerExpansion +} + +// iPAddressLister implements the IPAddressLister interface. +type iPAddressLister struct { + listers.ResourceIndexer[*networkingv1.IPAddress] +} + +// NewIPAddressLister returns a new IPAddressLister. +func NewIPAddressLister(indexer cache.Indexer) IPAddressLister { + return &iPAddressLister{listers.New[*networkingv1.IPAddress](indexer, networkingv1.Resource("ipaddress"))} +} diff --git a/listers/networking/v1/servicecidr.go b/listers/networking/v1/servicecidr.go new file mode 100644 index 0000000000..6e326da16b --- /dev/null +++ b/listers/networking/v1/servicecidr.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1 + +import ( + networkingv1 "k8s.io/api/networking/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// ServiceCIDRLister helps list ServiceCIDRs. +// All objects returned here must be treated as read-only. +type ServiceCIDRLister interface { + // List lists all ServiceCIDRs in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*networkingv1.ServiceCIDR, err error) + // Get retrieves the ServiceCIDR from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*networkingv1.ServiceCIDR, error) + ServiceCIDRListerExpansion +} + +// serviceCIDRLister implements the ServiceCIDRLister interface. +type serviceCIDRLister struct { + listers.ResourceIndexer[*networkingv1.ServiceCIDR] +} + +// NewServiceCIDRLister returns a new ServiceCIDRLister. +func NewServiceCIDRLister(indexer cache.Indexer) ServiceCIDRLister { + return &serviceCIDRLister{listers.New[*networkingv1.ServiceCIDR](indexer, networkingv1.Resource("servicecidr"))} +} diff --git a/listers/resource/v1alpha3/devicetaintrule.go b/listers/resource/v1alpha3/devicetaintrule.go new file mode 100644 index 0000000000..28d94ff2e4 --- /dev/null +++ b/listers/resource/v1alpha3/devicetaintrule.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + resourcev1alpha3 "k8s.io/api/resource/v1alpha3" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// DeviceTaintRuleLister helps list DeviceTaintRules. +// All objects returned here must be treated as read-only. +type DeviceTaintRuleLister interface { + // List lists all DeviceTaintRules in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1alpha3.DeviceTaintRule, err error) + // Get retrieves the DeviceTaintRule from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*resourcev1alpha3.DeviceTaintRule, error) + DeviceTaintRuleListerExpansion +} + +// deviceTaintRuleLister implements the DeviceTaintRuleLister interface. +type deviceTaintRuleLister struct { + listers.ResourceIndexer[*resourcev1alpha3.DeviceTaintRule] +} + +// NewDeviceTaintRuleLister returns a new DeviceTaintRuleLister. +func NewDeviceTaintRuleLister(indexer cache.Indexer) DeviceTaintRuleLister { + return &deviceTaintRuleLister{listers.New[*resourcev1alpha3.DeviceTaintRule](indexer, resourcev1alpha3.Resource("devicetaintrule"))} +} diff --git a/listers/resource/v1alpha3/expansion_generated.go b/listers/resource/v1alpha3/expansion_generated.go index f626c92837..ff94d28691 100644 --- a/listers/resource/v1alpha3/expansion_generated.go +++ b/listers/resource/v1alpha3/expansion_generated.go @@ -22,6 +22,10 @@ package v1alpha3 // DeviceClassLister. type DeviceClassListerExpansion interface{} +// DeviceTaintRuleListerExpansion allows custom methods to be added to +// DeviceTaintRuleLister. +type DeviceTaintRuleListerExpansion interface{} + // ResourceClaimListerExpansion allows custom methods to be added to // ResourceClaimLister. type ResourceClaimListerExpansion interface{} diff --git a/listers/resource/v1beta2/deviceclass.go b/listers/resource/v1beta2/deviceclass.go new file mode 100644 index 0000000000..a89e57202b --- /dev/null +++ b/listers/resource/v1beta2/deviceclass.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// DeviceClassLister helps list DeviceClasses. +// All objects returned here must be treated as read-only. +type DeviceClassLister interface { + // List lists all DeviceClasses in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1beta2.DeviceClass, err error) + // Get retrieves the DeviceClass from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*resourcev1beta2.DeviceClass, error) + DeviceClassListerExpansion +} + +// deviceClassLister implements the DeviceClassLister interface. +type deviceClassLister struct { + listers.ResourceIndexer[*resourcev1beta2.DeviceClass] +} + +// NewDeviceClassLister returns a new DeviceClassLister. +func NewDeviceClassLister(indexer cache.Indexer) DeviceClassLister { + return &deviceClassLister{listers.New[*resourcev1beta2.DeviceClass](indexer, resourcev1beta2.Resource("deviceclass"))} +} diff --git a/listers/resource/v1beta2/expansion_generated.go b/listers/resource/v1beta2/expansion_generated.go new file mode 100644 index 0000000000..590f26bd74 --- /dev/null +++ b/listers/resource/v1beta2/expansion_generated.go @@ -0,0 +1,43 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta2 + +// DeviceClassListerExpansion allows custom methods to be added to +// DeviceClassLister. +type DeviceClassListerExpansion interface{} + +// ResourceClaimListerExpansion allows custom methods to be added to +// ResourceClaimLister. +type ResourceClaimListerExpansion interface{} + +// ResourceClaimNamespaceListerExpansion allows custom methods to be added to +// ResourceClaimNamespaceLister. +type ResourceClaimNamespaceListerExpansion interface{} + +// ResourceClaimTemplateListerExpansion allows custom methods to be added to +// ResourceClaimTemplateLister. +type ResourceClaimTemplateListerExpansion interface{} + +// ResourceClaimTemplateNamespaceListerExpansion allows custom methods to be added to +// ResourceClaimTemplateNamespaceLister. +type ResourceClaimTemplateNamespaceListerExpansion interface{} + +// ResourceSliceListerExpansion allows custom methods to be added to +// ResourceSliceLister. +type ResourceSliceListerExpansion interface{} diff --git a/listers/resource/v1beta2/resourceclaim.go b/listers/resource/v1beta2/resourceclaim.go new file mode 100644 index 0000000000..ec6d40663c --- /dev/null +++ b/listers/resource/v1beta2/resourceclaim.go @@ -0,0 +1,70 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// ResourceClaimLister helps list ResourceClaims. +// All objects returned here must be treated as read-only. +type ResourceClaimLister interface { + // List lists all ResourceClaims in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1beta2.ResourceClaim, err error) + // ResourceClaims returns an object that can list and get ResourceClaims. + ResourceClaims(namespace string) ResourceClaimNamespaceLister + ResourceClaimListerExpansion +} + +// resourceClaimLister implements the ResourceClaimLister interface. +type resourceClaimLister struct { + listers.ResourceIndexer[*resourcev1beta2.ResourceClaim] +} + +// NewResourceClaimLister returns a new ResourceClaimLister. +func NewResourceClaimLister(indexer cache.Indexer) ResourceClaimLister { + return &resourceClaimLister{listers.New[*resourcev1beta2.ResourceClaim](indexer, resourcev1beta2.Resource("resourceclaim"))} +} + +// ResourceClaims returns an object that can list and get ResourceClaims. +func (s *resourceClaimLister) ResourceClaims(namespace string) ResourceClaimNamespaceLister { + return resourceClaimNamespaceLister{listers.NewNamespaced[*resourcev1beta2.ResourceClaim](s.ResourceIndexer, namespace)} +} + +// ResourceClaimNamespaceLister helps list and get ResourceClaims. +// All objects returned here must be treated as read-only. +type ResourceClaimNamespaceLister interface { + // List lists all ResourceClaims in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1beta2.ResourceClaim, err error) + // Get retrieves the ResourceClaim from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*resourcev1beta2.ResourceClaim, error) + ResourceClaimNamespaceListerExpansion +} + +// resourceClaimNamespaceLister implements the ResourceClaimNamespaceLister +// interface. +type resourceClaimNamespaceLister struct { + listers.ResourceIndexer[*resourcev1beta2.ResourceClaim] +} diff --git a/listers/resource/v1beta2/resourceclaimtemplate.go b/listers/resource/v1beta2/resourceclaimtemplate.go new file mode 100644 index 0000000000..8ff19b88ec --- /dev/null +++ b/listers/resource/v1beta2/resourceclaimtemplate.go @@ -0,0 +1,70 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// ResourceClaimTemplateLister helps list ResourceClaimTemplates. +// All objects returned here must be treated as read-only. +type ResourceClaimTemplateLister interface { + // List lists all ResourceClaimTemplates in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1beta2.ResourceClaimTemplate, err error) + // ResourceClaimTemplates returns an object that can list and get ResourceClaimTemplates. + ResourceClaimTemplates(namespace string) ResourceClaimTemplateNamespaceLister + ResourceClaimTemplateListerExpansion +} + +// resourceClaimTemplateLister implements the ResourceClaimTemplateLister interface. +type resourceClaimTemplateLister struct { + listers.ResourceIndexer[*resourcev1beta2.ResourceClaimTemplate] +} + +// NewResourceClaimTemplateLister returns a new ResourceClaimTemplateLister. +func NewResourceClaimTemplateLister(indexer cache.Indexer) ResourceClaimTemplateLister { + return &resourceClaimTemplateLister{listers.New[*resourcev1beta2.ResourceClaimTemplate](indexer, resourcev1beta2.Resource("resourceclaimtemplate"))} +} + +// ResourceClaimTemplates returns an object that can list and get ResourceClaimTemplates. +func (s *resourceClaimTemplateLister) ResourceClaimTemplates(namespace string) ResourceClaimTemplateNamespaceLister { + return resourceClaimTemplateNamespaceLister{listers.NewNamespaced[*resourcev1beta2.ResourceClaimTemplate](s.ResourceIndexer, namespace)} +} + +// ResourceClaimTemplateNamespaceLister helps list and get ResourceClaimTemplates. +// All objects returned here must be treated as read-only. +type ResourceClaimTemplateNamespaceLister interface { + // List lists all ResourceClaimTemplates in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1beta2.ResourceClaimTemplate, err error) + // Get retrieves the ResourceClaimTemplate from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*resourcev1beta2.ResourceClaimTemplate, error) + ResourceClaimTemplateNamespaceListerExpansion +} + +// resourceClaimTemplateNamespaceLister implements the ResourceClaimTemplateNamespaceLister +// interface. +type resourceClaimTemplateNamespaceLister struct { + listers.ResourceIndexer[*resourcev1beta2.ResourceClaimTemplate] +} diff --git a/listers/resource/v1beta2/resourceslice.go b/listers/resource/v1beta2/resourceslice.go new file mode 100644 index 0000000000..f1a8174078 --- /dev/null +++ b/listers/resource/v1beta2/resourceslice.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// ResourceSliceLister helps list ResourceSlices. +// All objects returned here must be treated as read-only. +type ResourceSliceLister interface { + // List lists all ResourceSlices in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1beta2.ResourceSlice, err error) + // Get retrieves the ResourceSlice from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*resourcev1beta2.ResourceSlice, error) + ResourceSliceListerExpansion +} + +// resourceSliceLister implements the ResourceSliceLister interface. +type resourceSliceLister struct { + listers.ResourceIndexer[*resourcev1beta2.ResourceSlice] +} + +// NewResourceSliceLister returns a new ResourceSliceLister. +func NewResourceSliceLister(indexer cache.Indexer) ResourceSliceLister { + return &resourceSliceLister{listers.New[*resourcev1beta2.ResourceSlice](indexer, resourcev1beta2.Resource("resourceslice"))} +} diff --git a/metadata/metadatainformer/informer.go b/metadata/metadatainformer/informer.go index ff3537e98e..6eb0584fd3 100644 --- a/metadata/metadatainformer/informer.go +++ b/metadata/metadatainformer/informer.go @@ -183,13 +183,25 @@ func NewFilteredMetadataInformer(client metadata.Interface, gvr schema.GroupVers if tweakListOptions != nil { tweakListOptions(&options) } - return client.Resource(gvr).Namespace(namespace).List(context.TODO(), options) + return client.Resource(gvr).Namespace(namespace).List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.Resource(gvr).Namespace(namespace).Watch(context.TODO(), options) + return client.Resource(gvr).Namespace(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Resource(gvr).Namespace(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.Resource(gvr).Namespace(namespace).Watch(ctx, options) }, }, &metav1.PartialObjectMetadata{}, diff --git a/pkg/apis/clientauthentication/doc.go b/pkg/apis/clientauthentication/doc.go index b99459757e..486790fa69 100644 --- a/pkg/apis/clientauthentication/doc.go +++ b/pkg/apis/clientauthentication/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // +groupName=client.authentication.k8s.io -package clientauthentication // import "k8s.io/client-go/pkg/apis/clientauthentication" +package clientauthentication diff --git a/pkg/apis/clientauthentication/v1/doc.go b/pkg/apis/clientauthentication/v1/doc.go index 94ca35c2c9..e378b75cf6 100644 --- a/pkg/apis/clientauthentication/v1/doc.go +++ b/pkg/apis/clientauthentication/v1/doc.go @@ -21,4 +21,4 @@ limitations under the License. // +groupName=client.authentication.k8s.io -package v1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1" +package v1 diff --git a/pkg/apis/clientauthentication/v1beta1/doc.go b/pkg/apis/clientauthentication/v1beta1/doc.go index 22d1c588bc..6eb6a98157 100644 --- a/pkg/apis/clientauthentication/v1beta1/doc.go +++ b/pkg/apis/clientauthentication/v1beta1/doc.go @@ -21,4 +21,4 @@ limitations under the License. // +groupName=client.authentication.k8s.io -package v1beta1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" +package v1beta1 diff --git a/pkg/version/doc.go b/pkg/version/doc.go index 05e997e133..c3ace74513 100644 --- a/pkg/version/doc.go +++ b/pkg/version/doc.go @@ -18,4 +18,4 @@ limitations under the License. // Package version supplies version information collected at build time to // kubernetes components. -package version // import "k8s.io/client-go/pkg/version" +package version diff --git a/rest/.mockery.yaml b/rest/.mockery.yaml new file mode 100644 index 0000000000..e21d7b5be2 --- /dev/null +++ b/rest/.mockery.yaml @@ -0,0 +1,10 @@ +--- +dir: . +filename: "mock_{{.InterfaceName | snakecase}}_test.go" +boilerplate-file: ../../../../../hack/boilerplate/boilerplate.generatego.txt +outpkg: rest +with-expecter: true +packages: + k8s.io/client-go/rest: + interfaces: + BackoffManager: diff --git a/rest/client.go b/rest/client.go index 159caa13fa..a085c334f9 100644 --- a/rest/client.go +++ b/rest/client.go @@ -93,7 +93,7 @@ type RESTClient struct { content requestClientContentConfigProvider // creates BackoffManager that is passed to requests. - createBackoffMgr func() BackoffManager + createBackoffMgr func() BackoffManagerWithContext // rateLimiter is shared among all requests created by this client unless specifically // overridden. @@ -101,7 +101,7 @@ type RESTClient struct { // warningHandler is shared among all requests created by this client. // If not set, defaultWarningHandler is used. - warningHandler WarningHandler + warningHandler WarningHandlerWithContext // Set specific behavior of the client. If not set http.DefaultClient will be used. Client *http.Client @@ -178,7 +178,7 @@ func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter { // readExpBackoffConfig handles the internal logic of determining what the // backoff policy is. By default if no information is available, NoBackoff. // TODO Generalize this see #17727 . -func readExpBackoffConfig() BackoffManager { +func readExpBackoffConfig() BackoffManagerWithContext { backoffBase := os.Getenv(envBackoffBase) backoffDuration := os.Getenv(envBackoffDuration) diff --git a/rest/client_test.go b/rest/client_test.go index ebb35c5090..c03f6832c6 100644 --- a/rest/client_test.go +++ b/rest/client_test.go @@ -35,6 +35,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" utiltesting "k8s.io/client-go/util/testing" + "k8s.io/klog/v2/ktesting" "github.com/google/go-cmp/cmp" ) @@ -335,26 +336,26 @@ func TestHTTPProxy(t *testing.T) { } func TestCreateBackoffManager(t *testing.T) { - + _, ctx := ktesting.NewTestContext(t) theUrl, _ := url.Parse("http://localhost") // 1 second base backoff + duration of 2 seconds -> exponential backoff for requests. t.Setenv(envBackoffBase, "1") t.Setenv(envBackoffDuration, "2") backoff := readExpBackoffConfig() - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - if backoff.CalculateBackoff(theUrl)/time.Second != 2 { + backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500) + backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500) + if backoff.CalculateBackoffWithContext(ctx, theUrl)/time.Second != 2 { t.Errorf("Backoff env not working.") } // 0 duration -> no backoff. t.Setenv(envBackoffBase, "1") t.Setenv(envBackoffDuration, "0") - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) + backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500) + backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500) backoff = readExpBackoffConfig() - if backoff.CalculateBackoff(theUrl)/time.Second != 0 { + if backoff.CalculateBackoffWithContext(ctx, theUrl)/time.Second != 0 { t.Errorf("Zero backoff duration, but backoff still occurring.") } @@ -362,9 +363,9 @@ func TestCreateBackoffManager(t *testing.T) { t.Setenv(envBackoffBase, "") t.Setenv(envBackoffDuration, "") backoff = readExpBackoffConfig() - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - if backoff.CalculateBackoff(theUrl)/time.Second != 0 { + backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500) + backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500) + if backoff.CalculateBackoffWithContext(ctx, theUrl)/time.Second != 0 { t.Errorf("Backoff should have been 0.") } diff --git a/rest/config.go b/rest/config.go index f2e813d075..82d4f7136a 100644 --- a/rest/config.go +++ b/rest/config.go @@ -129,10 +129,23 @@ type Config struct { RateLimiter flowcontrol.RateLimiter // WarningHandler handles warnings in server responses. - // If not set, the default warning handler is used. - // See documentation for SetDefaultWarningHandler() for details. + // If this and WarningHandlerWithContext are not set, the + // default warning handler is used. If both are set, + // WarningHandlerWithContext is used. + // + // See documentation for [SetDefaultWarningHandler] for details. + // + //logcheck:context // WarningHandlerWithContext should be used instead of WarningHandler in code which supports contextual logging. WarningHandler WarningHandler + // WarningHandlerWithContext handles warnings in server responses. + // If this and WarningHandler are not set, the + // default warning handler is used. If both are set, + // WarningHandlerWithContext is used. + // + // See documentation for [SetDefaultWarningHandler] for details. + WarningHandlerWithContext WarningHandlerWithContext + // The maximum length of time to wait before giving up on a server request. A value of zero means no timeout. Timeout time.Duration @@ -381,12 +394,27 @@ func RESTClientForConfigAndClient(config *Config, httpClient *http.Client) (*RES } restClient, err := NewRESTClient(baseURL, versionedAPIPath, clientContent, rateLimiter, httpClient) - if err == nil && config.WarningHandler != nil { - restClient.warningHandler = config.WarningHandler - } + maybeSetWarningHandler(restClient, config.WarningHandler, config.WarningHandlerWithContext) return restClient, err } +// maybeSetWarningHandler sets the handlerWithContext if non-nil, +// otherwise the handler with a wrapper if non-nil, +// and does nothing if both are nil. +// +// May be called for a nil client. +func maybeSetWarningHandler(c *RESTClient, handler WarningHandler, handlerWithContext WarningHandlerWithContext) { + if c == nil { + return + } + switch { + case handlerWithContext != nil: + c.warningHandler = handlerWithContext + case handler != nil: + c.warningHandler = warningLoggerNopContext{l: handler} + } +} + // UnversionedRESTClientFor is the same as RESTClientFor, except that it allows // the config.Version to be empty. func UnversionedRESTClientFor(config *Config) (*RESTClient, error) { @@ -448,9 +476,7 @@ func UnversionedRESTClientForConfigAndClient(config *Config, httpClient *http.Cl } restClient, err := NewRESTClient(baseURL, versionedAPIPath, clientContent, rateLimiter, httpClient) - if err == nil && config.WarningHandler != nil { - restClient.warningHandler = config.WarningHandler - } + maybeSetWarningHandler(restClient, config.WarningHandler, config.WarningHandlerWithContext) return restClient, err } @@ -532,6 +558,7 @@ func InClusterConfig() (*Config, error) { tlsClientConfig := TLSClientConfig{} if _, err := certutil.NewPool(rootCAFile); err != nil { + //nolint:logcheck // The decision to log this instead of returning an error goes back to ~2016. It's part of the client-go API now, so not changing it just to support contextual logging. klog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err) } else { tlsClientConfig.CAFile = rootCAFile @@ -616,15 +643,16 @@ func AnonymousClientConfig(config *Config) *Config { CAData: config.TLSClientConfig.CAData, NextProtos: config.TLSClientConfig.NextProtos, }, - RateLimiter: config.RateLimiter, - WarningHandler: config.WarningHandler, - UserAgent: config.UserAgent, - DisableCompression: config.DisableCompression, - QPS: config.QPS, - Burst: config.Burst, - Timeout: config.Timeout, - Dial: config.Dial, - Proxy: config.Proxy, + RateLimiter: config.RateLimiter, + WarningHandler: config.WarningHandler, + WarningHandlerWithContext: config.WarningHandlerWithContext, + UserAgent: config.UserAgent, + DisableCompression: config.DisableCompression, + QPS: config.QPS, + Burst: config.Burst, + Timeout: config.Timeout, + Dial: config.Dial, + Proxy: config.Proxy, } } @@ -658,17 +686,18 @@ func CopyConfig(config *Config) *Config { CAData: config.TLSClientConfig.CAData, NextProtos: config.TLSClientConfig.NextProtos, }, - UserAgent: config.UserAgent, - DisableCompression: config.DisableCompression, - Transport: config.Transport, - WrapTransport: config.WrapTransport, - QPS: config.QPS, - Burst: config.Burst, - RateLimiter: config.RateLimiter, - WarningHandler: config.WarningHandler, - Timeout: config.Timeout, - Dial: config.Dial, - Proxy: config.Proxy, + UserAgent: config.UserAgent, + DisableCompression: config.DisableCompression, + Transport: config.Transport, + WrapTransport: config.WrapTransport, + QPS: config.QPS, + Burst: config.Burst, + RateLimiter: config.RateLimiter, + WarningHandler: config.WarningHandler, + WarningHandlerWithContext: config.WarningHandlerWithContext, + Timeout: config.Timeout, + Dial: config.Dial, + Proxy: config.Proxy, } if config.ExecProvider != nil && config.ExecProvider.Config != nil { c.ExecProvider.Config = config.ExecProvider.Config.DeepCopyObject() diff --git a/rest/config_test.go b/rest/config_test.go index 4fc74f545a..9323d4cce7 100644 --- a/rest/config_test.go +++ b/rest/config_test.go @@ -39,8 +39,9 @@ import ( "k8s.io/client-go/util/flowcontrol" "github.com/google/go-cmp/cmp" - fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sigs.k8s.io/randfill" ) func TestIsConfigTransportTLS(t *testing.T) { @@ -266,6 +267,19 @@ type fakeWarningHandler struct{} func (f fakeWarningHandler) HandleWarningHeader(code int, agent string, message string) {} +type fakeWarningHandlerWithLogging struct { + messages []string +} + +func (f *fakeWarningHandlerWithLogging) HandleWarningHeader(code int, agent string, message string) { + f.messages = append(f.messages, message) +} + +type fakeWarningHandlerWithContext struct{} + +func (f fakeWarningHandlerWithContext) HandleWarningHeaderWithContext(ctx context.Context, code int, agent string, message string) { +} + type fakeNegotiatedSerializer struct{} func (n *fakeNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo { @@ -299,57 +313,60 @@ func (fakeAuthProviderConfigPersister) Persist(map[string]string) error { var fakeAuthProviderConfigPersisterError = errors.New("fakeAuthProviderConfigPersisterError") func TestAnonymousAuthConfig(t *testing.T) { - f := fuzz.New().NilChance(0.0).NumElements(1, 1) + f := randfill.New().NilChance(0.0).NumElements(1, 1) f.Funcs( - func(r *runtime.Codec, f fuzz.Continue) { + func(r *runtime.Codec, f randfill.Continue) { codec := &fakeCodec{} - f.Fuzz(codec) + f.Fill(codec) *r = codec }, - func(r *http.RoundTripper, f fuzz.Continue) { + func(r *http.RoundTripper, f randfill.Continue) { roundTripper := &fakeRoundTripper{} - f.Fuzz(roundTripper) + f.Fill(roundTripper) *r = roundTripper }, - func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) { + func(fn *func(http.RoundTripper) http.RoundTripper, f randfill.Continue) { *fn = fakeWrapperFunc }, - func(fn *transport.WrapperFunc, f fuzz.Continue) { + func(fn *transport.WrapperFunc, f randfill.Continue) { *fn = fakeWrapperFunc }, - func(r *runtime.NegotiatedSerializer, f fuzz.Continue) { + func(r *runtime.NegotiatedSerializer, f randfill.Continue) { serializer := &fakeNegotiatedSerializer{} - f.Fuzz(serializer) + f.Fill(serializer) *r = serializer }, - func(r *flowcontrol.RateLimiter, f fuzz.Continue) { + func(r *flowcontrol.RateLimiter, f randfill.Continue) { limiter := &fakeLimiter{} - f.Fuzz(limiter) + f.Fill(limiter) *r = limiter }, - func(h *WarningHandler, f fuzz.Continue) { + func(h *WarningHandler, f randfill.Continue) { *h = &fakeWarningHandler{} }, + func(h *WarningHandlerWithContext, f randfill.Continue) { + *h = &fakeWarningHandlerWithContext{} + }, // Authentication does not require fuzzer - func(r *AuthProviderConfigPersister, f fuzz.Continue) {}, - func(r *clientcmdapi.AuthProviderConfig, f fuzz.Continue) { + func(r *AuthProviderConfigPersister, f randfill.Continue) {}, + func(r *clientcmdapi.AuthProviderConfig, f randfill.Continue) { r.Config = map[string]string{} }, - func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f fuzz.Continue) { + func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f randfill.Continue) { *r = fakeDialFunc }, - func(r *func(*http.Request) (*url.URL, error), f fuzz.Continue) { + func(r *func(*http.Request) (*url.URL, error), f randfill.Continue) { *r = fakeProxyFunc }, - func(r *runtime.Object, f fuzz.Continue) { + func(r *runtime.Object, f randfill.Continue) { unknown := &runtime.Unknown{} - f.Fuzz(unknown) + f.Fill(unknown) *r = unknown }, ) for i := 0; i < 20; i++ { original := &Config{} - f.Fuzz(original) + f.Fill(original) actual := AnonymousClientConfig(original) expected := *original @@ -397,55 +414,58 @@ func TestAnonymousAuthConfig(t *testing.T) { } func TestCopyConfig(t *testing.T) { - f := fuzz.New().NilChance(0.0).NumElements(1, 1) + f := randfill.New().NilChance(0.0).NumElements(1, 1) f.Funcs( - func(r *runtime.Codec, f fuzz.Continue) { + func(r *runtime.Codec, f randfill.Continue) { codec := &fakeCodec{} - f.Fuzz(codec) + f.Fill(codec) *r = codec }, - func(r *http.RoundTripper, f fuzz.Continue) { + func(r *http.RoundTripper, f randfill.Continue) { roundTripper := &fakeRoundTripper{} - f.Fuzz(roundTripper) + f.Fill(roundTripper) *r = roundTripper }, - func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) { + func(fn *func(http.RoundTripper) http.RoundTripper, f randfill.Continue) { *fn = fakeWrapperFunc }, - func(fn *transport.WrapperFunc, f fuzz.Continue) { + func(fn *transport.WrapperFunc, f randfill.Continue) { *fn = fakeWrapperFunc }, - func(r *runtime.NegotiatedSerializer, f fuzz.Continue) { + func(r *runtime.NegotiatedSerializer, f randfill.Continue) { serializer := &fakeNegotiatedSerializer{} - f.Fuzz(serializer) + f.Fill(serializer) *r = serializer }, - func(r *flowcontrol.RateLimiter, f fuzz.Continue) { + func(r *flowcontrol.RateLimiter, f randfill.Continue) { limiter := &fakeLimiter{} - f.Fuzz(limiter) + f.Fill(limiter) *r = limiter }, - func(h *WarningHandler, f fuzz.Continue) { + func(h *WarningHandler, f randfill.Continue) { *h = &fakeWarningHandler{} }, - func(r *AuthProviderConfigPersister, f fuzz.Continue) { + func(h *WarningHandlerWithContext, f randfill.Continue) { + *h = &fakeWarningHandlerWithContext{} + }, + func(r *AuthProviderConfigPersister, f randfill.Continue) { *r = fakeAuthProviderConfigPersister{} }, - func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f fuzz.Continue) { + func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f randfill.Continue) { *r = fakeDialFunc }, - func(r *func(*http.Request) (*url.URL, error), f fuzz.Continue) { + func(r *func(*http.Request) (*url.URL, error), f randfill.Continue) { *r = fakeProxyFunc }, - func(r *runtime.Object, f fuzz.Continue) { + func(r *runtime.Object, f randfill.Continue) { unknown := &runtime.Unknown{} - f.Fuzz(unknown) + f.Fill(unknown) *r = unknown }, ) for i := 0; i < 20; i++ { original := &Config{} - f.Fuzz(original) + f.Fill(original) actual := CopyConfig(original) expected := *original @@ -619,25 +639,69 @@ func TestConfigSprint(t *testing.T) { KeyData: []byte("fake key"), NextProtos: []string{"h2", "http/1.1"}, }, - UserAgent: "gobot", - Transport: &fakeRoundTripper{}, - WrapTransport: fakeWrapperFunc, - QPS: 1, - Burst: 2, - RateLimiter: &fakeLimiter{}, - WarningHandler: fakeWarningHandler{}, - Timeout: 3 * time.Second, - Dial: fakeDialFunc, - Proxy: fakeProxyFunc, + UserAgent: "gobot", + Transport: &fakeRoundTripper{}, + WrapTransport: fakeWrapperFunc, + QPS: 1, + Burst: 2, + RateLimiter: &fakeLimiter{}, + WarningHandler: fakeWarningHandler{}, + WarningHandlerWithContext: fakeWarningHandlerWithContext{}, + Timeout: 3 * time.Second, + Dial: fakeDialFunc, + Proxy: fakeProxyFunc, } want := fmt.Sprintf( - `&rest.Config{Host:"localhost:8080", APIPath:"v1", ContentConfig:rest.ContentConfig{AcceptContentTypes:"application/json", ContentType:"application/json", GroupVersion:(*schema.GroupVersion)(nil), NegotiatedSerializer:runtime.NegotiatedSerializer(nil)}, Username:"gopher", Password:"--- REDACTED ---", BearerToken:"--- REDACTED ---", BearerTokenFile:"", Impersonate:rest.ImpersonationConfig{UserName:"gopher2", UID:"uid123", Groups:[]string(nil), Extra:map[string][]string(nil)}, AuthProvider:api.AuthProviderConfig{Name: "gopher", Config: map[string]string{--- REDACTED ---}}, AuthConfigPersister:rest.AuthProviderConfigPersister(--- REDACTED ---), ExecProvider:api.ExecConfig{Command: "sudo", Args: []string{"--- REDACTED ---"}, Env: []ExecEnvVar{--- REDACTED ---}, APIVersion: "", ProvideClusterInfo: true, Config: runtime.Object(--- REDACTED ---), StdinUnavailable: false}, TLSClientConfig:rest.sanitizedTLSClientConfig{Insecure:false, ServerName:"", CertFile:"a.crt", KeyFile:"a.key", CAFile:"", CertData:[]uint8{0x2d, 0x2d, 0x2d, 0x20, 0x54, 0x52, 0x55, 0x4e, 0x43, 0x41, 0x54, 0x45, 0x44, 0x20, 0x2d, 0x2d, 0x2d}, KeyData:[]uint8{0x2d, 0x2d, 0x2d, 0x20, 0x52, 0x45, 0x44, 0x41, 0x43, 0x54, 0x45, 0x44, 0x20, 0x2d, 0x2d, 0x2d}, CAData:[]uint8(nil), NextProtos:[]string{"h2", "http/1.1"}}, UserAgent:"gobot", DisableCompression:false, Transport:(*rest.fakeRoundTripper)(%p), WrapTransport:(transport.WrapperFunc)(%p), QPS:1, Burst:2, RateLimiter:(*rest.fakeLimiter)(%p), WarningHandler:rest.fakeWarningHandler{}, Timeout:3000000000, Dial:(func(context.Context, string, string) (net.Conn, error))(%p), Proxy:(func(*http.Request) (*url.URL, error))(%p)}`, + `&rest.Config{Host:"localhost:8080", APIPath:"v1", ContentConfig:rest.ContentConfig{AcceptContentTypes:"application/json", ContentType:"application/json", GroupVersion:(*schema.GroupVersion)(nil), NegotiatedSerializer:runtime.NegotiatedSerializer(nil)}, Username:"gopher", Password:"--- REDACTED ---", BearerToken:"--- REDACTED ---", BearerTokenFile:"", Impersonate:rest.ImpersonationConfig{UserName:"gopher2", UID:"uid123", Groups:[]string(nil), Extra:map[string][]string(nil)}, AuthProvider:api.AuthProviderConfig{Name: "gopher", Config: map[string]string{--- REDACTED ---}}, AuthConfigPersister:rest.AuthProviderConfigPersister(--- REDACTED ---), ExecProvider:api.ExecConfig{Command: "sudo", Args: []string{"--- REDACTED ---"}, Env: []ExecEnvVar{--- REDACTED ---}, APIVersion: "", ProvideClusterInfo: true, Config: runtime.Object(--- REDACTED ---), StdinUnavailable: false}, TLSClientConfig:rest.sanitizedTLSClientConfig{Insecure:false, ServerName:"", CertFile:"a.crt", KeyFile:"a.key", CAFile:"", CertData:[]uint8{0x2d, 0x2d, 0x2d, 0x20, 0x54, 0x52, 0x55, 0x4e, 0x43, 0x41, 0x54, 0x45, 0x44, 0x20, 0x2d, 0x2d, 0x2d}, KeyData:[]uint8{0x2d, 0x2d, 0x2d, 0x20, 0x52, 0x45, 0x44, 0x41, 0x43, 0x54, 0x45, 0x44, 0x20, 0x2d, 0x2d, 0x2d}, CAData:[]uint8(nil), NextProtos:[]string{"h2", "http/1.1"}}, UserAgent:"gobot", DisableCompression:false, Transport:(*rest.fakeRoundTripper)(%p), WrapTransport:(transport.WrapperFunc)(%p), QPS:1, Burst:2, RateLimiter:(*rest.fakeLimiter)(%p), WarningHandler:rest.fakeWarningHandler{}, WarningHandlerWithContext:rest.fakeWarningHandlerWithContext{}, Timeout:3000000000, Dial:(func(context.Context, string, string) (net.Conn, error))(%p), Proxy:(func(*http.Request) (*url.URL, error))(%p)}`, c.Transport, fakeWrapperFunc, c.RateLimiter, fakeDialFunc, fakeProxyFunc, ) for _, f := range []string{"%s", "%v", "%+v", "%#v"} { if got := fmt.Sprintf(f, c); want != got { - t.Errorf("fmt.Sprintf(%q, c)\ngot: %q\nwant: %q", f, got, want) + t.Errorf("fmt.Sprintf(%q, c)\ngot: %q\nwant: %q\ndiff: %s", f, got, want, cmp.Diff(want, got)) } } } + +func TestConfigWarningHandler(t *testing.T) { + config := &Config{} + config.GroupVersion = &schema.GroupVersion{} + config.NegotiatedSerializer = &fakeNegotiatedSerializer{} + handlerNoContext := &fakeWarningHandler{} + handlerWithContext := &fakeWarningHandlerWithContext{} + + t.Run("none", func(t *testing.T) { + client, err := RESTClientForConfigAndClient(config, nil) + require.NoError(t, err) + assert.Nil(t, client.warningHandler) + }) + + t.Run("no-context", func(t *testing.T) { + config := CopyConfig(config) + handler := &fakeWarningHandlerWithLogging{} + config.WarningHandler = handler + client, err := RESTClientForConfigAndClient(config, nil) + require.NoError(t, err) + client.warningHandler.HandleWarningHeaderWithContext(context.Background(), 0, "", "message") + assert.Equal(t, []string{"message"}, handler.messages) + + }) + + t.Run("with-context", func(t *testing.T) { + config := CopyConfig(config) + config.WarningHandlerWithContext = handlerWithContext + client, err := RESTClientForConfigAndClient(config, nil) + require.NoError(t, err) + assert.Equal(t, handlerWithContext, client.warningHandler) + }) + + t.Run("both", func(t *testing.T) { + config := CopyConfig(config) + config.WarningHandler = handlerNoContext + config.WarningHandlerWithContext = handlerWithContext + client, err := RESTClientForConfigAndClient(config, nil) + require.NoError(t, err) + assert.NotNil(t, client.warningHandler) + assert.Equal(t, handlerWithContext, client.warningHandler) + }) +} diff --git a/rest/exec_test.go b/rest/exec_test.go index 5469c6d037..290b512c2a 100644 --- a/rest/exec_test.go +++ b/rest/exec_test.go @@ -26,12 +26,12 @@ import ( "testing" "github.com/google/go-cmp/cmp" - fuzz "github.com/google/gofuzz" "k8s.io/apimachinery/pkg/runtime" clientauthenticationapi "k8s.io/client-go/pkg/apis/clientauthentication" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "k8s.io/client-go/transport" "k8s.io/client-go/util/flowcontrol" + "sigs.k8s.io/randfill" ) func TestConfigToExecCluster(t *testing.T) { @@ -211,57 +211,60 @@ func TestConfigToExecCluster(t *testing.T) { func TestConfigToExecClusterRoundtrip(t *testing.T) { t.Parallel() - f := fuzz.New().NilChance(0.5).NumElements(1, 1) + f := randfill.New().NilChance(0.5).NumElements(1, 1) f.Funcs( - func(r *runtime.Codec, f fuzz.Continue) { + func(r *runtime.Codec, f randfill.Continue) { codec := &fakeCodec{} - f.Fuzz(codec) + f.Fill(codec) *r = codec }, - func(r *http.RoundTripper, f fuzz.Continue) { + func(r *http.RoundTripper, f randfill.Continue) { roundTripper := &fakeRoundTripper{} - f.Fuzz(roundTripper) + f.Fill(roundTripper) *r = roundTripper }, - func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) { + func(fn *func(http.RoundTripper) http.RoundTripper, f randfill.Continue) { *fn = fakeWrapperFunc }, - func(fn *transport.WrapperFunc, f fuzz.Continue) { + func(fn *transport.WrapperFunc, f randfill.Continue) { *fn = fakeWrapperFunc }, - func(r *runtime.NegotiatedSerializer, f fuzz.Continue) { + func(r *runtime.NegotiatedSerializer, f randfill.Continue) { serializer := &fakeNegotiatedSerializer{} - f.Fuzz(serializer) + f.Fill(serializer) *r = serializer }, - func(r *flowcontrol.RateLimiter, f fuzz.Continue) { + func(r *flowcontrol.RateLimiter, f randfill.Continue) { limiter := &fakeLimiter{} - f.Fuzz(limiter) + f.Fill(limiter) *r = limiter }, - func(h *WarningHandler, f fuzz.Continue) { + func(h *WarningHandler, f randfill.Continue) { *h = &fakeWarningHandler{} }, + func(h *WarningHandlerWithContext, f randfill.Continue) { + *h = &fakeWarningHandlerWithContext{} + }, // Authentication does not require fuzzer - func(r *AuthProviderConfigPersister, f fuzz.Continue) {}, - func(r *clientcmdapi.AuthProviderConfig, f fuzz.Continue) { + func(r *AuthProviderConfigPersister, f randfill.Continue) {}, + func(r *clientcmdapi.AuthProviderConfig, f randfill.Continue) { r.Config = map[string]string{} }, - func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f fuzz.Continue) { + func(r *func(ctx context.Context, network, addr string) (net.Conn, error), f randfill.Continue) { *r = fakeDialFunc }, - func(r *func(*http.Request) (*url.URL, error), f fuzz.Continue) { + func(r *func(*http.Request) (*url.URL, error), f randfill.Continue) { *r = fakeProxyFunc }, - func(r *runtime.Object, f fuzz.Continue) { + func(r *runtime.Object, f randfill.Continue) { unknown := &runtime.Unknown{} - f.Fuzz(unknown) + f.Fill(unknown) *r = unknown }, ) for i := 0; i < 100; i++ { expected := &Config{} - f.Fuzz(expected) + f.Fill(expected) // This is the list of known fields that this roundtrip doesn't care about. We should add new // fields to this list if we don't want to roundtrip them on exec cluster conversion. @@ -289,6 +292,7 @@ func TestConfigToExecClusterRoundtrip(t *testing.T) { expected.Burst = 0 expected.RateLimiter = nil expected.WarningHandler = nil + expected.WarningHandlerWithContext = nil expected.Timeout = 0 expected.Dial = nil @@ -343,9 +347,9 @@ func TestConfigToExecClusterRoundtrip(t *testing.T) { func TestExecClusterToConfigRoundtrip(t *testing.T) { t.Parallel() - f := fuzz.New().NilChance(0.5).NumElements(1, 1) + f := randfill.New().NilChance(0.5).NumElements(1, 1) f.Funcs( - func(r *runtime.Object, f fuzz.Continue) { + func(r *runtime.Object, f randfill.Continue) { // We don't expect the clientauthentication.Cluster.Config to show up in the Config that // comes back from the roundtrip, so just set it to nil. *r = nil @@ -353,7 +357,7 @@ func TestExecClusterToConfigRoundtrip(t *testing.T) { ) for i := 0; i < 100; i++ { expected := &clientauthenticationapi.Cluster{} - f.Fuzz(expected) + f.Fill(expected) // Manually set URLs so we don't get an error when parsing these during the roundtrip. if expected.Server != "" { diff --git a/rest/mock_backoff_manager_test.go b/rest/mock_backoff_manager_test.go new file mode 100644 index 0000000000..3cd4585ae9 --- /dev/null +++ b/rest/mock_backoff_manager_test.go @@ -0,0 +1,168 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by mockery v2.40.3. DO NOT EDIT. + +package rest + +import ( + mock "github.com/stretchr/testify/mock" + + time "time" + + url "net/url" +) + +// MockBackoffManager is an autogenerated mock type for the BackoffManager type +type MockBackoffManager struct { + mock.Mock +} + +type MockBackoffManager_Expecter struct { + mock *mock.Mock +} + +func (_m *MockBackoffManager) EXPECT() *MockBackoffManager_Expecter { + return &MockBackoffManager_Expecter{mock: &_m.Mock} +} + +// CalculateBackoff provides a mock function with given fields: actualURL +func (_m *MockBackoffManager) CalculateBackoff(actualURL *url.URL) time.Duration { + ret := _m.Called(actualURL) + + if len(ret) == 0 { + panic("no return value specified for CalculateBackoff") + } + + var r0 time.Duration + if rf, ok := ret.Get(0).(func(*url.URL) time.Duration); ok { + r0 = rf(actualURL) + } else { + r0 = ret.Get(0).(time.Duration) + } + + return r0 +} + +// MockBackoffManager_CalculateBackoff_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CalculateBackoff' +type MockBackoffManager_CalculateBackoff_Call struct { + *mock.Call +} + +// CalculateBackoff is a helper method to define mock.On call +// - actualURL *url.URL +func (_e *MockBackoffManager_Expecter) CalculateBackoff(actualURL interface{}) *MockBackoffManager_CalculateBackoff_Call { + return &MockBackoffManager_CalculateBackoff_Call{Call: _e.mock.On("CalculateBackoff", actualURL)} +} + +func (_c *MockBackoffManager_CalculateBackoff_Call) Run(run func(actualURL *url.URL)) *MockBackoffManager_CalculateBackoff_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(*url.URL)) + }) + return _c +} + +func (_c *MockBackoffManager_CalculateBackoff_Call) Return(_a0 time.Duration) *MockBackoffManager_CalculateBackoff_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockBackoffManager_CalculateBackoff_Call) RunAndReturn(run func(*url.URL) time.Duration) *MockBackoffManager_CalculateBackoff_Call { + _c.Call.Return(run) + return _c +} + +// Sleep provides a mock function with given fields: d +func (_m *MockBackoffManager) Sleep(d time.Duration) { + _m.Called(d) +} + +// MockBackoffManager_Sleep_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sleep' +type MockBackoffManager_Sleep_Call struct { + *mock.Call +} + +// Sleep is a helper method to define mock.On call +// - d time.Duration +func (_e *MockBackoffManager_Expecter) Sleep(d interface{}) *MockBackoffManager_Sleep_Call { + return &MockBackoffManager_Sleep_Call{Call: _e.mock.On("Sleep", d)} +} + +func (_c *MockBackoffManager_Sleep_Call) Run(run func(d time.Duration)) *MockBackoffManager_Sleep_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(time.Duration)) + }) + return _c +} + +func (_c *MockBackoffManager_Sleep_Call) Return() *MockBackoffManager_Sleep_Call { + _c.Call.Return() + return _c +} + +func (_c *MockBackoffManager_Sleep_Call) RunAndReturn(run func(time.Duration)) *MockBackoffManager_Sleep_Call { + _c.Call.Return(run) + return _c +} + +// UpdateBackoff provides a mock function with given fields: actualURL, err, responseCode +func (_m *MockBackoffManager) UpdateBackoff(actualURL *url.URL, err error, responseCode int) { + _m.Called(actualURL, err, responseCode) +} + +// MockBackoffManager_UpdateBackoff_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateBackoff' +type MockBackoffManager_UpdateBackoff_Call struct { + *mock.Call +} + +// UpdateBackoff is a helper method to define mock.On call +// - actualURL *url.URL +// - err error +// - responseCode int +func (_e *MockBackoffManager_Expecter) UpdateBackoff(actualURL interface{}, err interface{}, responseCode interface{}) *MockBackoffManager_UpdateBackoff_Call { + return &MockBackoffManager_UpdateBackoff_Call{Call: _e.mock.On("UpdateBackoff", actualURL, err, responseCode)} +} + +func (_c *MockBackoffManager_UpdateBackoff_Call) Run(run func(actualURL *url.URL, err error, responseCode int)) *MockBackoffManager_UpdateBackoff_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(*url.URL), args[1].(error), args[2].(int)) + }) + return _c +} + +func (_c *MockBackoffManager_UpdateBackoff_Call) Return() *MockBackoffManager_UpdateBackoff_Call { + _c.Call.Return() + return _c +} + +func (_c *MockBackoffManager_UpdateBackoff_Call) RunAndReturn(run func(*url.URL, error, int)) *MockBackoffManager_UpdateBackoff_Call { + _c.Call.Return(run) + return _c +} + +// NewMockBackoffManager creates a new instance of MockBackoffManager. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockBackoffManager(t interface { + mock.TestingT + Cleanup(func()) +}) *MockBackoffManager { + mock := &MockBackoffManager{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/rest/plugin.go b/rest/plugin.go index ae5cbdc2c4..f7a4e4f344 100644 --- a/rest/plugin.go +++ b/rest/plugin.go @@ -21,8 +21,6 @@ import ( "net/http" "sync" - "k8s.io/klog/v2" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" ) @@ -65,7 +63,10 @@ func RegisterAuthProviderPlugin(name string, plugin Factory) error { if _, found := plugins[name]; found { return fmt.Errorf("auth Provider Plugin %q was registered twice", name) } - klog.V(4).Infof("Registered Auth Provider Plugin %q", name) + // RegisterAuthProviderPlugin gets called during the init phase before + // logging is initialized and therefore should not emit logs. If you + // need this message for debugging something, then uncomment it. + // klog.V(4).Infof("Registered Auth Provider Plugin %q", name) plugins[name] = plugin return nil } diff --git a/rest/request.go b/rest/request.go index 0ec90ad188..1eb2f9b42a 100644 --- a/rest/request.go +++ b/rest/request.go @@ -54,7 +54,7 @@ import ( "k8s.io/utils/clock" ) -var ( +const ( // longThrottleLatency defines threshold for logging requests. All requests being // throttled (via the provided rateLimiter) for more than longThrottleLatency will // be logged. @@ -103,10 +103,10 @@ type Request struct { contentConfig ClientContentConfig contentTypeNotSet bool - warningHandler WarningHandler + warningHandler WarningHandlerWithContext rateLimiter flowcontrol.RateLimiter - backoff BackoffManager + backoff BackoffManagerWithContext timeout time.Duration maxRetries int @@ -136,7 +136,7 @@ type Request struct { // NewRequest creates a new request helper object for accessing runtime.Objects on a server. func NewRequest(c *RESTClient) *Request { - var backoff BackoffManager + var backoff BackoffManagerWithContext if c.createBackoffMgr != nil { backoff = c.createBackoffMgr() } @@ -259,20 +259,47 @@ func (r *Request) Resource(resource string) *Request { } // BackOff sets the request's backoff manager to the one specified, -// or defaults to the stub implementation if nil is provided +// or defaults to the stub implementation if nil is provided. +// +// Deprecated: BackoffManager.Sleep ignores the caller's context. Use BackOffWithContext and BackoffManagerWithContext instead. func (r *Request) BackOff(manager BackoffManager) *Request { if manager == nil { r.backoff = &NoBackoff{} return r } + r.backoff = &backoffManagerNopContext{BackoffManager: manager} + return r +} + +// BackOffWithContext sets the request's backoff manager to the one specified, +// or defaults to the stub implementation if nil is provided. +func (r *Request) BackOffWithContext(manager BackoffManagerWithContext) *Request { + if manager == nil { + r.backoff = &NoBackoff{} + return r + } + r.backoff = manager return r } // WarningHandler sets the handler this client uses when warning headers are encountered. -// If set to nil, this client will use the default warning handler (see SetDefaultWarningHandler). +// If set to nil, this client will use the default warning handler (see [SetDefaultWarningHandler]). +// +//logcheck:context // WarningHandlerWithContext should be used instead of WarningHandler in code which supports contextual logging. func (r *Request) WarningHandler(handler WarningHandler) *Request { + if handler == nil { + r.warningHandler = nil + return r + } + r.warningHandler = warningLoggerNopContext{l: handler} + return r +} + +// WarningHandlerWithContext sets the handler this client uses when warning headers are encountered. +// If set to nil, this client will use the default warning handler (see [SetDefaultWarningHandlerWithContext]). +func (r *Request) WarningHandlerWithContext(handler WarningHandlerWithContext) *Request { r.warningHandler = handler return r } @@ -649,21 +676,17 @@ func (r *Request) tryThrottleWithInfo(ctx context.Context, retryInfo string) err } latency := time.Since(now) - var message string - switch { - case len(retryInfo) > 0: - message = fmt.Sprintf("Waited for %v, %s - request: %s:%s", latency, retryInfo, r.verb, r.URL().String()) - default: - message = fmt.Sprintf("Waited for %v due to client-side throttling, not priority and fairness, request: %s:%s", latency, r.verb, r.URL().String()) - } - if latency > longThrottleLatency { - klog.V(3).Info(message) - } - if latency > extraLongThrottleLatency { - // If the rate limiter latency is very high, the log message should be printed at a higher log level, - // but we use a throttled logger to prevent spamming. - globalThrottledLogger.Infof("%s", message) + if retryInfo == "" { + retryInfo = "client-side throttling, not priority and fairness" + } + klog.FromContext(ctx).V(3).Info("Waited before sending request", "delay", latency, "reason", retryInfo, "verb", r.verb, "URL", r.URL()) + + if latency > extraLongThrottleLatency { + // If the rate limiter latency is very high, the log message should be printed at a higher log level, + // but we use a throttled logger to prevent spamming. + globalThrottledLogger.info(klog.FromContext(ctx), "Waited before sending request", "delay", latency, "reason", retryInfo, "verb", r.verb, "URL", r.URL()) + } } metrics.RateLimiterLatency.Observe(ctx, r.verb, r.finalURLTemplate(), latency) @@ -675,7 +698,7 @@ func (r *Request) tryThrottle(ctx context.Context) error { } type throttleSettings struct { - logLevel klog.Level + logLevel int minLogInterval time.Duration lastLogTime time.Time @@ -700,9 +723,9 @@ var globalThrottledLogger = &throttledLogger{ }, } -func (b *throttledLogger) attemptToLog() (klog.Level, bool) { +func (b *throttledLogger) attemptToLog(logger klog.Logger) (int, bool) { for _, setting := range b.settings { - if bool(klog.V(setting.logLevel).Enabled()) { + if bool(logger.V(setting.logLevel).Enabled()) { // Return early without write locking if possible. if func() bool { setting.lock.RLock() @@ -724,9 +747,9 @@ func (b *throttledLogger) attemptToLog() (klog.Level, bool) { // Infof will write a log message at each logLevel specified by the receiver's throttleSettings // as long as it hasn't written a log message more recently than minLogInterval. -func (b *throttledLogger) Infof(message string, args ...interface{}) { - if logLevel, ok := b.attemptToLog(); ok { - klog.V(logLevel).Infof(message, args...) +func (b *throttledLogger) info(logger klog.Logger, message string, kv ...any) { + if logLevel, ok := b.attemptToLog(logger); ok { + logger.V(logLevel).Info(message, kv...) } } @@ -739,7 +762,7 @@ func (r *Request) Watch(ctx context.Context) (watch.Interface, error) { func (r *Request) watchInternal(ctx context.Context) (watch.Interface, runtime.Decoder, error) { if r.body == nil { - logBody(ctx, 2, "Request Body", r.bodyBytes) + logBody(klog.FromContext(ctx), 2, "Request Body", r.bodyBytes) } // We specifically don't want to rate limit watches, so we @@ -776,7 +799,7 @@ func (r *Request) watchInternal(ctx context.Context) (watch.Interface, runtime.D resp, err := client.Do(req) retry.After(ctx, r, resp, err) if err == nil && resp.StatusCode == http.StatusOK { - return r.newStreamWatcher(resp) + return r.newStreamWatcher(ctx, resp) } done, transformErr := func() (bool, error) { @@ -898,7 +921,7 @@ func (r WatchListResult) Into(obj runtime.Object) error { // to see what parameters are currently required. func (r *Request) WatchList(ctx context.Context) WatchListResult { if r.body == nil { - logBody(ctx, 2, "Request Body", r.bodyBytes) + logBody(klog.FromContext(ctx), 2, "Request Body", r.bodyBytes) } if !clientfeatures.FeatureGates().Enabled(clientfeatures.WatchListClient) { @@ -969,23 +992,24 @@ func (r *Request) handleWatchList(ctx context.Context, w watch.Interface, negoti } } -func (r *Request) newStreamWatcher(resp *http.Response) (watch.Interface, runtime.Decoder, error) { +func (r *Request) newStreamWatcher(ctx context.Context, resp *http.Response) (watch.Interface, runtime.Decoder, error) { contentType := resp.Header.Get("Content-Type") mediaType, params, err := mime.ParseMediaType(contentType) if err != nil { - klog.V(4).Infof("Unexpected content type from the server: %q: %v", contentType, err) + klog.FromContext(ctx).V(4).Info("Unexpected content type from the server", "contentType", contentType, "err", err) } objectDecoder, streamingSerializer, framer, err := r.contentConfig.Negotiator.StreamDecoder(mediaType, params) if err != nil { return nil, nil, err } - handleWarnings(resp.Header, r.warningHandler) + handleWarnings(ctx, resp.Header, r.warningHandler) frameReader := framer.NewFrameReader(resp.Body) watchEventDecoder := streaming.NewDecoder(frameReader, streamingSerializer) - return watch.NewStreamWatcher( + return watch.NewStreamWatcherWithLogger( + klog.FromContext(ctx), restclientwatch.NewDecoder(watchEventDecoder, objectDecoder), // use 500 to indicate that the cause of the error is unknown - other error codes // are more specific to HTTP interactions, and set a reason @@ -1031,7 +1055,7 @@ func sanitize(req *Request, resp *http.Response, err error) (string, string) { // If we can, we return that as an error. Otherwise, we create an error that lists the http status and the content of the response. func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error) { if r.body == nil { - logBody(ctx, 2, "Request Body", r.bodyBytes) + logBody(klog.FromContext(ctx), 2, "Request Body", r.bodyBytes) } if r.err != nil { @@ -1067,7 +1091,7 @@ func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error) { switch { case (resp.StatusCode >= 200) && (resp.StatusCode < 300): - handleWarnings(resp.Header, r.warningHandler) + handleWarnings(ctx, resp.Header, r.warningHandler) return resp.Body, nil default: @@ -1175,7 +1199,7 @@ func (r *Request) request(ctx context.Context, fn func(*http.Request, *http.Resp }() if r.err != nil { - klog.V(4).Infof("Error in request: %v", r.err) + klog.FromContext(ctx).V(4).Info("Error in request", "err", r.err) return r.err } @@ -1267,8 +1291,9 @@ func (r *Request) request(ctx context.Context, fn func(*http.Request, *http.Resp // - If the server responds with a status: *errors.StatusError or *errors.UnexpectedObjectError // - http.Client.Do errors are returned directly. func (r *Request) Do(ctx context.Context) Result { + logger := klog.FromContext(ctx) if r.body == nil { - logBody(ctx, 2, "Request Body", r.bodyBytes) + logBody(logger, 2, "Request Body", r.bodyBytes) } var result Result @@ -1276,7 +1301,7 @@ func (r *Request) Do(ctx context.Context) Result { result = r.transformResponse(ctx, resp, req) }) if err != nil { - return Result{err: err} + return Result{err: err, logger: logger} } if result.err == nil || len(result.body) > 0 { metrics.ResponseSize.Observe(ctx, r.verb, r.URL().Host, float64(len(result.body))) @@ -1286,14 +1311,15 @@ func (r *Request) Do(ctx context.Context) Result { // DoRaw executes the request but does not process the response body. func (r *Request) DoRaw(ctx context.Context) ([]byte, error) { + logger := klog.FromContext(ctx) if r.body == nil { - logBody(ctx, 2, "Request Body", r.bodyBytes) + logBody(logger, 2, "Request Body", r.bodyBytes) } var result Result err := r.request(ctx, func(req *http.Request, resp *http.Response) { result.body, result.err = io.ReadAll(resp.Body) - logBody(ctx, 2, "Response Body", result.body) + logBody(logger, 2, "Response Body", result.body) if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent { result.err = r.transformUnstructuredResponseError(resp, req, result.body) } @@ -1309,6 +1335,7 @@ func (r *Request) DoRaw(ctx context.Context) ([]byte, error) { // transformResponse converts an API response into a structured API object func (r *Request) transformResponse(ctx context.Context, resp *http.Response, req *http.Request) Result { + logger := klog.FromContext(ctx) var body []byte if resp.Body != nil { data, err := io.ReadAll(resp.Body) @@ -1323,22 +1350,24 @@ func (r *Request) transformResponse(ctx context.Context, resp *http.Response, re // 2. Apiserver sends back the headers and then part of the body // 3. Apiserver closes connection. // 4. client-go should catch this and return an error. - klog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err) + logger.V(2).Info("Stream error when reading response body, may be caused by closed connection", "err", err) streamErr := fmt.Errorf("stream error when reading response body, may be caused by closed connection. Please retry. Original error: %w", err) return Result{ - err: streamErr, + err: streamErr, + logger: logger, } default: - klog.Errorf("Unexpected error when reading response body: %v", err) + logger.Error(err, "Unexpected error when reading response body") unexpectedErr := fmt.Errorf("unexpected error when reading response body. Please retry. Original error: %w", err) return Result{ - err: unexpectedErr, + err: unexpectedErr, + logger: logger, } } } // Call depth is tricky. This one is okay for Do and DoRaw. - logBody(ctx, 7, "Response Body", body) + logBody(logger, 7, "Response Body", body) // verify the content type is accurate var decoder runtime.Decoder @@ -1350,7 +1379,7 @@ func (r *Request) transformResponse(ctx context.Context, resp *http.Response, re var err error mediaType, params, err := mime.ParseMediaType(contentType) if err != nil { - return Result{err: errors.NewInternalError(err)} + return Result{err: errors.NewInternalError(err), logger: logger} } decoder, err = r.contentConfig.Negotiator.Decoder(mediaType, params) if err != nil { @@ -1359,13 +1388,14 @@ func (r *Request) transformResponse(ctx context.Context, resp *http.Response, re case resp.StatusCode == http.StatusSwitchingProtocols: // no-op, we've been upgraded case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent: - return Result{err: r.transformUnstructuredResponseError(resp, req, body)} + return Result{err: r.transformUnstructuredResponseError(resp, req, body), logger: logger} } return Result{ body: body, contentType: contentType, statusCode: resp.StatusCode, - warnings: handleWarnings(resp.Header, r.warningHandler), + warnings: handleWarnings(ctx, resp.Header, r.warningHandler), + logger: logger, } } } @@ -1384,7 +1414,8 @@ func (r *Request) transformResponse(ctx context.Context, resp *http.Response, re statusCode: resp.StatusCode, decoder: decoder, err: err, - warnings: handleWarnings(resp.Header, r.warningHandler), + warnings: handleWarnings(ctx, resp.Header, r.warningHandler), + logger: logger, } } @@ -1393,7 +1424,8 @@ func (r *Request) transformResponse(ctx context.Context, resp *http.Response, re contentType: contentType, statusCode: resp.StatusCode, decoder: decoder, - warnings: handleWarnings(resp.Header, r.warningHandler), + warnings: handleWarnings(ctx, resp.Header, r.warningHandler), + logger: logger, } } @@ -1421,8 +1453,7 @@ func truncateBody(logger klog.Logger, body string) string { // whether the body is printable. // // It needs to be called by all functions which send or receive the data. -func logBody(ctx context.Context, callDepth int, prefix string, body []byte) { - logger := klog.FromContext(ctx) +func logBody(logger klog.Logger, callDepth int, prefix string, body []byte) { if loggerV := logger.V(8); loggerV.Enabled() { loggerV := loggerV.WithCallDepth(callDepth) if bytes.IndexFunc(body, func(r rune) bool { @@ -1524,6 +1555,7 @@ type Result struct { contentType string err error statusCode int + logger klog.Logger decoder runtime.Decoder } @@ -1629,7 +1661,7 @@ func (r Result) Error() error { // to be backwards compatible with old servers that do not return a version, default to "v1" out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil) if err != nil { - klog.V(5).Infof("body was not decodable (unable to check for Status): %v", err) + r.logger.V(5).Info("Body was not decodable (unable to check for Status)", "err", err) return r.err } switch t := out.(type) { diff --git a/rest/request_test.go b/rest/request_test.go index 186c5a35b9..fd64dcb028 100644 --- a/rest/request_test.go +++ b/rest/request_test.go @@ -1489,6 +1489,7 @@ func TestDoRequestNewWay(t *testing.T) { // This test assumes that the client implementation backs off exponentially, for an individual request. func TestBackoffLifecycle(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) count := 0 testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { count++ @@ -1508,22 +1509,30 @@ func TestBackoffLifecycle(t *testing.T) { seconds := []int{0, 1, 2, 4, 8, 0, 1, 2, 4, 0} request := c.Verb("POST").Prefix("backofftest").Suffix("abc") clock := testingclock.FakeClock{} - request.backoff = &URLBackoff{ - // Use a fake backoff here to avoid flakes and speed the test up. - Backoff: flowcontrol.NewFakeBackOff( - time.Duration(1)*time.Second, - time.Duration(200)*time.Second, - &clock, - )} + request.backoff = stepClockDuringSleep{ + BackoffManagerWithContext: &URLBackoff{ + // Use a fake backoff here to avoid flakes and speed the test up. + Backoff: flowcontrol.NewFakeBackOff( + time.Duration(1)*time.Second, + time.Duration(200)*time.Second, + &clock, + ), + }, + clock: &clock, + } for _, sec := range seconds { - thisBackoff := request.backoff.CalculateBackoff(request.URL()) + thisBackoff := request.backoff.CalculateBackoffWithContext(ctx, request.URL()) t.Logf("Current backoff %v", thisBackoff) if thisBackoff != time.Duration(sec)*time.Second { t.Errorf("Backoff is %v instead of %v", thisBackoff, sec) } + + // This relies on advancing the fake clock by exactly the duration + // that SleepWithContext is being called for while DoRaw is executing. + // stepClockDuringSleep.SleepWithContext ensures that this happens. now := clock.Now() - request.DoRaw(context.Background()) + request.DoRaw(ctx) elapsed := clock.Since(now) if clock.Since(now) != thisBackoff { t.Errorf("CalculatedBackoff not honored by clock: Expected time of %v, but got %v ", thisBackoff, elapsed) @@ -1531,18 +1540,51 @@ func TestBackoffLifecycle(t *testing.T) { } } +type stepClockDuringSleep struct { + BackoffManagerWithContext + clock *testingclock.FakeClock +} + +// SleepWithContext wraps the underlying SleepWithContext and ensures that once +// that is sleeping, the fake clock advances by exactly the duration that +// it is sleeping for. +func (s stepClockDuringSleep) SleepWithContext(ctx context.Context, d time.Duration) { + // This code is sensitive to both the implementation of + // URLBackoff.SleepWithContext and of FakeClock.NewTimer: + // - SleepWithContext must be a no-op when the duration is zero + // => no need to step the fake clock + // - SleepWithContext must use FakeClock.NewTimer, not FakeClock.Sleep + // because the latter would advance time itself + if d != 0 { + go func() { + // Poll until the caller is sleeping. + for { + if s.clock.HasWaiters() { + s.clock.Step(d) + return + } + if ctx.Err() != nil { + return + } + time.Sleep(time.Millisecond) + } + }() + } + s.BackoffManagerWithContext.SleepWithContext(ctx, d) +} + type testBackoffManager struct { sleeps []time.Duration } -func (b *testBackoffManager) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) { +func (b *testBackoffManager) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) { } -func (b *testBackoffManager) CalculateBackoff(actualUrl *url.URL) time.Duration { +func (b *testBackoffManager) CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration { return time.Duration(0) } -func (b *testBackoffManager) Sleep(d time.Duration) { +func (b *testBackoffManager) SleepWithContext(ctx context.Context, d time.Duration) { b.sleeps = append(b.sleeps, d) } @@ -1568,7 +1610,7 @@ func TestCheckRetryClosesBody(t *testing.T) { expectedSleeps := []time.Duration{0, time.Second, time.Second, time.Second, time.Second} c := testRESTClient(t, testServer) - c.createBackoffMgr = func() BackoffManager { return backoff } + c.createBackoffMgr = func() BackoffManagerWithContext { return backoff } _, err := c.Verb("POST"). Prefix("foo", "bar"). Suffix("baz"). @@ -2434,6 +2476,7 @@ func TestRequestPreflightCheck(t *testing.T) { } func TestThrottledLogger(t *testing.T) { + logger := klog.Background() now := time.Now() oldClock := globalThrottledLogger.clock defer func() { @@ -2448,7 +2491,7 @@ func TestThrottledLogger(t *testing.T) { wg.Add(10) for j := 0; j < 10; j++ { go func() { - if _, ok := globalThrottledLogger.attemptToLog(); ok { + if _, ok := globalThrottledLogger.attemptToLog(logger); ok { logMessages++ } wg.Done() @@ -2612,6 +2655,8 @@ type noSleepBackOff struct { func (n *noSleepBackOff) Sleep(d time.Duration) {} +func (n *noSleepBackOff) SleepWithContext(ctx context.Context, d time.Duration) {} + func TestRequestWithRetry(t *testing.T) { tests := []struct { name string @@ -2997,7 +3042,6 @@ const retryTestKey retryTestKeyType = iota // metric calls are invoked appropriately in right order. type withRateLimiterBackoffManagerAndMetrics struct { flowcontrol.RateLimiter - *NoBackoff metrics.ResultMetric calculateBackoffSeq int64 calculateBackoffFn func(i int64) time.Duration @@ -3013,7 +3057,7 @@ func (lb *withRateLimiterBackoffManagerAndMetrics) Wait(ctx context.Context) err return nil } -func (lb *withRateLimiterBackoffManagerAndMetrics) CalculateBackoff(actualUrl *url.URL) time.Duration { +func (lb *withRateLimiterBackoffManagerAndMetrics) CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration { lb.invokeOrderGot = append(lb.invokeOrderGot, "BackoffManager.CalculateBackoff") waitFor := lb.calculateBackoffFn(lb.calculateBackoffSeq) @@ -3021,11 +3065,11 @@ func (lb *withRateLimiterBackoffManagerAndMetrics) CalculateBackoff(actualUrl *u return waitFor } -func (lb *withRateLimiterBackoffManagerAndMetrics) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) { +func (lb *withRateLimiterBackoffManagerAndMetrics) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) { lb.invokeOrderGot = append(lb.invokeOrderGot, "BackoffManager.UpdateBackoff") } -func (lb *withRateLimiterBackoffManagerAndMetrics) Sleep(d time.Duration) { +func (lb *withRateLimiterBackoffManagerAndMetrics) SleepWithContext(ctx context.Context, d time.Duration) { lb.invokeOrderGot = append(lb.invokeOrderGot, "BackoffManager.Sleep") lb.sleepsGot = append(lb.sleepsGot, d.String()) } @@ -3206,7 +3250,6 @@ func testRetryWithRateLimiterBackoffAndMetrics(t *testing.T, key string, doFunc t.Run(test.name, func(t *testing.T) { interceptor := &withRateLimiterBackoffManagerAndMetrics{ RateLimiter: flowcontrol.NewFakeAlwaysRateLimiter(), - NoBackoff: &NoBackoff{}, calculateBackoffFn: test.calculateBackoffFn, } @@ -4066,15 +4109,24 @@ func TestRequestLogging(t *testing.T) { testcases := map[string]struct { v int body any + response *http.Response expectedOutput string }{ "no-output": { v: 7, body: []byte("ping"), + response: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader("pong")), + }, }, "output": { v: 8, body: []byte("ping"), + response: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader("pong")), + }, expectedOutput: `] "Request Body" logger="TestLogger" body="ping" ] "Response Body" logger="TestLogger" body="pong" `, @@ -4082,6 +4134,10 @@ func TestRequestLogging(t *testing.T) { "io-reader": { v: 8, body: strings.NewReader("ping"), + response: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader("pong")), + }, // Cannot log the request body! expectedOutput: `] "Response Body" logger="TestLogger" body="pong" `, @@ -4089,13 +4145,38 @@ func TestRequestLogging(t *testing.T) { "truncate": { v: 8, body: []byte(strings.Repeat("a", 2000)), + response: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader("pong")), + }, expectedOutput: fmt.Sprintf(`] "Request Body" logger="TestLogger" body="%s [truncated 976 chars]" ] "Response Body" logger="TestLogger" body="pong" `, strings.Repeat("a", 1024)), }, + "warnings": { + v: 8, + body: []byte("ping"), + response: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Warning": []string{ + `299 request-test "warning 1"`, + `299 request-test-2 "warning 2"`, + `300 request-test-3 "ignore code 300"`, + }, + }, + Body: io.NopCloser(strings.NewReader("pong")), + }, + expectedOutput: `] "Request Body" logger="TestLogger" body="ping" +] "Response Body" logger="TestLogger" body="pong" +warnings.go] "Warning: warning 1" logger="TestLogger" +warnings.go] "Warning: warning 2" logger="TestLogger" +`, + }, } for name, tc := range testcases { + //nolint:logcheck // Intentionally testing with plain klog here. t.Run(name, func(t *testing.T) { state := klog.CaptureState() defer state.Restore() @@ -4106,12 +4187,10 @@ func TestRequestLogging(t *testing.T) { var fs flag.FlagSet klog.InitFlags(&fs) require.NoError(t, fs.Set("v", fmt.Sprintf("%d", tc.v)), "set verbosity") + require.NoError(t, fs.Set("one_output", "true"), "set one_output") client := clientForFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(strings.NewReader("pong")), - }, nil + return tc.response, nil }) req := NewRequestWithClient(nil, "", defaultContentConfig(), client). @@ -4128,11 +4207,49 @@ func TestRequestLogging(t *testing.T) { // Compare log output: // - strip date/time/pid from each line (fixed length header) // - replace with the actual call location + // - strip line number from warnings.go (might change) state.Restore() expectedOutput := strings.ReplaceAll(tc.expectedOutput, "", fmt.Sprintf("%s:%d", path.Base(file), line+1)) actualOutput := buffer.String() actualOutput = regexp.MustCompile(`(?m)^.{30}`).ReplaceAllString(actualOutput, "") + actualOutput = regexp.MustCompile(`(?m)^warnings\.go:\d+`).ReplaceAllString(actualOutput, "warnings.go") assert.Equal(t, expectedOutput, actualOutput) }) } } + +func TestRequestWarningHandler(t *testing.T) { + t.Run("no-context", func(t *testing.T) { + request := &Request{} + handler := &fakeWarningHandlerWithLogging{} + //nolint:logcheck + assert.Equal(t, request, request.WarningHandler(handler)) + assert.NotNil(t, request.warningHandler) + request.warningHandler.HandleWarningHeaderWithContext(context.Background(), 0, "", "message") + assert.Equal(t, []string{"message"}, handler.messages) + }) + + t.Run("with-context", func(t *testing.T) { + request := &Request{} + handler := &fakeWarningHandlerWithContext{} + assert.Equal(t, request, request.WarningHandlerWithContext(handler)) + assert.Equal(t, request.warningHandler, handler) + }) + + t.Run("nil-no-context", func(t *testing.T) { + request := &Request{ + warningHandler: &fakeWarningHandlerWithContext{}, + } + //nolint:logcheck + assert.Equal(t, request, request.WarningHandler(nil)) + assert.Nil(t, request.warningHandler) + }) + + t.Run("nil-with-context", func(t *testing.T) { + request := &Request{ + warningHandler: &fakeWarningHandlerWithContext{}, + } + assert.Equal(t, request, request.WarningHandlerWithContext(nil)) + assert.Nil(t, request.warningHandler) + }) +} diff --git a/rest/urlbackoff.go b/rest/urlbackoff.go index 2f9962d7e5..5b7b4e216e 100644 --- a/rest/urlbackoff.go +++ b/rest/urlbackoff.go @@ -17,6 +17,8 @@ limitations under the License. package rest import ( + "context" + "fmt" "net/url" "time" @@ -32,12 +34,24 @@ import ( var serverIsOverloadedSet = sets.NewInt(429) var maxResponseCode = 499 +//go:generate mockery + +// Deprecated: BackoffManager.Sleep ignores the caller's context. Use BackoffManagerWithContext instead. type BackoffManager interface { - UpdateBackoff(actualUrl *url.URL, err error, responseCode int) - CalculateBackoff(actualUrl *url.URL) time.Duration + UpdateBackoff(actualURL *url.URL, err error, responseCode int) + CalculateBackoff(actualURL *url.URL) time.Duration Sleep(d time.Duration) } +type BackoffManagerWithContext interface { + UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) + CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration + SleepWithContext(ctx context.Context, d time.Duration) +} + +var _ BackoffManager = &URLBackoff{} +var _ BackoffManagerWithContext = &URLBackoff{} + // URLBackoff struct implements the semantics on top of Backoff which // we need for URL specific exponential backoff. type URLBackoff struct { @@ -49,11 +63,19 @@ type URLBackoff struct { type NoBackoff struct { } -func (n *NoBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) { +func (n *NoBackoff) UpdateBackoff(actualURL *url.URL, err error, responseCode int) { // do nothing. } -func (n *NoBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration { +func (n *NoBackoff) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) { + // do nothing. +} + +func (n *NoBackoff) CalculateBackoff(actualURL *url.URL) time.Duration { + return 0 * time.Second +} + +func (n *NoBackoff) CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration { return 0 * time.Second } @@ -61,10 +83,21 @@ func (n *NoBackoff) Sleep(d time.Duration) { time.Sleep(d) } +func (n *NoBackoff) SleepWithContext(ctx context.Context, d time.Duration) { + if d == 0 { + return + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + case <-t.C: + } +} + // Disable makes the backoff trivial, i.e., sets it to zero. This might be used // by tests which want to run 1000s of mock requests without slowing down. func (b *URLBackoff) Disable() { - klog.V(4).Infof("Disabling backoff strategy") b.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second) } @@ -76,32 +109,74 @@ func (b *URLBackoff) baseUrlKey(rawurl *url.URL) string { // in the future. host, err := url.Parse(rawurl.String()) if err != nil { - klog.V(4).Infof("Error extracting url: %v", rawurl) - panic("bad url!") + panic(fmt.Sprintf("Error parsing bad URL %q: %v", rawurl, err)) } return host.Host } // UpdateBackoff updates backoff metadata -func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) { +func (b *URLBackoff) UpdateBackoff(actualURL *url.URL, err error, responseCode int) { + b.UpdateBackoffWithContext(context.Background(), actualURL, err, responseCode) +} + +// UpdateBackoffWithContext updates backoff metadata +func (b *URLBackoff) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) { // range for retry counts that we store is [0,13] if responseCode > maxResponseCode || serverIsOverloadedSet.Has(responseCode) { - b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now()) + b.Backoff.Next(b.baseUrlKey(actualURL), b.Backoff.Clock.Now()) return } else if responseCode >= 300 || err != nil { - klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) + klog.FromContext(ctx).V(4).Info("Client is returning errors", "code", responseCode, "err", err) } //If we got this far, there is no backoff required for this URL anymore. - b.Backoff.Reset(b.baseUrlKey(actualUrl)) + b.Backoff.Reset(b.baseUrlKey(actualURL)) } // CalculateBackoff takes a url and back's off exponentially, // based on its knowledge of existing failures. -func (b *URLBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration { - return b.Backoff.Get(b.baseUrlKey(actualUrl)) +func (b *URLBackoff) CalculateBackoff(actualURL *url.URL) time.Duration { + return b.Backoff.Get(b.baseUrlKey(actualURL)) +} + +// CalculateBackoffWithContext takes a url and back's off exponentially, +// based on its knowledge of existing failures. +func (b *URLBackoff) CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration { + return b.Backoff.Get(b.baseUrlKey(actualURL)) } func (b *URLBackoff) Sleep(d time.Duration) { b.Backoff.Clock.Sleep(d) } + +func (b *URLBackoff) SleepWithContext(ctx context.Context, d time.Duration) { + if d == 0 { + return + } + t := b.Backoff.Clock.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + case <-t.C(): + } +} + +// backoffManagerNopContext wraps a BackoffManager and adds the *WithContext methods. +type backoffManagerNopContext struct { + BackoffManager +} + +var _ BackoffManager = &backoffManagerNopContext{} +var _ BackoffManagerWithContext = &backoffManagerNopContext{} + +func (b *backoffManagerNopContext) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) { + b.UpdateBackoff(actualURL, err, responseCode) +} + +func (b *backoffManagerNopContext) CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration { + return b.CalculateBackoff(actualURL) +} + +func (b *backoffManagerNopContext) SleepWithContext(ctx context.Context, d time.Duration) { + b.Sleep(d) +} diff --git a/rest/urlbackoff_test.go b/rest/urlbackoff_test.go index c5f439238d..b80b721d97 100644 --- a/rest/urlbackoff_test.go +++ b/rest/urlbackoff_test.go @@ -17,10 +17,14 @@ limitations under the License. package rest import ( + "context" + "errors" "net/url" "testing" "time" + "github.com/stretchr/testify/assert" + "k8s.io/client-go/util/flowcontrol" ) @@ -77,3 +81,38 @@ func TestURLBackoffFunctionality(t *testing.T) { t.Errorf("The final return code %v should have resulted in a backoff ! ", returnCodes[7]) } } + +func TestBackoffManagerNopContext(t *testing.T) { + mock := NewMockBackoffManager(t) + + sleepDuration := 42 * time.Second + mock.On("Sleep", sleepDuration).Return() + url := &url.URL{} + mock.On("CalculateBackoff", url).Return(time.Second) + err := errors.New("fake error") + responseCode := 404 + mock.On("UpdateBackoff", url, err, responseCode).Return() + + ctx := context.Background() + wrapper := backoffManagerNopContext{BackoffManager: mock} + wrapper.SleepWithContext(ctx, sleepDuration) + wrapper.CalculateBackoffWithContext(ctx, url) + wrapper.UpdateBackoffWithContext(ctx, url, err, responseCode) +} + +func TestNoBackoff(t *testing.T) { + var backoff NoBackoff + assert.Equal(t, 0*time.Second, backoff.CalculateBackoff(nil)) + assert.Equal(t, 0*time.Second, backoff.CalculateBackoffWithContext(context.Background(), nil)) + + start := time.Now() + backoff.Sleep(0 * time.Second) + assert.WithinDuration(t, start, time.Now(), time.Minute /* pretty generous, but we don't want to flake */, time.Since(start), "backoff.Sleep") + + // Cancel right away to prevent sleeping. + ctx, cancel := context.WithCancel(context.Background()) + cancel() + start = time.Now() + backoff.SleepWithContext(ctx, 10*time.Minute) + assert.WithinDuration(t, start, time.Now(), time.Minute /* pretty generous, but we don't want to flake */, time.Since(start), "backoff.SleepWithContext") +} diff --git a/rest/warnings.go b/rest/warnings.go index ad493659f2..713b2d64d6 100644 --- a/rest/warnings.go +++ b/rest/warnings.go @@ -17,6 +17,7 @@ limitations under the License. package rest import ( + "context" "fmt" "io" "net/http" @@ -33,8 +34,15 @@ type WarningHandler interface { HandleWarningHeader(code int, agent string, text string) } +// WarningHandlerWithContext is an interface for handling warning headers with +// support for contextual logging. +type WarningHandlerWithContext interface { + // HandleWarningHeaderWithContext is called with the warn code, agent, and text when a warning header is countered. + HandleWarningHeaderWithContext(ctx context.Context, code int, agent string, text string) +} + var ( - defaultWarningHandler WarningHandler = WarningLogger{} + defaultWarningHandler WarningHandlerWithContext = WarningLogger{} defaultWarningHandlerLock sync.RWMutex ) @@ -43,33 +51,68 @@ var ( // - NoWarnings suppresses warnings. // - WarningLogger logs warnings. // - NewWarningWriter() outputs warnings to the provided writer. +// +// logcheck:context // SetDefaultWarningHandlerWithContext should be used instead of SetDefaultWarningHandler in code which supports contextual logging. func SetDefaultWarningHandler(l WarningHandler) { + if l == nil { + SetDefaultWarningHandlerWithContext(nil) + return + } + SetDefaultWarningHandlerWithContext(warningLoggerNopContext{l: l}) +} + +// SetDefaultWarningHandlerWithContext is a variant of [SetDefaultWarningHandler] which supports contextual logging. +func SetDefaultWarningHandlerWithContext(l WarningHandlerWithContext) { defaultWarningHandlerLock.Lock() defer defaultWarningHandlerLock.Unlock() defaultWarningHandler = l } -func getDefaultWarningHandler() WarningHandler { + +func getDefaultWarningHandler() WarningHandlerWithContext { defaultWarningHandlerLock.RLock() defer defaultWarningHandlerLock.RUnlock() l := defaultWarningHandler return l } -// NoWarnings is an implementation of WarningHandler that suppresses warnings. +type warningLoggerNopContext struct { + l WarningHandler +} + +func (w warningLoggerNopContext) HandleWarningHeaderWithContext(_ context.Context, code int, agent string, message string) { + w.l.HandleWarningHeader(code, agent, message) +} + +// NoWarnings is an implementation of [WarningHandler] and [WarningHandlerWithContext] that suppresses warnings. type NoWarnings struct{} func (NoWarnings) HandleWarningHeader(code int, agent string, message string) {} +func (NoWarnings) HandleWarningHeaderWithContext(ctx context.Context, code int, agent string, message string) { +} + +var _ WarningHandler = NoWarnings{} +var _ WarningHandlerWithContext = NoWarnings{} -// WarningLogger is an implementation of WarningHandler that logs code 299 warnings +// WarningLogger is an implementation of [WarningHandler] and [WarningHandlerWithContext] that logs code 299 warnings type WarningLogger struct{} func (WarningLogger) HandleWarningHeader(code int, agent string, message string) { if code != 299 || len(message) == 0 { return } - klog.Warning(message) + klog.Background().Info("Warning: " + message) } +func (WarningLogger) HandleWarningHeaderWithContext(ctx context.Context, code int, agent string, message string) { + if code != 299 || len(message) == 0 { + return + } + klog.FromContext(ctx).Info("Warning: " + message) +} + +var _ WarningHandler = WarningLogger{} +var _ WarningHandlerWithContext = WarningLogger{} + type warningWriter struct { // out is the writer to output warnings to out io.Writer @@ -134,14 +177,14 @@ func (w *warningWriter) WarningCount() int { return w.writtenCount } -func handleWarnings(headers http.Header, handler WarningHandler) []net.WarningHeader { +func handleWarnings(ctx context.Context, headers http.Header, handler WarningHandlerWithContext) []net.WarningHeader { if handler == nil { handler = getDefaultWarningHandler() } warnings, _ := net.ParseWarningHeaders(headers["Warning"]) for _, warning := range warnings { - handler.HandleWarningHeader(warning.Code, warning.Agent, warning.Text) + handler.HandleWarningHeaderWithContext(ctx, warning.Code, warning.Agent, warning.Text) } return warnings } diff --git a/rest/warnings_test.go b/rest/warnings_test.go new file mode 100644 index 0000000000..d74964310d --- /dev/null +++ b/rest/warnings_test.go @@ -0,0 +1,57 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package rest + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDefaultWarningHandler(t *testing.T) { + t.Run("default", func(t *testing.T) { + assert.IsType(t, WarningHandlerWithContext(WarningLogger{}), getDefaultWarningHandler()) + }) + + deferRestore := func(t *testing.T) { + handler := getDefaultWarningHandler() + t.Cleanup(func() { + SetDefaultWarningHandlerWithContext(handler) + }) + } + + t.Run("no-context", func(t *testing.T) { + deferRestore(t) + handler := &fakeWarningHandlerWithLogging{} + //nolint:logcheck + SetDefaultWarningHandler(handler) + getDefaultWarningHandler().HandleWarningHeaderWithContext(context.Background(), 0, "", "message") + assert.Equal(t, []string{"message"}, handler.messages) + SetDefaultWarningHandler(nil) + assert.Nil(t, getDefaultWarningHandler()) + }) + + t.Run("with-context", func(t *testing.T) { + deferRestore(t) + handler := &fakeWarningHandlerWithContext{} + SetDefaultWarningHandlerWithContext(handler) + assert.Equal(t, handler, getDefaultWarningHandler()) + SetDefaultWarningHandlerWithContext(nil) + assert.Nil(t, getDefaultWarningHandler()) + }) +} diff --git a/rest/with_retry.go b/rest/with_retry.go index eaaadc6a4c..e211c39d41 100644 --- a/rest/with_retry.go +++ b/rest/with_retry.go @@ -209,18 +209,18 @@ func (r *withRetry) Before(ctx context.Context, request *Request) error { // we do a backoff sleep before the first attempt is made, // (preserving current behavior). if request.backoff != nil { - request.backoff.Sleep(request.backoff.CalculateBackoff(url)) + request.backoff.SleepWithContext(ctx, request.backoff.CalculateBackoffWithContext(ctx, url)) } return nil } // if we are here, we have made attempt(s) at least once before. if request.backoff != nil { - delay := request.backoff.CalculateBackoff(url) + delay := request.backoff.CalculateBackoffWithContext(ctx, url) if r.retryAfter.Wait > delay { delay = r.retryAfter.Wait } - request.backoff.Sleep(delay) + request.backoff.SleepWithContext(ctx, delay) } // We are retrying the request that we already send to @@ -231,7 +231,7 @@ func (r *withRetry) Before(ctx context.Context, request *Request) error { return err } - klog.V(4).Infof("Got a Retry-After %s response for attempt %d to %v", r.retryAfter.Wait, r.retryAfter.Attempt, request.URL().String()) + klog.FromContext(ctx).V(4).Info("Got a Retry-After response", "delay", r.retryAfter.Wait, "attempt", r.retryAfter.Attempt, "url", request.URL()) return nil } @@ -258,9 +258,9 @@ func (r *withRetry) After(ctx context.Context, request *Request, resp *http.Resp if request.c.base != nil { if err != nil { - request.backoff.UpdateBackoff(request.URL(), err, 0) + request.backoff.UpdateBackoffWithContext(ctx, request.URL(), err, 0) } else { - request.backoff.UpdateBackoff(request.URL(), err, resp.StatusCode) + request.backoff.UpdateBackoffWithContext(ctx, request.URL(), err, resp.StatusCode) } } } diff --git a/scale/doc.go b/scale/doc.go index b6fa3f5f20..59fd39146c 100644 --- a/scale/doc.go +++ b/scale/doc.go @@ -18,4 +18,4 @@ limitations under the License. // and updating Scale for any resource which implements the `scale` subresource, // as long as that subresource operates on a version of scale convertable to // autoscaling.Scale. -package scale // import "k8s.io/client-go/scale" +package scale diff --git a/scale/scheme/appsint/doc.go b/scale/scheme/appsint/doc.go index 735efb953c..16f29e2afe 100644 --- a/scale/scheme/appsint/doc.go +++ b/scale/scheme/appsint/doc.go @@ -19,4 +19,4 @@ limitations under the License. // It doesn't have any of its own types -- it's just necessary to // get the expected behavior out of runtime.Scheme.ConvertToVersion // and associated methods. -package appsint // import "k8s.io/client-go/scale/scheme/appsint" +package appsint diff --git a/scale/scheme/appsv1beta1/doc.go b/scale/scheme/appsv1beta1/doc.go index aea95e2e4c..b9e8cf63d6 100644 --- a/scale/scheme/appsv1beta1/doc.go +++ b/scale/scheme/appsv1beta1/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:conversion-gen=k8s.io/client-go/scale/scheme // +k8s:conversion-gen-external-types=k8s.io/api/apps/v1beta1 -package appsv1beta1 // import "k8s.io/client-go/scale/scheme/appsv1beta1" +package appsv1beta1 diff --git a/scale/scheme/appsv1beta2/doc.go b/scale/scheme/appsv1beta2/doc.go index d1ae2118e9..b224c4da62 100644 --- a/scale/scheme/appsv1beta2/doc.go +++ b/scale/scheme/appsv1beta2/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:conversion-gen=k8s.io/client-go/scale/scheme // +k8s:conversion-gen-external-types=k8s.io/api/apps/v1beta2 -package appsv1beta2 // import "k8s.io/client-go/scale/scheme/appsv1beta2" +package appsv1beta2 diff --git a/scale/scheme/autoscalingv1/doc.go b/scale/scheme/autoscalingv1/doc.go index 25f23d2d8c..2741a8a457 100644 --- a/scale/scheme/autoscalingv1/doc.go +++ b/scale/scheme/autoscalingv1/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:conversion-gen=k8s.io/client-go/scale/scheme // +k8s:conversion-gen-external-types=k8s.io/api/autoscaling/v1 -package autoscalingv1 // import "k8s.io/client-go/scale/scheme/autoscalingv1" +package autoscalingv1 diff --git a/scale/scheme/doc.go b/scale/scheme/doc.go index 248b448a59..0203d6d5a2 100644 --- a/scale/scheme/doc.go +++ b/scale/scheme/doc.go @@ -19,4 +19,4 @@ limitations under the License. // Package scheme contains a runtime.Scheme to be used for serializing // and deserializing different versions of Scale, and for converting // in between them. -package scheme // import "k8s.io/client-go/scale/scheme" +package scheme diff --git a/scale/scheme/extensionsint/doc.go b/scale/scheme/extensionsint/doc.go index dedff2d704..9aaac60861 100644 --- a/scale/scheme/extensionsint/doc.go +++ b/scale/scheme/extensionsint/doc.go @@ -19,4 +19,4 @@ limitations under the License. // It doesn't have any of its own types -- it's just necessary to // get the expected behavior out of runtime.Scheme.ConvertToVersion // and associated methods. -package extensionsint // import "k8s.io/client-go/scale/scheme/extensionsint" +package extensionsint diff --git a/scale/scheme/extensionsv1beta1/doc.go b/scale/scheme/extensionsv1beta1/doc.go index de633889a1..b5d24f50b7 100644 --- a/scale/scheme/extensionsv1beta1/doc.go +++ b/scale/scheme/extensionsv1beta1/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:conversion-gen=k8s.io/client-go/scale/scheme // +k8s:conversion-gen-external-types=k8s.io/api/extensions/v1beta1 -package extensionsv1beta1 // import "k8s.io/client-go/scale/scheme/extensionsv1beta1" +package extensionsv1beta1 diff --git a/tools/cache/cache_test.go b/tools/cache/cache_test.go new file mode 100644 index 0000000000..614ffba2a6 --- /dev/null +++ b/tools/cache/cache_test.go @@ -0,0 +1,25 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cache + +import ( + "k8s.io/klog/v2" +) + +func init() { + klog.InitFlags(nil) +} diff --git a/tools/cache/controller.go b/tools/cache/controller.go index e523a66522..1497700d81 100644 --- a/tools/cache/controller.go +++ b/tools/cache/controller.go @@ -17,7 +17,9 @@ limitations under the License. package cache import ( + "context" "errors" + clientgofeaturegate "k8s.io/client-go/features" "sync" "time" @@ -71,16 +73,15 @@ type Config struct { // resync. ShouldResync ShouldResyncFunc - // If true, when Process() returns an error, re-enqueue the object. - // TODO: add interface to let you inject a delay/backoff or drop - // the object completely if desired. Pass the object in - // question to this interface as a parameter. This is probably moot - // now that this functionality appears at a higher level. - RetryOnError bool - // Called whenever the ListAndWatch drops the connection with an error. + // + // Contextual logging: WatchErrorHandlerWithContext should be used instead of WatchErrorHandler in code which supports contextual logging. WatchErrorHandler WatchErrorHandler + // Called whenever the ListAndWatch drops the connection with an error + // and WatchErrorHandler is not set. + WatchErrorHandlerWithContext WatchErrorHandlerWithContext + // WatchListPageSize is the requested chunk size of initial and relist watch lists. WatchListPageSize int64 } @@ -104,12 +105,21 @@ type controller struct { // Controller is a low-level controller that is parameterized by a // Config and used in sharedIndexInformer. type Controller interface { - // Run does two things. One is to construct and run a Reflector + // RunWithContext does two things. One is to construct and run a Reflector // to pump objects/notifications from the Config's ListerWatcher // to the Config's Queue and possibly invoke the occasional Resync // on that Queue. The other is to repeatedly Pop from the Queue // and process with the Config's ProcessFunc. Both of these - // continue until `stopCh` is closed. + // continue until the context is canceled. + // + // It's an error to call RunWithContext more than once. + // RunWithContext blocks; call via go. + RunWithContext(ctx context.Context) + + // Run does the same as RunWithContext with a stop channel instead of + // a context. + // + // Contextual logging: RunWithcontext should be used instead of Run in code which supports contextual logging. Run(stopCh <-chan struct{}) // HasSynced delegates to the Config's Queue @@ -129,13 +139,16 @@ func New(c *Config) Controller { return ctlr } -// Run begins processing items, and will continue until a value is sent down stopCh or it is closed. -// It's an error to call Run more than once. -// Run blocks; call via go. +// Run implements [Controller.Run]. func (c *controller) Run(stopCh <-chan struct{}) { - defer utilruntime.HandleCrash() + c.RunWithContext(wait.ContextForChannel(stopCh)) +} + +// RunWithContext implements [Controller.RunWithContext]. +func (c *controller) RunWithContext(ctx context.Context) { + defer utilruntime.HandleCrashWithContext(ctx) go func() { - <-stopCh + <-ctx.Done() c.config.Queue.Close() }() r := NewReflectorWithOptions( @@ -152,7 +165,11 @@ func (c *controller) Run(stopCh <-chan struct{}) { r.ShouldResync = c.config.ShouldResync r.WatchListPageSize = c.config.WatchListPageSize if c.config.WatchErrorHandler != nil { - r.watchErrorHandler = c.config.WatchErrorHandler + r.watchErrorHandler = func(_ context.Context, r *Reflector, err error) { + c.config.WatchErrorHandler(r, err) + } + } else if c.config.WatchErrorHandlerWithContext != nil { + r.watchErrorHandler = c.config.WatchErrorHandlerWithContext } c.reflectorMutex.Lock() @@ -161,9 +178,9 @@ func (c *controller) Run(stopCh <-chan struct{}) { var wg wait.Group - wg.StartWithChannel(stopCh, r.Run) + wg.StartWithContext(ctx, r.RunWithContext) - wait.Until(c.processLoop, time.Second, stopCh) + wait.UntilWithContext(ctx, c.processLoop, time.Second) wg.Wait() } @@ -185,22 +202,16 @@ func (c *controller) LastSyncResourceVersion() string { // TODO: Consider doing the processing in parallel. This will require a little thought // to make sure that we don't end up processing the same object multiple times // concurrently. -// -// TODO: Plumb through the stopCh here (and down to the queue) so that this can -// actually exit when the controller is stopped. Or just give up on this stuff -// ever being stoppable. Converting this whole package to use Context would -// also be helpful. -func (c *controller) processLoop() { +func (c *controller) processLoop(ctx context.Context) { for { - obj, err := c.config.Queue.Pop(PopProcessFunc(c.config.Process)) + // TODO: Plumb through the ctx so that this can + // actually exit when the controller is stopped. Or just give up on this stuff + // ever being stoppable. + _, err := c.config.Queue.Pop(PopProcessFunc(c.config.Process)) if err != nil { if err == ErrFIFOClosed { return } - if c.config.RetryOnError { - // This is the safe way to re-enqueue. - c.config.Queue.AddIfNotPresent(obj) - } } } } @@ -582,11 +593,17 @@ func newInformer(clientState Store, options InformerOptions) Controller { // This will hold incoming changes. Note how we pass clientState in as a // KeyLister, that way resync operations will result in the correct set // of update/delete deltas. - fifo := NewDeltaFIFOWithOptions(DeltaFIFOOptions{ - KnownObjects: clientState, - EmitDeltaTypeReplaced: true, - Transformer: options.Transform, - }) + + var fifo Queue + if clientgofeaturegate.FeatureGates().Enabled(clientgofeaturegate.InOrderInformers) { + fifo = NewRealFIFO(MetaNamespaceKeyFunc, clientState, options.Transform) + } else { + fifo = NewDeltaFIFOWithOptions(DeltaFIFOOptions{ + KnownObjects: clientState, + EmitDeltaTypeReplaced: true, + Transformer: options.Transform, + }) + } cfg := &Config{ Queue: fifo, @@ -594,7 +611,6 @@ func newInformer(clientState Store, options InformerOptions) Controller { ObjectType: options.ObjectType, FullResyncPeriod: options.ResyncPeriod, MinWatchTimeout: options.MinWatchTimeout, - RetryOnError: false, Process: func(obj interface{}, isInInitialList bool) error { if deltas, ok := obj.(Deltas); ok { diff --git a/tools/cache/controller_test.go b/tools/cache/controller_test.go index 992c1f5a4a..d76cc634de 100644 --- a/tools/cache/controller_test.go +++ b/tools/cache/controller_test.go @@ -17,6 +17,7 @@ limitations under the License. package cache import ( + "context" "fmt" "math/rand" "sync" @@ -32,13 +33,15 @@ import ( "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" fcache "k8s.io/client-go/tools/cache/testing" + "k8s.io/klog/v2/ktesting" - fuzz "github.com/google/gofuzz" + "sigs.k8s.io/randfill" ) func Example() { // source simulates an apiserver object endpoint. source := fcache.NewFakeControllerSource() + defer source.Shutdown() // This will hold the downstream state, as we know it. downstream := NewStore(DeletionHandlingMetaNamespaceKeyFunc) @@ -46,10 +49,7 @@ func Example() { // This will hold incoming changes. Note how we pass downstream in as a // KeyLister, that way resync operations will result in the correct set // of update/delete deltas. - fifo := NewDeltaFIFOWithOptions(DeltaFIFOOptions{ - KeyFunction: MetaNamespaceKeyFunc, - KnownObjects: downstream, - }) + fifo := NewRealFIFO(MetaNamespaceKeyFunc, downstream, nil) // Let's do threadsafe output to get predictable test results. deletionCounter := make(chan string, 1000) @@ -59,7 +59,6 @@ func Example() { ListerWatcher: source, ObjectType: &v1.Pod{}, FullResyncPeriod: time.Millisecond * 100, - RetryOnError: false, // Let's implement a simple controller that just deletes // everything that comes in. @@ -85,7 +84,7 @@ func Example() { // fifo's KeyOf is easiest, because it handles // DeletedFinalStateUnknown markers. - key, err := fifo.KeyOf(newest.Object) + key, err := fifo.keyOf(newest.Object) if err != nil { return err } @@ -97,10 +96,10 @@ func Example() { }, } - // Create the controller and run it until we close stop. - stop := make(chan struct{}) - defer close(stop) - go New(cfg).Run(stop) + // Create the controller and run it until we cancel. + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go New(cfg).RunWithContext(ctx) // Let's add a few objects to the source. testIDs := []string{"a-hello", "b-controller", "c-framework"} @@ -128,6 +127,7 @@ func Example() { func ExampleNewInformer() { // source simulates an apiserver object endpoint. source := fcache.NewFakeControllerSource() + defer source.Shutdown() // Let's do threadsafe output to get predictable test results. deletionCounter := make(chan string, 1000) @@ -154,10 +154,10 @@ func ExampleNewInformer() { }, ) - // Run the controller and run it until we close stop. - stop := make(chan struct{}) - defer close(stop) - go controller.Run(stop) + // Run the controller and run it until we cancel. + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go controller.RunWithContext(ctx) // Let's add a few objects to the source. testIDs := []string{"a-hello", "b-controller", "c-framework"} @@ -189,7 +189,7 @@ func TestHammerController(t *testing.T) { // race detector. // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) // Let's do threadsafe output to get predictable test results. outputSetLock := sync.Mutex{} @@ -225,9 +225,15 @@ func TestHammerController(t *testing.T) { t.Errorf("Expected HasSynced() to return false before we started the controller") } - // Run the controller and run it until we close stop. - stop := make(chan struct{}) - go controller.Run(stop) + // Run the controller and run it until we cancel. + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancel(ctx) + var controllerWG sync.WaitGroup + controllerWG.Add(1) + go func() { + defer controllerWG.Done() + controller.RunWithContext(ctx) + }() // Let's wait for the controller to do its initial sync wait.Poll(100*time.Millisecond, wait.ForeverTestTimeout, func() (bool, error) { @@ -246,12 +252,12 @@ func TestHammerController(t *testing.T) { // Let's add a few objects to the source. currentNames := sets.String{} rs := rand.NewSource(rand.Int63()) - f := fuzz.New().NilChance(.5).NumElements(0, 2).RandSource(rs) + f := randfill.New().NilChance(.5).NumElements(0, 2).RandSource(rs) for i := 0; i < 100; i++ { var name string var isNew bool if currentNames.Len() == 0 || rand.Intn(3) == 1 { - f.Fuzz(&name) + f.Fill(&name) isNew = true } else { l := currentNames.List() @@ -259,7 +265,7 @@ func TestHammerController(t *testing.T) { } pod := &v1.Pod{} - f.Fuzz(pod) + f.Fill(pod) pod.ObjectMeta.Name = name pod.ObjectMeta.Namespace = "default" // Add, update, or delete randomly. @@ -286,10 +292,13 @@ func TestHammerController(t *testing.T) { // Let's wait for the controller to finish processing the things we just added. // TODO: look in the queue to see how many items need to be processed. time.Sleep(100 * time.Millisecond) - close(stop) + cancel() - // TODO: Verify that no goroutines were leaked here and that everything shut - // down cleanly. + // Before we permanently lock this mutex, we have to be sure + // that the controller has stopped running. At this point, + // all goroutines should have stopped. Leak checking is + // done by TestMain. + controllerWG.Wait() outputSetLock.Lock() t.Logf("got: %#v", outputSet) @@ -300,7 +309,7 @@ func TestUpdate(t *testing.T) { // call to update. // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) const ( FROM = "from" @@ -354,7 +363,7 @@ func TestUpdate(t *testing.T) { // everything we've added has been deleted. watchCh := make(chan struct{}) _, controller := NewInformer( - &testLW{ + &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { watch, err := source.Watch(options) close(watchCh) @@ -383,11 +392,13 @@ func TestUpdate(t *testing.T) { }, ) - // Run the controller and run it until we close stop. + // Run the controller and run it until we cancel. // Once Run() is called, calls to testDoneWG.Done() might start, so // all testDoneWG.Add() calls must happen before this point - stop := make(chan struct{}) - go controller.Run(stop) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + go controller.RunWithContext(ctx) <-watchCh // run every test a few times, in parallel @@ -405,12 +416,11 @@ func TestUpdate(t *testing.T) { // Let's wait for the controller to process the things we just added. testDoneWG.Wait() - close(stop) } func TestPanicPropagated(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) // Make a controller that just panic if the AddFunc is called. _, controller := NewInformer( @@ -425,9 +435,10 @@ func TestPanicPropagated(t *testing.T) { }, ) - // Run the controller and run it until we close stop. - stop := make(chan struct{}) - defer close(stop) + // Run the controller and run it until we cancel. + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancel(ctx) + defer cancel() propagated := make(chan interface{}) go func() { @@ -436,7 +447,7 @@ func TestPanicPropagated(t *testing.T) { propagated <- r } }() - controller.Run(stop) + controller.RunWithContext(ctx) }() // Let's add a object to the source. It will trigger a panic. source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test"}}) @@ -456,7 +467,7 @@ func TestPanicPropagated(t *testing.T) { func TestTransformingInformer(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) makePod := func(name, generation string) *v1.Pod { return &v1.Pod{ @@ -553,8 +564,10 @@ func TestTransformingInformer(t *testing.T) { } } - stopCh := make(chan struct{}) - go controller.Run(stopCh) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + go controller.RunWithContext(ctx) verifyEvent(watch.Added, nil, expectedPod("pod1", "2")) verifyStore([]interface{}{expectedPod("pod1", "2")}) @@ -572,13 +585,19 @@ func TestTransformingInformer(t *testing.T) { source.Delete(makePod("pod1", "2")) verifyEvent(watch.Deleted, expectedPod("pod1", "2"), nil) verifyStore([]interface{}{expectedPod("pod2", "2"), expectedPod("pod3", "1")}) - - close(stopCh) } func TestTransformingInformerRace(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) + // Canceled *only* when the test is done. + testCtx, cancel := context.WithCancel(ctx) + defer cancel() + // Canceled *also* during the test. + ctx, cancel = context.WithCancel(ctx) + defer cancel() + // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) label := "to-be-transformed" makePod := func(name string) *v1.Pod { @@ -616,7 +635,11 @@ func TestTransformingInformerRace(t *testing.T) { type event struct{} events := make(chan event, numObjs) recordEvent := func(eventType watch.EventType, previous, current interface{}) { - events <- event{} + select { + case events <- event{}: + case <-testCtx.Done(): + // Don't block forever in the write above when test is already done. + } } checkEvents := func(count int) { for i := 0; i < count; i++ { @@ -635,8 +658,7 @@ func TestTransformingInformerRace(t *testing.T) { podTransformer, ) - stopCh := make(chan struct{}) - go controller.Run(stopCh) + go controller.RunWithContext(ctx) checkEvents(numObjs) @@ -650,7 +672,7 @@ func TestTransformingInformerRace(t *testing.T) { key := fmt.Sprintf("namespace/pod-%d", index) for { select { - case <-stopCh: + case <-ctx.Done(): return default: } @@ -672,7 +694,7 @@ func TestTransformingInformerRace(t *testing.T) { // Let resyncs to happen for some time. time.Sleep(time.Second) - close(stopCh) + cancel() wg.Wait() close(errors) for err := range errors { diff --git a/tools/cache/delta_fifo.go b/tools/cache/delta_fifo.go index ce74dfb6f1..264d7559a0 100644 --- a/tools/cache/delta_fifo.go +++ b/tools/cache/delta_fifo.go @@ -55,6 +55,9 @@ type DeltaFIFOOptions struct { // If set, will be called for objects before enqueueing them. Please // see the comment on TransformFunc for details. Transformer TransformFunc + + // If set, log output will go to this logger instead of klog.Background(). + Logger *klog.Logger } // DeltaFIFO is like FIFO, but differs in two ways. One is that the @@ -136,6 +139,10 @@ type DeltaFIFO struct { // Called with every object if non-nil. transformer TransformFunc + + // logger is a per-instance logger. This gets chosen when constructing + // the instance, with klog.Background() as default. + logger klog.Logger } // TransformFunc allows for transforming an object before it will be processed. @@ -253,6 +260,10 @@ func NewDeltaFIFOWithOptions(opts DeltaFIFOOptions) *DeltaFIFO { emitDeltaTypeReplaced: opts.EmitDeltaTypeReplaced, transformer: opts.Transformer, + logger: klog.Background(), + } + if opts.Logger != nil { + f.logger = *opts.Logger } f.cond.L = &f.lock return f @@ -358,43 +369,6 @@ func (f *DeltaFIFO) Delete(obj interface{}) error { return f.queueActionLocked(Deleted, obj) } -// AddIfNotPresent inserts an item, and puts it in the queue. If the item is already -// present in the set, it is neither enqueued nor added to the set. -// -// This is useful in a single producer/consumer scenario so that the consumer can -// safely retry items without contending with the producer and potentially enqueueing -// stale items. -// -// Important: obj must be a Deltas (the output of the Pop() function). Yes, this is -// different from the Add/Update/Delete functions. -func (f *DeltaFIFO) AddIfNotPresent(obj interface{}) error { - deltas, ok := obj.(Deltas) - if !ok { - return fmt.Errorf("object must be of type deltas, but got: %#v", obj) - } - id, err := f.KeyOf(deltas) - if err != nil { - return KeyError{obj, err} - } - f.lock.Lock() - defer f.lock.Unlock() - f.addIfNotPresent(id, deltas) - return nil -} - -// addIfNotPresent inserts deltas under id if it does not exist, and assumes the caller -// already holds the fifo lock. -func (f *DeltaFIFO) addIfNotPresent(id string, deltas Deltas) { - f.populated = true - if _, exists := f.items[id]; exists { - return - } - - f.queue = append(f.queue, id) - f.items[id] = deltas - f.cond.Broadcast() -} - // re-listing and watching can deliver the same update multiple times in any // order. This will combine the most recent two deltas if they are the same. func dedupDeltas(deltas Deltas) Deltas { @@ -487,71 +461,16 @@ func (f *DeltaFIFO) queueActionInternalLocked(actionType, internalActionType Del // when given a non-empty list (as it is here). // If somehow it happens anyway, deal with it but complain. if oldDeltas == nil { - klog.Errorf("Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; ignoring", id, oldDeltas, obj) + f.logger.Error(nil, "Impossible dedupDeltas, ignoring", "id", id, "oldDeltas", oldDeltas, "obj", obj) return nil } - klog.Errorf("Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; breaking invariant by storing empty Deltas", id, oldDeltas, obj) + f.logger.Error(nil, "Impossible dedupDeltas, breaking invariant by storing empty Deltas", "id", id, "oldDeltas", oldDeltas, "obj", obj) f.items[id] = newDeltas return fmt.Errorf("Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; broke DeltaFIFO invariant by storing empty Deltas", id, oldDeltas, obj) } return nil } -// List returns a list of all the items; it returns the object -// from the most recent Delta. -// You should treat the items returned inside the deltas as immutable. -func (f *DeltaFIFO) List() []interface{} { - f.lock.RLock() - defer f.lock.RUnlock() - return f.listLocked() -} - -func (f *DeltaFIFO) listLocked() []interface{} { - list := make([]interface{}, 0, len(f.items)) - for _, item := range f.items { - list = append(list, item.Newest().Object) - } - return list -} - -// ListKeys returns a list of all the keys of the objects currently -// in the FIFO. -func (f *DeltaFIFO) ListKeys() []string { - f.lock.RLock() - defer f.lock.RUnlock() - list := make([]string, 0, len(f.queue)) - for _, key := range f.queue { - list = append(list, key) - } - return list -} - -// Get returns the complete list of deltas for the requested item, -// or sets exists=false. -// You should treat the items returned inside the deltas as immutable. -func (f *DeltaFIFO) Get(obj interface{}) (item interface{}, exists bool, err error) { - key, err := f.KeyOf(obj) - if err != nil { - return nil, false, KeyError{obj, err} - } - return f.GetByKey(key) -} - -// GetByKey returns the complete list of deltas for the requested item, -// setting exists=false if that list is empty. -// You should treat the items returned inside the deltas as immutable. -func (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err error) { - f.lock.RLock() - defer f.lock.RUnlock() - d, exists := f.items[key] - if exists { - // Copy item's slice so operations on this slice - // won't interfere with the object we return. - d = copyDeltas(d) - } - return d, exists, nil -} - // IsClosed checks if the queue is closed func (f *DeltaFIFO) IsClosed() bool { f.lock.Lock() @@ -565,9 +484,7 @@ func (f *DeltaFIFO) IsClosed() bool { // is returned, so if you don't successfully process it, you need to add it back // with AddIfNotPresent(). // process function is called under lock, so it is safe to update data structures -// in it that need to be in sync with the queue (e.g. knownKeys). The PopProcessFunc -// may return an instance of ErrRequeue with a nested error to indicate the current -// item should be requeued (equivalent to calling AddIfNotPresent under the lock). +// in it that need to be in sync with the queue (e.g. knownKeys). // process should avoid expensive I/O operation so that other queue operations, i.e. // Add() and Get(), won't be blocked for too long. // @@ -597,7 +514,7 @@ func (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error) { item, ok := f.items[id] if !ok { // This should never happen - klog.Errorf("Inconceivable! %q was in f.queue but not f.items; ignoring.", id) + f.logger.Error(nil, "Inconceivable! Item was in f.queue but not f.items; ignoring", "id", id) continue } delete(f.items, id) @@ -614,10 +531,6 @@ func (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error) { defer trace.LogIfLong(100 * time.Millisecond) } err := process(item, isInInitialList) - if e, ok := err.(ErrRequeue); ok { - f.addIfNotPresent(id, item) - err = e.Err - } // Don't need to copyDeltas here, because we're transferring // ownership to the caller. return item, err @@ -694,10 +607,10 @@ func (f *DeltaFIFO) Replace(list []interface{}, _ string) error { deletedObj, exists, err := f.knownObjects.GetByKey(k) if err != nil { deletedObj = nil - klog.Errorf("Unexpected error %v during lookup of key %v, placing DeleteFinalStateUnknown marker without object", err, k) + f.logger.Error(err, "Unexpected error during lookup, placing DeleteFinalStateUnknown marker without object", "key", k) } else if !exists { deletedObj = nil - klog.Infof("Key %v does not exist in known objects store, placing DeleteFinalStateUnknown marker without object", k) + f.logger.Info("Key does not exist in known objects store, placing DeleteFinalStateUnknown marker without object", "key", k) } queuedDeletions++ if err := f.queueActionLocked(Deleted, DeletedFinalStateUnknown{k, deletedObj}); err != nil { @@ -737,10 +650,10 @@ func (f *DeltaFIFO) Resync() error { func (f *DeltaFIFO) syncKeyLocked(key string) error { obj, exists, err := f.knownObjects.GetByKey(key) if err != nil { - klog.Errorf("Unexpected error %v during lookup of key %v, unable to queue object for sync", err, key) + f.logger.Error(err, "Unexpected error during lookup, unable to queue object for sync", "key", key) return nil } else if !exists { - klog.Infof("Key %v does not exist in known objects store, unable to queue object for sync", key) + f.logger.Info("Key does not exist in known objects store, unable to queue object for sync", "key", key) return nil } diff --git a/tools/cache/delta_fifo_test.go b/tools/cache/delta_fifo_test.go index 80994beb45..8f069eb1c5 100644 --- a/tools/cache/delta_fifo_test.go +++ b/tools/cache/delta_fifo_test.go @@ -17,7 +17,6 @@ limitations under the License. package cache import ( - "errors" "fmt" "reflect" "runtime" @@ -25,6 +24,66 @@ import ( "time" ) +// List returns a list of all the items; it returns the object +// from the most recent Delta. +// You should treat the items returned inside the deltas as immutable. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *DeltaFIFO) List() []interface{} { + f.lock.RLock() + defer f.lock.RUnlock() + return f.listLocked() +} + +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *DeltaFIFO) listLocked() []interface{} { + list := make([]interface{}, 0, len(f.items)) + for _, item := range f.items { + list = append(list, item.Newest().Object) + } + return list +} + +// ListKeys returns a list of all the keys of the objects currently +// in the FIFO. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *DeltaFIFO) ListKeys() []string { + f.lock.RLock() + defer f.lock.RUnlock() + list := make([]string, 0, len(f.queue)) + for _, key := range f.queue { + list = append(list, key) + } + return list +} + +// Get returns the complete list of deltas for the requested item, +// or sets exists=false. +// You should treat the items returned inside the deltas as immutable. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *DeltaFIFO) Get(obj interface{}) (item interface{}, exists bool, err error) { + key, err := f.KeyOf(obj) + if err != nil { + return nil, false, KeyError{obj, err} + } + return f.GetByKey(key) +} + +// GetByKey returns the complete list of deltas for the requested item, +// setting exists=false if that list is empty. +// You should treat the items returned inside the deltas as immutable. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err error) { + f.lock.RLock() + defer f.lock.RUnlock() + d, exists := f.items[key] + if exists { + // Copy item's slice so operations on this slice + // won't interfere with the object we return. + d = copyDeltas(d) + } + return d, exists, nil +} + // helper function to reduce stuttering func testPop(f *DeltaFIFO) testFifoObject { return Pop(f).(Deltas).Newest().Object.(testFifoObject) @@ -245,50 +304,6 @@ func TestDeltaFIFOW_ReplaceMakesDeletionsForObjectsOnlyInQueue(t *testing.T) { } } -func TestDeltaFIFO_requeueOnPop(t *testing.T) { - f := NewDeltaFIFOWithOptions(DeltaFIFOOptions{KeyFunction: testFifoObjectKeyFunc}) - - f.Add(mkFifoObj("foo", 10)) - _, err := f.Pop(func(obj interface{}, isInInitialList bool) error { - if obj.(Deltas)[0].Object.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: nil} - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}, isInInitialList bool) error { - if obj.(Deltas)[0].Object.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: fmt.Errorf("test error")} - }) - if err == nil || err.Error() != "test error" { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}, isInInitialList bool) error { - if obj.(Deltas)[0].Object.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return nil - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); ok || err != nil { - t.Fatalf("object should have been removed: %t %v", ok, err) - } -} - func TestDeltaFIFO_addUpdate(t *testing.T) { f := NewDeltaFIFOWithOptions(DeltaFIFOOptions{KeyFunction: testFifoObjectKeyFunc}) f.Add(mkFifoObj("foo", 10)) @@ -821,39 +836,6 @@ func TestDeltaFIFO_detectLineJumpers(t *testing.T) { } } -func TestDeltaFIFO_addIfNotPresent(t *testing.T) { - f := NewDeltaFIFOWithOptions(DeltaFIFOOptions{KeyFunction: testFifoObjectKeyFunc}) - - emptyDeltas := Deltas{} - if err := f.AddIfNotPresent(emptyDeltas); err == nil || !errors.Is(err, ErrZeroLengthDeltasObject) { - t.Errorf("Expected error '%v', got %v", ErrZeroLengthDeltasObject, err) - } - - f.Add(mkFifoObj("b", 3)) - b3 := Pop(f) - f.Add(mkFifoObj("c", 4)) - c4 := Pop(f) - if e, a := 0, len(f.items); e != a { - t.Fatalf("Expected %v, got %v items in queue", e, a) - } - - f.Add(mkFifoObj("a", 1)) - f.Add(mkFifoObj("b", 2)) - f.AddIfNotPresent(b3) - f.AddIfNotPresent(c4) - - if e, a := 3, len(f.items); a != e { - t.Fatalf("expected queue length %d, got %d", e, a) - } - - expectedValues := []int{1, 2, 4} - for _, expected := range expectedValues { - if actual := testPop(f).val; actual != expected { - t.Fatalf("expected value %d, got %d", expected, actual) - } - } -} - func TestDeltaFIFO_KeyOf(t *testing.T) { f := DeltaFIFO{keyFunc: testFifoObjectKeyFunc} diff --git a/tools/cache/doc.go b/tools/cache/doc.go index 56b61d3006..4f593f0d3d 100644 --- a/tools/cache/doc.go +++ b/tools/cache/doc.go @@ -21,4 +21,4 @@ limitations under the License. // list currently available nodes), and one that additionally acts as // a FIFO queue (for example, to allow a scheduler to process incoming // pods). -package cache // import "k8s.io/client-go/tools/cache" +package cache diff --git a/tools/cache/fifo.go b/tools/cache/fifo.go index dd13c4ea77..5c2ca90084 100644 --- a/tools/cache/fifo.go +++ b/tools/cache/fifo.go @@ -27,30 +27,16 @@ import ( // It is supposed to process the accumulator popped from the queue. type PopProcessFunc func(obj interface{}, isInInitialList bool) error -// ErrRequeue may be returned by a PopProcessFunc to safely requeue -// the current item. The value of Err will be returned from Pop. -type ErrRequeue struct { - // Err is returned by the Pop function - Err error -} - // ErrFIFOClosed used when FIFO is closed var ErrFIFOClosed = errors.New("DeltaFIFO: manipulating with closed queue") -func (e ErrRequeue) Error() string { - if e.Err == nil { - return "the popped item should be requeued without returning an error" - } - return e.Err.Error() -} - -// Queue extends Store with a collection of Store keys to "process". +// Queue extends ReflectorStore with a collection of Store keys to "process". // Every Add, Update, or Delete may put the object's key in that collection. // A Queue has a way to derive the corresponding key given an accumulator. // A Queue can be accessed concurrently from multiple goroutines. // A Queue can be "closed", after which Pop operations return an error. type Queue interface { - Store + ReflectorStore // Pop blocks until there is at least one key to process or the // Queue is closed. In the latter case Pop returns with an error. @@ -64,11 +50,6 @@ type Queue interface { // Pop. Pop(PopProcessFunc) (interface{}, error) - // AddIfNotPresent puts the given accumulator into the Queue (in - // association with the accumulator's key) if and only if that key - // is not already associated with a non-empty accumulator. - AddIfNotPresent(interface{}) error - // HasSynced returns true if the first batch of keys have all been // popped. The first batch of keys are those of the first Replace // operation if that happened before any Add, AddIfNotPresent, @@ -177,36 +158,6 @@ func (f *FIFO) Add(obj interface{}) error { return nil } -// AddIfNotPresent inserts an item, and puts it in the queue. If the item is already -// present in the set, it is neither enqueued nor added to the set. -// -// This is useful in a single producer/consumer scenario so that the consumer can -// safely retry items without contending with the producer and potentially enqueueing -// stale items. -func (f *FIFO) AddIfNotPresent(obj interface{}) error { - id, err := f.keyFunc(obj) - if err != nil { - return KeyError{obj, err} - } - f.lock.Lock() - defer f.lock.Unlock() - f.addIfNotPresent(id, obj) - return nil -} - -// addIfNotPresent assumes the fifo lock is already held and adds the provided -// item to the queue under id if it does not already exist. -func (f *FIFO) addIfNotPresent(id string, obj interface{}) { - f.populated = true - if _, exists := f.items[id]; exists { - return - } - - f.queue = append(f.queue, id) - f.items[id] = obj - f.cond.Broadcast() -} - // Update is the same as Add in this implementation. func (f *FIFO) Update(obj interface{}) error { return f.Add(obj) @@ -227,46 +178,6 @@ func (f *FIFO) Delete(obj interface{}) error { return err } -// List returns a list of all the items. -func (f *FIFO) List() []interface{} { - f.lock.RLock() - defer f.lock.RUnlock() - list := make([]interface{}, 0, len(f.items)) - for _, item := range f.items { - list = append(list, item) - } - return list -} - -// ListKeys returns a list of all the keys of the objects currently -// in the FIFO. -func (f *FIFO) ListKeys() []string { - f.lock.RLock() - defer f.lock.RUnlock() - list := make([]string, 0, len(f.items)) - for key := range f.items { - list = append(list, key) - } - return list -} - -// Get returns the requested item, or sets exists=false. -func (f *FIFO) Get(obj interface{}) (item interface{}, exists bool, err error) { - key, err := f.keyFunc(obj) - if err != nil { - return nil, false, KeyError{obj, err} - } - return f.GetByKey(key) -} - -// GetByKey returns the requested item, or sets exists=false. -func (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error) { - f.lock.RLock() - defer f.lock.RUnlock() - item, exists = f.items[key] - return item, exists, nil -} - // IsClosed checks if the queue is closed func (f *FIFO) IsClosed() bool { f.lock.Lock() @@ -307,10 +218,6 @@ func (f *FIFO) Pop(process PopProcessFunc) (interface{}, error) { } delete(f.items, id) err := process(item, isInInitialList) - if e, ok := err.(ErrRequeue); ok { - f.addIfNotPresent(id, item) - err = e.Err - } return item, err } } diff --git a/tools/cache/fifo_test.go b/tools/cache/fifo_test.go index 655f137853..1831889b09 100644 --- a/tools/cache/fifo_test.go +++ b/tools/cache/fifo_test.go @@ -17,13 +17,56 @@ limitations under the License. package cache import ( - "fmt" "reflect" "runtime" "testing" "time" ) +// List returns a list of all the items. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *FIFO) List() []interface{} { + f.lock.RLock() + defer f.lock.RUnlock() + list := make([]interface{}, 0, len(f.items)) + for _, item := range f.items { + list = append(list, item) + } + return list +} + +// ListKeys returns a list of all the keys of the objects currently +// in the FIFO. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *FIFO) ListKeys() []string { + f.lock.RLock() + defer f.lock.RUnlock() + list := make([]string, 0, len(f.items)) + for key := range f.items { + list = append(list, key) + } + return list +} + +// Get returns the requested item, or sets exists=false. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *FIFO) Get(obj interface{}) (item interface{}, exists bool, err error) { + key, err := f.keyFunc(obj) + if err != nil { + return nil, false, KeyError{obj, err} + } + return f.GetByKey(key) +} + +// GetByKey returns the requested item, or sets exists=false. +// This function was moved here because it is not consistent with normal list semantics, but is used in unit testing. +func (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error) { + f.lock.RLock() + defer f.lock.RUnlock() + item, exists = f.items[key] + return item, exists, nil +} + func testFifoObjectKeyFunc(obj interface{}) (string, error) { return obj.(testFifoObject).name, nil } @@ -72,50 +115,6 @@ func TestFIFO_basic(t *testing.T) { } } -func TestFIFO_requeueOnPop(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - - f.Add(mkFifoObj("foo", 10)) - _, err := f.Pop(func(obj interface{}, isInInitialList bool) error { - if obj.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: nil} - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}, isInInitialList bool) error { - if obj.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: fmt.Errorf("test error")} - }) - if err == nil || err.Error() != "test error" { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}, isInInitialList bool) error { - if obj.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return nil - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); ok || err != nil { - t.Fatalf("object should have been removed: %t %v", ok, err) - } -} - func TestFIFO_addUpdate(t *testing.T) { f := NewFIFO(testFifoObjectKeyFunc) f.Add(mkFifoObj("foo", 10)) @@ -204,26 +203,6 @@ func TestFIFO_detectLineJumpers(t *testing.T) { } } -func TestFIFO_addIfNotPresent(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - - f.Add(mkFifoObj("a", 1)) - f.Add(mkFifoObj("b", 2)) - f.AddIfNotPresent(mkFifoObj("b", 3)) - f.AddIfNotPresent(mkFifoObj("c", 4)) - - if e, a := 3, len(f.items); a != e { - t.Fatalf("expected queue length %d, got %d", e, a) - } - - expectedValues := []int{1, 2, 4} - for _, expected := range expectedValues { - if actual := Pop(f).(testFifoObject).val; actual != expected { - t.Fatalf("expected value %d, got %d", expected, actual) - } - } -} - func TestFIFO_HasSynced(t *testing.T) { tests := []struct { actions []func(f *FIFO) diff --git a/tools/cache/listers.go b/tools/cache/listers.go index a60f44943e..9e050ff45e 100644 --- a/tools/cache/listers.go +++ b/tools/cache/listers.go @@ -62,7 +62,12 @@ func ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selec items, err := indexer.Index(NamespaceIndex, &metav1.ObjectMeta{Namespace: namespace}) if err != nil { // Ignore error; do slow search without index. - klog.Warningf("can not retrieve list of objects using index : %v", err) + // + // ListAllByNamespace is called by generated code + // (k8s.io/client-go/listers) and probably not worth converting + // to contextual logging, which would require changing all of + // those APIs. + klog.TODO().Info("Warning: can not retrieve list of objects using index", "err", err) for _, m := range indexer.List() { metadata, err := meta.Accessor(m) if err != nil { diff --git a/tools/cache/listers_test.go b/tools/cache/listers_test.go new file mode 100644 index 0000000000..730807f6e3 --- /dev/null +++ b/tools/cache/listers_test.go @@ -0,0 +1,140 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cache + +import ( + "fmt" + "testing" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" +) + +func TestListAll(t *testing.T) { + testCases := []struct { + name string + numObjects int + numMatching int + matchingLabels map[string]string + selector labels.Selector + expectedCount int + }{ + { + name: "subset match", + numObjects: 100000, + numMatching: 10000, + matchingLabels: map[string]string{"match": "true"}, + selector: labels.SelectorFromSet(map[string]string{"match": "true"}), + expectedCount: 10000, + }, + { + name: "all match", + numObjects: 1000000, + numMatching: 0, + matchingLabels: map[string]string{}, + selector: labels.Everything(), + expectedCount: 1000000, + }, + { + name: "no match", + numObjects: 1000000, + numMatching: 0, + matchingLabels: map[string]string{"nomatch": "true"}, + selector: labels.SelectorFromSet(map[string]string{"match": "true"}), + expectedCount: 0, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + store := mustCreateStore(tc.numObjects, tc.numMatching, tc.matchingLabels) + + var matchingObjects int + appendFn := func(obj interface{}) { + matchingObjects++ + } + + err := ListAll(store, tc.selector, appendFn) + if err != nil { + t.Fatalf("ListAll returned an error: %v", err) + } + + if matchingObjects != tc.expectedCount { + t.Errorf("ListAll returned %d objects, expected %d", matchingObjects, tc.expectedCount) + } + }) + } +} + +func mustCreateStore(numObjects int, numMatching int, labels map[string]string) Store { + if numMatching > numObjects { + panic("there can not be more matches than objects") + } + store := NewStore(func(obj interface{}) (string, error) { + meta, err := meta.Accessor(obj) + if err != nil { + return "", err + } + return meta.GetName(), nil + }) + // add matching objects to the store + for i := 0; i < numObjects; i++ { + obj := &metav1.PartialObjectMetadata{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("obj-%d", i), + Labels: map[string]string{}, + }, + } + if i < numMatching { + obj.Labels = labels + } + err := store.Add(obj) + if err != nil { + panic("unexpected error") + } + } + return store +} + +func benchmarkLister(b *testing.B, numObjects int, numMatching int, label map[string]string) { + store := mustCreateStore(numObjects, numMatching, label) + selector := labels.SelectorFromSet(label) + b.ResetTimer() + for n := 0; n < b.N; n++ { + err := ListAll(store, selector, func(m interface{}) { + }) + if err != nil { + b.Fatalf("ListAll returned an error: %v", err) + } + } +} + +func BenchmarkLister_Match_1k_100(b *testing.B) { + benchmarkLister(b, 1000, 100, map[string]string{"match": "true"}) +} +func BenchmarkLister_Match_10k_100(b *testing.B) { + benchmarkLister(b, 10000, 100, map[string]string{"match": "true"}) +} + +func BenchmarkLister_Match_100k_100(b *testing.B) { + benchmarkLister(b, 100000, 100, map[string]string{"match": "true"}) +} + +func BenchmarkLister_Match_1M_100(b *testing.B) { + benchmarkLister(b, 1000000, 100, map[string]string{"match": "true"}) +} diff --git a/tools/cache/listwatch.go b/tools/cache/listwatch.go index f5708ffeb1..30d30e8858 100644 --- a/tools/cache/listwatch.go +++ b/tools/cache/listwatch.go @@ -27,50 +27,160 @@ import ( ) // Lister is any object that knows how to perform an initial list. +// +// Ideally, all implementations of Lister should also implement ListerWithContext. type Lister interface { // List should return a list type object; the Items field will be extracted, and the // ResourceVersion field will be used to start the watch in the right place. + // + // Deprecated: use ListerWithContext.ListWithContext instead. List(options metav1.ListOptions) (runtime.Object, error) } +// ListerWithContext is any object that knows how to perform an initial list. +type ListerWithContext interface { + // ListWithContext should return a list type object; the Items field will be extracted, and the + // ResourceVersion field will be used to start the watch in the right place. + ListWithContext(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) +} + +func ToListerWithContext(l Lister) ListerWithContext { + if l, ok := l.(ListerWithContext); ok { + return l + } + return listerWrapper{ + parent: l, + } +} + +type listerWrapper struct { + parent Lister +} + +func (l listerWrapper) ListWithContext(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + return l.parent.List(options) +} + // Watcher is any object that knows how to start a watch on a resource. +// +// Ideally, all implementations of Watcher should also implement WatcherWithContext. type Watcher interface { // Watch should begin a watch at the specified version. // // If Watch returns an error, it should handle its own cleanup, including // but not limited to calling Stop() on the watch, if one was constructed. // This allows the caller to ignore the watch, if the error is non-nil. + // + // Deprecated: use WatcherWithContext.WatchWithContext instead. Watch(options metav1.ListOptions) (watch.Interface, error) } +// WatcherWithContext is any object that knows how to start a watch on a resource. +type WatcherWithContext interface { + // WatchWithContext should begin a watch at the specified version. + // + // If Watch returns an error, it should handle its own cleanup, including + // but not limited to calling Stop() on the watch, if one was constructed. + // This allows the caller to ignore the watch, if the error is non-nil. + WatchWithContext(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) +} + +func ToWatcherWithContext(w Watcher) WatcherWithContext { + if w, ok := w.(WatcherWithContext); ok { + return w + } + return watcherWrapper{ + parent: w, + } +} + +type watcherWrapper struct { + parent Watcher +} + +func (l watcherWrapper) WatchWithContext(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + return l.parent.Watch(options) +} + // ListerWatcher is any object that knows how to perform an initial list and start a watch on a resource. +// +// Ideally, all implementations of ListerWatcher should also implement ListerWatcherWithContext. type ListerWatcher interface { Lister Watcher } +// ListerWatcherWithContext is any object that knows how to perform an initial list and start a watch on a resource. +type ListerWatcherWithContext interface { + ListerWithContext + WatcherWithContext +} + +func ToListerWatcherWithContext(lw ListerWatcher) ListerWatcherWithContext { + if lw, ok := lw.(ListerWatcherWithContext); ok { + return lw + } + return listerWatcherWrapper{ + ListerWithContext: ToListerWithContext(lw), + WatcherWithContext: ToWatcherWithContext(lw), + } +} + +type listerWatcherWrapper struct { + ListerWithContext + WatcherWithContext +} + // ListFunc knows how to list resources +// +// Deprecated: use ListWithContextFunc instead. type ListFunc func(options metav1.ListOptions) (runtime.Object, error) +// ListWithContextFunc knows how to list resources +type ListWithContextFunc func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) + // WatchFunc knows how to watch resources +// +// Deprecated: use WatchFuncWithContext instead. type WatchFunc func(options metav1.ListOptions) (watch.Interface, error) -// ListWatch knows how to list and watch a set of apiserver resources. It satisfies the ListerWatcher interface. +// WatchFuncWithContext knows how to watch resources +type WatchFuncWithContext func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) + +// ListWatch knows how to list and watch a set of apiserver resources. +// It satisfies the ListerWatcher and ListerWatcherWithContext interfaces. // It is a convenience function for users of NewReflector, etc. -// ListFunc and WatchFunc must not be nil +// ListFunc or ListWithContextFunc must be set. Same for WatchFunc and WatchFuncWithContext. +// ListWithContextFunc and WatchFuncWithContext are preferred if +// a context is available, otherwise ListFunc and WatchFunc. +// +// NewFilteredListWatchFromClient sets all of the functions to ensure that callers +// which only know about ListFunc and WatchFunc continue to work. type ListWatch struct { - ListFunc ListFunc + // Deprecated: use ListWithContext instead. + ListFunc ListFunc + // Deprecated: use WatchWithContext instead. WatchFunc WatchFunc + + ListWithContextFunc ListWithContextFunc + WatchFuncWithContext WatchFuncWithContext + // DisableChunking requests no chunking for this list watcher. DisableChunking bool } +var ( + _ ListerWatcher = &ListWatch{} + _ ListerWatcherWithContext = &ListWatch{} +) + // Getter interface knows how to access Get method from RESTClient. type Getter interface { Get() *restclient.Request } // NewListWatchFromClient creates a new ListWatch from the specified client, resource, namespace and field selector. +// For backward compatibility, all function fields are populated. func NewListWatchFromClient(c Getter, resource string, namespace string, fieldSelector fields.Selector) *ListWatch { optionsModifier := func(options *metav1.ListOptions) { options.FieldSelector = fieldSelector.String() @@ -81,6 +191,7 @@ func NewListWatchFromClient(c Getter, resource string, namespace string, fieldSe // NewFilteredListWatchFromClient creates a new ListWatch from the specified client, resource, namespace, and option modifier. // Option modifier is a function takes a ListOptions and modifies the consumed ListOptions. Provide customized modifier function // to apply modification to ListOptions with a field selector, a label selector, or any other desired options. +// For backward compatibility, all function fields are populated. func NewFilteredListWatchFromClient(c Getter, resource string, namespace string, optionsModifier func(options *metav1.ListOptions)) *ListWatch { listFunc := func(options metav1.ListOptions) (runtime.Object, error) { optionsModifier(&options) @@ -88,7 +199,7 @@ func NewFilteredListWatchFromClient(c Getter, resource string, namespace string, Namespace(namespace). Resource(resource). VersionedParams(&options, metav1.ParameterCodec). - Do(context.TODO()). + Do(context.Background()). Get() } watchFunc := func(options metav1.ListOptions) (watch.Interface, error) { @@ -98,19 +209,70 @@ func NewFilteredListWatchFromClient(c Getter, resource string, namespace string, Namespace(namespace). Resource(resource). VersionedParams(&options, metav1.ParameterCodec). - Watch(context.TODO()) + Watch(context.Background()) + } + listFuncWithContext := func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + optionsModifier(&options) + return c.Get(). + Namespace(namespace). + Resource(resource). + VersionedParams(&options, metav1.ParameterCodec). + Do(ctx). + Get() + } + watchFuncWithContext := func(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + options.Watch = true + optionsModifier(&options) + return c.Get(). + Namespace(namespace). + Resource(resource). + VersionedParams(&options, metav1.ParameterCodec). + Watch(ctx) + } + return &ListWatch{ + ListFunc: listFunc, + WatchFunc: watchFunc, + ListWithContextFunc: listFuncWithContext, + WatchFuncWithContext: watchFuncWithContext, } - return &ListWatch{ListFunc: listFunc, WatchFunc: watchFunc} } // List a set of apiserver resources +// +// Deprecated: use ListWatchWithContext.ListWithContext instead. func (lw *ListWatch) List(options metav1.ListOptions) (runtime.Object, error) { // ListWatch is used in Reflector, which already supports pagination. // Don't paginate here to avoid duplication. + if lw.ListFunc != nil { + return lw.ListFunc(options) + } + return lw.ListWithContextFunc(context.Background(), options) +} + +// List a set of apiserver resources +func (lw *ListWatch) ListWithContext(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { + // ListWatch is used in Reflector, which already supports pagination. + // Don't paginate here to avoid duplication. + if lw.ListWithContextFunc != nil { + return lw.ListWithContextFunc(ctx, options) + } return lw.ListFunc(options) } // Watch a set of apiserver resources +// +// Deprecated: use ListWatchWithContext.WatchWithContext instead. func (lw *ListWatch) Watch(options metav1.ListOptions) (watch.Interface, error) { + if lw.WatchFunc != nil { + return lw.WatchFunc(options) + } + return lw.WatchFuncWithContext(context.Background(), options) +} + +// Watch a set of apiserver resources +func (lw *ListWatch) WatchWithContext(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) { + if lw.WatchFuncWithContext != nil { + return lw.WatchFuncWithContext(ctx, options) + } return lw.WatchFunc(options) } diff --git a/tools/cache/main_test.go b/tools/cache/main_test.go index abbfb0b506..b0ed00f323 100644 --- a/tools/cache/main_test.go +++ b/tools/cache/main_test.go @@ -17,10 +17,19 @@ limitations under the License. package cache import ( - "os" "testing" + + "go.uber.org/goleak" ) func TestMain(m *testing.M) { - os.Exit(m.Run()) + options := []goleak.Option{ + // These tests run goroutines which get stuck in Pop. + // This cannot be fixed without modifying the API. + goleak.IgnoreAnyFunction("k8s.io/client-go/tools/cache.TestFIFO_addReplace.func1"), + goleak.IgnoreAnyFunction("k8s.io/client-go/tools/cache.TestFIFO_addUpdate.func1"), + goleak.IgnoreAnyFunction("k8s.io/client-go/tools/cache.TestDeltaFIFO_addReplace.func1"), + goleak.IgnoreAnyFunction("k8s.io/client-go/tools/cache.TestDeltaFIFO_addUpdate.func1"), + } + goleak.VerifyTestMain(m, options...) } diff --git a/tools/cache/mutation_cache.go b/tools/cache/mutation_cache.go index c6f953d8e0..6800a62508 100644 --- a/tools/cache/mutation_cache.go +++ b/tools/cache/mutation_cache.go @@ -60,7 +60,7 @@ type ResourceVersionComparator interface { // If includeAdds is true, objects in the mutation cache will be returned even if they don't exist // in the underlying store. This is only safe if your use of the cache can handle mutation entries // remaining in the cache for up to ttl when mutations and deletes occur very closely in time. -func NewIntegerResourceVersionMutationCache(backingCache Store, indexer Indexer, ttl time.Duration, includeAdds bool) MutationCache { +func NewIntegerResourceVersionMutationCache(logger klog.Logger, backingCache Store, indexer Indexer, ttl time.Duration, includeAdds bool) MutationCache { return &mutationCache{ backingCache: backingCache, indexer: indexer, @@ -68,6 +68,7 @@ func NewIntegerResourceVersionMutationCache(backingCache Store, indexer Indexer, comparator: etcdObjectVersioner{}, ttl: ttl, includeAdds: includeAdds, + logger: logger, } } @@ -75,6 +76,7 @@ func NewIntegerResourceVersionMutationCache(backingCache Store, indexer Indexer, // since you can't distinguish between, "didn't observe create" and "was deleted after create", // if the key is missing from the backing cache, we always return it as missing type mutationCache struct { + logger klog.Logger lock sync.Mutex backingCache Store indexer Indexer @@ -157,7 +159,7 @@ func (c *mutationCache) ByIndex(name string, indexKey string) ([]interface{}, er } elements, err := fn(updated) if err != nil { - klog.V(4).Infof("Unable to calculate an index entry for mutation cache entry %s: %v", key, err) + c.logger.V(4).Info("Unable to calculate an index entry for mutation cache entry", "key", key, "err", err) continue } for _, inIndex := range elements { @@ -204,7 +206,7 @@ func (c *mutationCache) Mutation(obj interface{}) { key, err := DeletionHandlingMetaNamespaceKeyFunc(obj) if err != nil { // this is a "nice to have", so failures shouldn't do anything weird - utilruntime.HandleError(err) + utilruntime.HandleErrorWithLogger(c.logger, err, "DeletionHandlingMetaNamespaceKeyFunc") return } diff --git a/tools/cache/mutation_detector.go b/tools/cache/mutation_detector.go index b37537cbd8..27ea62bfbb 100644 --- a/tools/cache/mutation_detector.go +++ b/tools/cache/mutation_detector.go @@ -50,6 +50,7 @@ func NewCacheMutationDetector(name string) MutationDetector { if !mutationDetectionEnabled { return dummyMutationDetector{} } + //nolint:logcheck // This code shouldn't be used in production. klog.Warningln("Mutation detector is enabled, this will result in memory leakage.") return &defaultCacheMutationDetector{name: name, period: 1 * time.Second, retainDuration: 2 * time.Minute} } diff --git a/tools/cache/mutation_detector_test.go b/tools/cache/mutation_detector_test.go index 589b87a099..fab9f4dd07 100644 --- a/tools/cache/mutation_detector_test.go +++ b/tools/cache/mutation_detector_test.go @@ -20,7 +20,7 @@ import ( "testing" "time" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/wait" @@ -29,7 +29,7 @@ import ( func TestMutationDetector(t *testing.T) { fakeWatch := watch.NewFake() - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return fakeWatch, nil }, diff --git a/tools/cache/processor_listener_test.go b/tools/cache/processor_listener_test.go index fd658197d4..517258a160 100644 --- a/tools/cache/processor_listener_test.go +++ b/tools/cache/processor_listener_test.go @@ -22,6 +22,7 @@ import ( "time" "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/klog/v2" ) const ( @@ -35,7 +36,7 @@ func BenchmarkListener(b *testing.B) { swg.Add(b.N) b.SetParallelism(concurrencyLevel) // Preallocate enough space so that benchmark does not run out of it - pl := newProcessListener(&ResourceEventHandlerFuncs{ + pl := newProcessListener(klog.Background(), &ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { swg.Done() }, diff --git a/tools/cache/reflector.go b/tools/cache/reflector.go index 030b452979..8e2a827002 100644 --- a/tools/cache/reflector.go +++ b/tools/cache/reflector.go @@ -55,6 +55,28 @@ var ( defaultMinWatchTimeout = 5 * time.Minute ) +// ReflectorStore is the subset of cache.Store that the reflector uses +type ReflectorStore interface { + // Add adds the given object to the accumulator associated with the given object's key + Add(obj interface{}) error + + // Update updates the given object in the accumulator associated with the given object's key + Update(obj interface{}) error + + // Delete deletes the given object from the accumulator associated with the given object's key + Delete(obj interface{}) error + + // Replace will delete the contents of the store, using instead the + // given list. Store takes ownership of the list, you should not reference + // it after calling this function. + Replace([]interface{}, string) error + + // Resync is meaningless in the terms appearing here but has + // meaning in some implementations that have non-trivial + // additional behavior (e.g., DeltaFIFO). + Resync() error +} + // Reflector watches a specified resource and causes all changes to be reflected in the given store. type Reflector struct { // name identifies this reflector. By default, it will be a file:line if possible. @@ -72,9 +94,9 @@ type Reflector struct { // The GVK of the object we expect to place in the store if unstructured. expectedGVK *schema.GroupVersionKind // The destination to sync up with the watch source - store Store + store ReflectorStore // listerWatcher is used to perform lists and watches. - listerWatcher ListerWatcher + listerWatcher ListerWatcherWithContext // backoff manages backoff of ListWatch backoffManager wait.BackoffManager resyncPeriod time.Duration @@ -95,7 +117,7 @@ type Reflector struct { // lastSyncResourceVersionMutex guards read/write access to lastSyncResourceVersion lastSyncResourceVersionMutex sync.RWMutex // Called whenever the ListAndWatch drops the connection with an error. - watchErrorHandler WatchErrorHandler + watchErrorHandler WatchErrorHandlerWithContext // WatchListPageSize is the requested chunk size of initial and resync watch lists. // If unset, for consistent reads (RV="") or reads that opt-into arbitrarily old data // (RV="0") it will default to pager.PageSize, for the rest (RV != "" && RV != "0") @@ -150,20 +172,32 @@ type ResourceVersionUpdater interface { // should be offloaded. type WatchErrorHandler func(r *Reflector, err error) -// DefaultWatchErrorHandler is the default implementation of WatchErrorHandler -func DefaultWatchErrorHandler(r *Reflector, err error) { +// The WatchErrorHandler is called whenever ListAndWatch drops the +// connection with an error. After calling this handler, the informer +// will backoff and retry. +// +// The default implementation looks at the error type and tries to log +// the error message at an appropriate level. +// +// Implementations of this handler may display the error message in other +// ways. Implementations should return quickly - any expensive processing +// should be offloaded. +type WatchErrorHandlerWithContext func(ctx context.Context, r *Reflector, err error) + +// DefaultWatchErrorHandler is the default implementation of WatchErrorHandlerWithContext. +func DefaultWatchErrorHandler(ctx context.Context, r *Reflector, err error) { switch { case isExpiredError(err): // Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already // has a semantic that it returns data at least as fresh as provided RV. // So first try to LIST with setting RV to resource version of last observed object. - klog.V(4).Infof("%s: watch of %v closed with: %v", r.name, r.typeDescription, err) + klog.FromContext(ctx).V(4).Info("Watch closed", "reflector", r.name, "type", r.typeDescription, "err", err) case err == io.EOF: // watch closed normally case err == io.ErrUnexpectedEOF: - klog.V(1).Infof("%s: Watch for %v closed with unexpected EOF: %v", r.name, r.typeDescription, err) + klog.FromContext(ctx).V(1).Info("Watch closed with unexpected EOF", "reflector", r.name, "type", r.typeDescription, "err", err) default: - utilruntime.HandleError(fmt.Errorf("%s: Failed to watch %v: %v", r.name, r.typeDescription, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Failed to watch", "reflector", r.name, "type", r.typeDescription) } } @@ -177,13 +211,13 @@ func NewNamespaceKeyedIndexerAndReflector(lw ListerWatcher, expectedType interfa // NewReflector creates a new Reflector with its name defaulted to the closest source_file.go:line in the call stack // that is outside this package. See NewReflectorWithOptions for further information. -func NewReflector(lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector { +func NewReflector(lw ListerWatcher, expectedType interface{}, store ReflectorStore, resyncPeriod time.Duration) *Reflector { return NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{ResyncPeriod: resyncPeriod}) } // NewNamedReflector creates a new Reflector with the specified name. See NewReflectorWithOptions for further // information. -func NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector { +func NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store ReflectorStore, resyncPeriod time.Duration) *Reflector { return NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{Name: name, ResyncPeriod: resyncPeriod}) } @@ -222,7 +256,7 @@ type ReflectorOptions struct { // "yes". This enables you to use reflectors to periodically process // everything as well as incrementally processing the things that // change. -func NewReflectorWithOptions(lw ListerWatcher, expectedType interface{}, store Store, options ReflectorOptions) *Reflector { +func NewReflectorWithOptions(lw ListerWatcher, expectedType interface{}, store ReflectorStore, options ReflectorOptions) *Reflector { reflectorClock := options.Clock if reflectorClock == nil { reflectorClock = clock.RealClock{} @@ -236,14 +270,14 @@ func NewReflectorWithOptions(lw ListerWatcher, expectedType interface{}, store S resyncPeriod: options.ResyncPeriod, minWatchTimeout: minWatchTimeout, typeDescription: options.TypeDescription, - listerWatcher: lw, + listerWatcher: ToListerWatcherWithContext(lw), store: store, // We used to make the call every 1sec (1 QPS), the goal here is to achieve ~98% traffic reduction when // API server is not healthy. With these parameters, backoff will stop at [30,60) sec interval which is // 0.22 QPS. If we don't backoff for 2min, assume API server is healthy and we reset the backoff. backoffManager: wait.NewExponentialBackoffManager(800*time.Millisecond, 30*time.Second, 2*time.Minute, 2.0, 1.0, reflectorClock), clock: reflectorClock, - watchErrorHandler: WatchErrorHandler(DefaultWatchErrorHandler), + watchErrorHandler: WatchErrorHandlerWithContext(DefaultWatchErrorHandler), expectedType: reflect.TypeOf(expectedType), } @@ -309,14 +343,24 @@ var internalPackages = []string{"client-go/tools/cache/"} // Run repeatedly uses the reflector's ListAndWatch to fetch all the // objects and subsequent deltas. // Run will exit when stopCh is closed. +// +// Contextual logging: RunWithContext should be used instead of Run in code which supports contextual logging. func (r *Reflector) Run(stopCh <-chan struct{}) { - klog.V(3).Infof("Starting reflector %s (%s) from %s", r.typeDescription, r.resyncPeriod, r.name) + r.RunWithContext(wait.ContextForChannel(stopCh)) +} + +// RunWithContext repeatedly uses the reflector's ListAndWatch to fetch all the +// objects and subsequent deltas. +// Run will exit when the context is canceled. +func (r *Reflector) RunWithContext(ctx context.Context) { + logger := klog.FromContext(ctx) + logger.V(3).Info("Starting reflector", "type", r.typeDescription, "resyncPeriod", r.resyncPeriod, "reflector", r.name) wait.BackoffUntil(func() { - if err := r.ListAndWatch(stopCh); err != nil { - r.watchErrorHandler(r, err) + if err := r.ListAndWatchWithContext(ctx); err != nil { + r.watchErrorHandler(ctx, r, err) } - }, r.backoffManager, true, stopCh) - klog.V(3).Infof("Stopping reflector %s (%s) from %s", r.typeDescription, r.resyncPeriod, r.name) + }, r.backoffManager, true, ctx.Done()) + logger.V(3).Info("Stopping reflector", "type", r.typeDescription, "resyncPeriod", r.resyncPeriod, "reflector", r.name) } var ( @@ -345,21 +389,31 @@ func (r *Reflector) resyncChan() (<-chan time.Time, func() bool) { // ListAndWatch first lists all items and get the resource version at the moment of call, // and then use the resource version to watch. // It returns error if ListAndWatch didn't even try to initialize watch. +// +// Contextual logging: ListAndWatchWithContext should be used instead of ListAndWatch in code which supports contextual logging. func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { - klog.V(3).Infof("Listing and watching %v from %s", r.typeDescription, r.name) + return r.ListAndWatchWithContext(wait.ContextForChannel(stopCh)) +} + +// ListAndWatchWithContext first lists all items and get the resource version at the moment of call, +// and then use the resource version to watch. +// It returns error if ListAndWatchWithContext didn't even try to initialize watch. +func (r *Reflector) ListAndWatchWithContext(ctx context.Context) error { + logger := klog.FromContext(ctx) + logger.V(3).Info("Listing and watching", "type", r.typeDescription, "reflector", r.name) var err error var w watch.Interface useWatchList := ptr.Deref(r.UseWatchList, false) fallbackToList := !useWatchList if useWatchList { - w, err = r.watchList(stopCh) + w, err = r.watchList(ctx) if w == nil && err == nil { // stopCh was closed return nil } if err != nil { - klog.Warningf("The watchlist request ended with an error, falling back to the standard LIST/WATCH semantics because making progress is better than deadlocking, err = %v", err) + logger.Error(err, "The watchlist request ended with an error, falling back to the standard LIST/WATCH semantics because making progress is better than deadlocking") fallbackToList = true // ensure that we won't accidentally pass some garbage down the watch. w = nil @@ -367,20 +421,21 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { } if fallbackToList { - err = r.list(stopCh) + err = r.list(ctx) if err != nil { return err } } - klog.V(2).Infof("Caches populated for %v from %s", r.typeDescription, r.name) - return r.watchWithResync(w, stopCh) + logger.V(2).Info("Caches populated", "type", r.typeDescription, "reflector", r.name) + return r.watchWithResync(ctx, w) } // startResync periodically calls r.store.Resync() method. // Note that this method is blocking and should be // called in a separate goroutine. -func (r *Reflector) startResync(stopCh <-chan struct{}, cancelCh <-chan struct{}, resyncerrc chan error) { +func (r *Reflector) startResync(ctx context.Context, resyncerrc chan error) { + logger := klog.FromContext(ctx) resyncCh, cleanup := r.resyncChan() defer func() { cleanup() // Call the last one written into cleanup @@ -388,13 +443,11 @@ func (r *Reflector) startResync(stopCh <-chan struct{}, cancelCh <-chan struct{} for { select { case <-resyncCh: - case <-stopCh: - return - case <-cancelCh: + case <-ctx.Done(): return } if r.ShouldResync == nil || r.ShouldResync() { - klog.V(4).Infof("%s: forcing resync", r.name) + logger.V(4).Info("Forcing resync", "reflector", r.name) if err := r.store.Resync(); err != nil { resyncerrc <- err return @@ -406,16 +459,27 @@ func (r *Reflector) startResync(stopCh <-chan struct{}, cancelCh <-chan struct{} } // watchWithResync runs watch with startResync in the background. -func (r *Reflector) watchWithResync(w watch.Interface, stopCh <-chan struct{}) error { +func (r *Reflector) watchWithResync(ctx context.Context, w watch.Interface) error { resyncerrc := make(chan error, 1) - cancelCh := make(chan struct{}) - defer close(cancelCh) - go r.startResync(stopCh, cancelCh, resyncerrc) - return r.watch(w, stopCh, resyncerrc) + cancelCtx, cancel := context.WithCancel(ctx) + // Waiting for completion of the goroutine is relevant for race detector. + // Without this, there is a race between "this function returns + code + // waiting for it" and "goroutine does something". + var wg wait.Group + defer func() { + cancel() + wg.Wait() + }() + wg.Start(func() { + r.startResync(cancelCtx, resyncerrc) + }) + return r.watch(ctx, w, resyncerrc) } // watch simply starts a watch request with the server. -func (r *Reflector) watch(w watch.Interface, stopCh <-chan struct{}, resyncerrc chan error) error { +func (r *Reflector) watch(ctx context.Context, w watch.Interface, resyncerrc chan error) error { + stopCh := ctx.Done() + logger := klog.FromContext(ctx) var err error retry := NewRetryWithDeadline(r.MaxInternalErrorRetryDuration, time.Minute, apierrors.IsInternalError, r.clock) @@ -448,10 +512,10 @@ func (r *Reflector) watch(w watch.Interface, stopCh <-chan struct{}, resyncerrc AllowWatchBookmarks: true, } - w, err = r.listerWatcher.Watch(options) + w, err = r.listerWatcher.WatchWithContext(ctx, options) if err != nil { if canRetry := isWatchErrorRetriable(err); canRetry { - klog.V(4).Infof("%s: watch of %v returned %v - backing off", r.name, r.typeDescription, err) + logger.V(4).Info("Watch failed - backing off", "reflector", r.name, "type", r.typeDescription, "err", err) select { case <-stopCh: return nil @@ -463,8 +527,8 @@ func (r *Reflector) watch(w watch.Interface, stopCh <-chan struct{}, resyncerrc } } - err = handleWatch(start, w, r.store, r.expectedType, r.expectedGVK, r.name, r.typeDescription, r.setLastSyncResourceVersion, - r.clock, resyncerrc, stopCh) + err = handleWatch(ctx, start, w, r.store, r.expectedType, r.expectedGVK, r.name, r.typeDescription, r.setLastSyncResourceVersion, + r.clock, resyncerrc) // Ensure that watch will not be reused across iterations. w.Stop() w = nil @@ -476,9 +540,9 @@ func (r *Reflector) watch(w watch.Interface, stopCh <-chan struct{}, resyncerrc // Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already // has a semantic that it returns data at least as fresh as provided RV. // So first try to LIST with setting RV to resource version of last observed object. - klog.V(4).Infof("%s: watch of %v closed with: %v", r.name, r.typeDescription, err) + logger.V(4).Info("Watch closed", "reflector", r.name, "type", r.typeDescription, "err", err) case apierrors.IsTooManyRequests(err): - klog.V(2).Infof("%s: watch of %v returned 429 - backing off", r.name, r.typeDescription) + logger.V(2).Info("Watch returned 429 - backing off", "reflector", r.name, "type", r.typeDescription) select { case <-stopCh: return nil @@ -486,10 +550,10 @@ func (r *Reflector) watch(w watch.Interface, stopCh <-chan struct{}, resyncerrc continue } case apierrors.IsInternalError(err) && retry.ShouldRetry(): - klog.V(2).Infof("%s: retrying watch of %v internal error: %v", r.name, r.typeDescription, err) + logger.V(2).Info("Retrying watch after internal error", "reflector", r.name, "type", r.typeDescription, "err", err) continue default: - klog.Warningf("%s: watch of %v ended with: %v", r.name, r.typeDescription, err) + logger.Info("Warning: watch ended with error", "reflector", r.name, "type", r.typeDescription, "err", err) } } return nil @@ -499,7 +563,7 @@ func (r *Reflector) watch(w watch.Interface, stopCh <-chan struct{}, resyncerrc // list simply lists all items and records a resource version obtained from the server at the moment of the call. // the resource version can be used for further progress notification (aka. watch). -func (r *Reflector) list(stopCh <-chan struct{}) error { +func (r *Reflector) list(ctx context.Context) error { var resourceVersion string options := metav1.ListOptions{ResourceVersion: r.relistResourceVersion()} @@ -519,7 +583,7 @@ func (r *Reflector) list(stopCh <-chan struct{}) error { // Attempt to gather list in chunks, if supported by listerWatcher, if not, the first // list request will return the full response. pager := pager.New(pager.SimplePageFunc(func(opts metav1.ListOptions) (runtime.Object, error) { - return r.listerWatcher.List(opts) + return r.listerWatcher.ListWithContext(ctx, opts) })) switch { case r.WatchListPageSize != 0: @@ -558,7 +622,7 @@ func (r *Reflector) list(stopCh <-chan struct{}) error { close(listCh) }() select { - case <-stopCh: + case <-ctx.Done(): return nil case r := <-panicCh: panic(r) @@ -566,7 +630,6 @@ func (r *Reflector) list(stopCh <-chan struct{}) error { } initTrace.Step("Objects listed", trace.Field{Key: "error", Value: err}) if err != nil { - klog.Warningf("%s: failed to list %v: %v", r.name, r.typeDescription, err) return fmt.Errorf("failed to list %v: %w", r.typeDescription, err) } @@ -624,7 +687,9 @@ func (r *Reflector) list(stopCh <-chan struct{}) error { // After receiving a "Bookmark" event the reflector is considered to be synchronized. // It replaces its internal store with the collected items and // reuses the current watch requests for getting further events. -func (r *Reflector) watchList(stopCh <-chan struct{}) (watch.Interface, error) { +func (r *Reflector) watchList(ctx context.Context) (watch.Interface, error) { + stopCh := ctx.Done() + logger := klog.FromContext(ctx) var w watch.Interface var err error var temporaryStore Store @@ -634,7 +699,7 @@ func (r *Reflector) watchList(stopCh <-chan struct{}) (watch.Interface, error) { // could be unified with the r.watch method isErrorRetriableWithSideEffectsFn := func(err error) bool { if canRetry := isWatchErrorRetriable(err); canRetry { - klog.V(2).Infof("%s: watch-list of %v returned %v - backing off", r.name, r.typeDescription, err) + logger.V(2).Info("watch-list failed - backing off", "reflector", r.name, "type", r.typeDescription, "err", err) <-r.backoffManager.Backoff().C() return true } @@ -674,16 +739,16 @@ func (r *Reflector) watchList(stopCh <-chan struct{}) (watch.Interface, error) { } start := r.clock.Now() - w, err = r.listerWatcher.Watch(options) + w, err = r.listerWatcher.WatchWithContext(ctx, options) if err != nil { if isErrorRetriableWithSideEffectsFn(err) { continue } return nil, err } - watchListBookmarkReceived, err := handleListWatch(start, w, temporaryStore, r.expectedType, r.expectedGVK, r.name, r.typeDescription, + watchListBookmarkReceived, err := handleListWatch(ctx, start, w, temporaryStore, r.expectedType, r.expectedGVK, r.name, r.typeDescription, func(rv string) { resourceVersion = rv }, - r.clock, make(chan error), stopCh) + r.clock, make(chan error)) if err != nil { w.Stop() // stop and retry with clean state if errors.Is(err, errorStopRequested) { @@ -706,7 +771,7 @@ func (r *Reflector) watchList(stopCh <-chan struct{}) (watch.Interface, error) { // we utilize the temporaryStore to ensure independence from the current store implementation. // as of today, the store is implemented as a queue and will be drained by the higher-level // component as soon as it finishes replacing the content. - checkWatchListDataConsistencyIfRequested(wait.ContextForChannel(stopCh), r.name, resourceVersion, wrapListFuncWithContext(r.listerWatcher.List), temporaryStore.List) + checkWatchListDataConsistencyIfRequested(ctx, r.name, resourceVersion, r.listerWatcher.ListWithContext, temporaryStore.List) if err := r.store.Replace(temporaryStore.List(), resourceVersion); err != nil { return nil, fmt.Errorf("unable to sync watch-list result: %w", err) @@ -731,6 +796,7 @@ func (r *Reflector) syncWith(items []runtime.Object, resourceVersion string) err // retry. If successful, the watcher will be left open after receiving the // initial set of objects, to allow watching for future events. func handleListWatch( + ctx context.Context, start time.Time, w watch.Interface, store Store, @@ -741,20 +807,20 @@ func handleListWatch( setLastSyncResourceVersion func(string), clock clock.Clock, errCh chan error, - stopCh <-chan struct{}, ) (bool, error) { exitOnWatchListBookmarkReceived := true - return handleAnyWatch(start, w, store, expectedType, expectedGVK, name, expectedTypeName, - setLastSyncResourceVersion, exitOnWatchListBookmarkReceived, clock, errCh, stopCh) + return handleAnyWatch(ctx, start, w, store, expectedType, expectedGVK, name, expectedTypeName, + setLastSyncResourceVersion, exitOnWatchListBookmarkReceived, clock, errCh) } // handleListWatch consumes events from w, updates the Store, and records the // last seen ResourceVersion, to allow continuing from that ResourceVersion on // retry. The watcher will always be stopped on exit. func handleWatch( + ctx context.Context, start time.Time, w watch.Interface, - store Store, + store ReflectorStore, expectedType reflect.Type, expectedGVK *schema.GroupVersionKind, name string, @@ -762,11 +828,10 @@ func handleWatch( setLastSyncResourceVersion func(string), clock clock.Clock, errCh chan error, - stopCh <-chan struct{}, ) error { exitOnWatchListBookmarkReceived := false - _, err := handleAnyWatch(start, w, store, expectedType, expectedGVK, name, expectedTypeName, - setLastSyncResourceVersion, exitOnWatchListBookmarkReceived, clock, errCh, stopCh) + _, err := handleAnyWatch(ctx, start, w, store, expectedType, expectedGVK, name, expectedTypeName, + setLastSyncResourceVersion, exitOnWatchListBookmarkReceived, clock, errCh) return err } @@ -779,9 +844,11 @@ func handleWatch( // The watcher will always be stopped, unless exitOnWatchListBookmarkReceived is // true and watchListBookmarkReceived is true. This allows the same watch stream // to be re-used by the caller to continue watching for new events. -func handleAnyWatch(start time.Time, +func handleAnyWatch( + ctx context.Context, + start time.Time, w watch.Interface, - store Store, + store ReflectorStore, expectedType reflect.Type, expectedGVK *schema.GroupVersionKind, name string, @@ -790,17 +857,17 @@ func handleAnyWatch(start time.Time, exitOnWatchListBookmarkReceived bool, clock clock.Clock, errCh chan error, - stopCh <-chan struct{}, ) (bool, error) { watchListBookmarkReceived := false eventCount := 0 - initialEventsEndBookmarkWarningTicker := newInitialEventsEndBookmarkTicker(name, clock, start, exitOnWatchListBookmarkReceived) + logger := klog.FromContext(ctx) + initialEventsEndBookmarkWarningTicker := newInitialEventsEndBookmarkTicker(logger, name, clock, start, exitOnWatchListBookmarkReceived) defer initialEventsEndBookmarkWarningTicker.Stop() loop: for { select { - case <-stopCh: + case <-ctx.Done(): return watchListBookmarkReceived, errorStopRequested case err := <-errCh: return watchListBookmarkReceived, err @@ -813,19 +880,19 @@ loop: } if expectedType != nil { if e, a := expectedType, reflect.TypeOf(event.Object); e != a { - utilruntime.HandleError(fmt.Errorf("%s: expected type %v, but watch event object had type %v", name, e, a)) + utilruntime.HandleErrorWithContext(ctx, nil, "Unexpected watch event object type", "reflector", name, "expectedType", e, "actualType", a) continue } } if expectedGVK != nil { if e, a := *expectedGVK, event.Object.GetObjectKind().GroupVersionKind(); e != a { - utilruntime.HandleError(fmt.Errorf("%s: expected gvk %v, but watch event object had gvk %v", name, e, a)) + utilruntime.HandleErrorWithContext(ctx, nil, "Unexpected watch event object gvk", "reflector", name, "expectedGVK", e, "actualGVK", a) continue } } meta, err := meta.Accessor(event.Object) if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: unable to understand watch event %#v", name, event)) + utilruntime.HandleErrorWithContext(ctx, err, "Unable to understand watch event", "reflector", name, "event", event) continue } resourceVersion := meta.GetResourceVersion() @@ -833,12 +900,12 @@ loop: case watch.Added: err := store.Add(event.Object) if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: unable to add watch event object (%#v) to store: %v", name, event.Object, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Unable to add watch event object to store", "reflector", name, "object", event.Object) } case watch.Modified: err := store.Update(event.Object) if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: unable to update watch event object (%#v) to store: %v", name, event.Object, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Unable to update watch event object to store", "reflector", name, "object", event.Object) } case watch.Deleted: // TODO: Will any consumers need access to the "last known @@ -846,7 +913,7 @@ loop: // to change this. err := store.Delete(event.Object) if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: unable to delete watch event object (%#v) from store: %v", name, event.Object, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Unable to delete watch event object from store", "reflector", name, "object", event.Object) } case watch.Bookmark: // A `Bookmark` means watch has synced here, just update the resourceVersion @@ -854,7 +921,7 @@ loop: watchListBookmarkReceived = true } default: - utilruntime.HandleError(fmt.Errorf("%s: unable to understand watch event %#v", name, event)) + utilruntime.HandleErrorWithContext(ctx, err, "Unknown watch event", "reflector", name, "event", event) } setLastSyncResourceVersion(resourceVersion) if rvu, ok := store.(ResourceVersionUpdater); ok { @@ -863,7 +930,7 @@ loop: eventCount++ if exitOnWatchListBookmarkReceived && watchListBookmarkReceived { watchDuration := clock.Since(start) - klog.V(4).Infof("exiting %v Watch because received the bookmark that marks the end of initial events stream, total %v items received in %v", name, eventCount, watchDuration) + klog.FromContext(ctx).V(4).Info("Exiting watch because received the bookmark that marks the end of initial events stream", "reflector", name, "totalItems", eventCount, "duration", watchDuration) return watchListBookmarkReceived, nil } initialEventsEndBookmarkWarningTicker.observeLastEventTimeStamp(clock.Now()) @@ -876,7 +943,7 @@ loop: if watchDuration < 1*time.Second && eventCount == 0 { return watchListBookmarkReceived, fmt.Errorf("very short watch: %s: Unexpected watch close - watch lasted less than a second and no items received", name) } - klog.V(4).Infof("%s: Watch close - %v total %v items received", name, expectedTypeName, eventCount) + klog.FromContext(ctx).V(4).Info("Watch close", "reflector", name, "type", expectedTypeName, "totalItems", eventCount) return watchListBookmarkReceived, nil } @@ -990,13 +1057,6 @@ func isWatchErrorRetriable(err error) bool { return false } -// wrapListFuncWithContext simply wraps ListFunction into another function that accepts a context and ignores it. -func wrapListFuncWithContext(listFn ListFunc) func(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { - return func(_ context.Context, options metav1.ListOptions) (runtime.Object, error) { - return listFn(options) - } -} - // initialEventsEndBookmarkTicker a ticker that produces a warning if the bookmark event // which marks the end of the watch stream, has not been received within the defined tick interval. // @@ -1004,8 +1064,9 @@ func wrapListFuncWithContext(listFn ListFunc) func(ctx context.Context, options // The methods exposed by this type are not thread-safe. type initialEventsEndBookmarkTicker struct { clock.Ticker - clock clock.Clock - name string + clock clock.Clock + name string + logger klog.Logger watchStart time.Time tickInterval time.Duration @@ -1019,15 +1080,15 @@ type initialEventsEndBookmarkTicker struct { // Note that the caller controls whether to call t.C() and t.Stop(). // // In practice, the reflector exits the watchHandler as soon as the bookmark event is received and calls the t.C() method. -func newInitialEventsEndBookmarkTicker(name string, c clock.Clock, watchStart time.Time, exitOnWatchListBookmarkReceived bool) *initialEventsEndBookmarkTicker { - return newInitialEventsEndBookmarkTickerInternal(name, c, watchStart, 10*time.Second, exitOnWatchListBookmarkReceived) +func newInitialEventsEndBookmarkTicker(logger klog.Logger, name string, c clock.Clock, watchStart time.Time, exitOnWatchListBookmarkReceived bool) *initialEventsEndBookmarkTicker { + return newInitialEventsEndBookmarkTickerInternal(logger, name, c, watchStart, 10*time.Second, exitOnWatchListBookmarkReceived) } -func newInitialEventsEndBookmarkTickerInternal(name string, c clock.Clock, watchStart time.Time, tickInterval time.Duration, exitOnWatchListBookmarkReceived bool) *initialEventsEndBookmarkTicker { +func newInitialEventsEndBookmarkTickerInternal(logger klog.Logger, name string, c clock.Clock, watchStart time.Time, tickInterval time.Duration, exitOnWatchListBookmarkReceived bool) *initialEventsEndBookmarkTicker { clockWithTicker, ok := c.(clock.WithTicker) if !ok || !exitOnWatchListBookmarkReceived { if exitOnWatchListBookmarkReceived { - klog.Warningf("clock does not support WithTicker interface but exitOnInitialEventsEndBookmark was requested") + logger.Info("Warning: clock does not support WithTicker interface but exitOnInitialEventsEndBookmark was requested") } return &initialEventsEndBookmarkTicker{ Ticker: &noopTicker{}, @@ -1038,6 +1099,7 @@ func newInitialEventsEndBookmarkTickerInternal(name string, c clock.Clock, watch Ticker: clockWithTicker.NewTicker(tickInterval), clock: c, name: name, + logger: logger, watchStart: watchStart, tickInterval: tickInterval, } @@ -1049,7 +1111,7 @@ func (t *initialEventsEndBookmarkTicker) observeLastEventTimeStamp(lastEventObse func (t *initialEventsEndBookmarkTicker) warnIfExpired() { if err := t.produceWarningIfExpired(); err != nil { - klog.Warning(err) + t.logger.Info("Warning: event bookmark expired", "err", err) } } diff --git a/tools/cache/reflector_test.go b/tools/cache/reflector_test.go index a56fce6e4b..d7614f3641 100644 --- a/tools/cache/reflector_test.go +++ b/tools/cache/reflector_test.go @@ -45,29 +45,19 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" + "k8s.io/klog/v2/ktesting" "k8s.io/utils/clock" testingclock "k8s.io/utils/clock/testing" ) var nevererrc chan error -type testLW struct { - ListFunc func(options metav1.ListOptions) (runtime.Object, error) - WatchFunc func(options metav1.ListOptions) (watch.Interface, error) -} - -func (t *testLW) List(options metav1.ListOptions) (runtime.Object, error) { - return t.ListFunc(options) -} -func (t *testLW) Watch(options metav1.ListOptions) (watch.Interface, error) { - return t.WatchFunc(options) -} - func TestCloseWatchChannelOnError(t *testing.T) { - r := NewReflector(&testLW{}, &v1.Pod{}, NewStore(MetaNamespaceKeyFunc), 0) + _, ctx := ktesting.NewTestContext(t) + r := NewReflector(&ListWatch{}, &v1.Pod{}, NewStore(MetaNamespaceKeyFunc), 0) pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "bar"}} fw := watch.NewFake() - r.listerWatcher = &testLW{ + r.listerWatcher = &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return fw, nil }, @@ -75,7 +65,7 @@ func TestCloseWatchChannelOnError(t *testing.T) { return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "1"}}, nil }, } - go r.ListAndWatch(wait.NeverStop) + go func() { assert.NoError(t, r.ListAndWatchWithContext(ctx)) }() fw.Error(pod) select { case _, ok := <-fw.ResultChan(): @@ -89,11 +79,12 @@ func TestCloseWatchChannelOnError(t *testing.T) { } func TestRunUntil(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) store := NewStore(MetaNamespaceKeyFunc) - r := NewReflector(&testLW{}, &v1.Pod{}, store, 0) + r := NewReflector(&ListWatch{}, &v1.Pod{}, store, 0) fw := watch.NewFake() - r.listerWatcher = &testLW{ + r.listerWatcher = &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return fw, nil }, @@ -104,13 +95,13 @@ func TestRunUntil(t *testing.T) { doneCh := make(chan struct{}) go func() { defer close(doneCh) - r.Run(stopCh) + r.RunWithContext(ctx) }() // Synchronously add a dummy pod into the watch channel so we // know the RunUntil go routine is in the watch handler. fw.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "bar"}}) - close(stopCh) + cancel(errors.New("done")) resultCh := fw.ResultChan() for { select { @@ -135,7 +126,7 @@ func TestRunUntil(t *testing.T) { func TestReflectorResyncChan(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, time.Millisecond) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, time.Millisecond) a, _ := g.resyncChan() b := time.After(wait.ForeverTestTimeout) select { @@ -149,8 +140,9 @@ func TestReflectorResyncChan(t *testing.T) { // TestReflectorWatchStoppedBefore ensures that neither List nor Watch are // called if the stop channel is closed before Reflector.watch is called. func TestReflectorWatchStoppedBefore(t *testing.T) { - stopCh := make(chan struct{}) - close(stopCh) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) + cancel(errors.New("don't run")) lw := &ListWatch{ ListFunc: func(_ metav1.ListOptions) (runtime.Object, error) { @@ -165,14 +157,15 @@ func TestReflectorWatchStoppedBefore(t *testing.T) { } target := NewReflector(lw, &v1.Pod{}, nil, 0) - err := target.watch(nil, stopCh, nil) + err := target.watch(ctx, nil, nil) require.NoError(t, err) } // TestReflectorWatchStoppedAfter ensures that neither the watcher is stopped if // the stop channel is closed after Reflector.watch has started watching. func TestReflectorWatchStoppedAfter(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) var watchers []*watch.FakeWatcher @@ -185,7 +178,7 @@ func TestReflectorWatchStoppedAfter(t *testing.T) { // Simulate the stop channel being closed after watching has started go func() { time.Sleep(10 * time.Millisecond) - close(stopCh) + cancel(errors.New("10ms timeout reached")) }() // Use a fake watcher that never sends events w := watch.NewFake() @@ -195,7 +188,7 @@ func TestReflectorWatchStoppedAfter(t *testing.T) { } target := NewReflector(lw, &v1.Pod{}, nil, 0) - err := target.watch(nil, stopCh, nil) + err := target.watch(ctx, nil, nil) require.NoError(t, err) require.Len(t, watchers, 1) require.True(t, watchers[0].IsStopped()) @@ -203,7 +196,7 @@ func TestReflectorWatchStoppedAfter(t *testing.T) { func BenchmarkReflectorResyncChanMany(b *testing.B) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 25*time.Millisecond) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, 25*time.Millisecond) // The improvement to this (calling the timer's Stop() method) makes // this benchmark about 40% faster. for i := 0; i < b.N; i++ { @@ -218,10 +211,11 @@ func BenchmarkReflectorResyncChanMany(b *testing.B) { // ResultChan is only called once and that Stop is called after ResultChan. func TestReflectorHandleWatchStoppedBefore(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) - stopCh := make(chan struct{}) - // Simulate the watch channel being closed before the watchHandler is called - close(stopCh) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, 0) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) + // Simulate the context being canceled before the watchHandler is called + cancel(errors.New("don't run")) var calls []string resultCh := make(chan watch.Event) fw := watch.MockWatcher{ @@ -234,7 +228,7 @@ func TestReflectorHandleWatchStoppedBefore(t *testing.T) { return resultCh }, } - err := handleWatch(time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc, stopCh) + err := handleWatch(ctx, time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc) if err == nil { t.Errorf("unexpected non-error") } @@ -249,9 +243,10 @@ func TestReflectorHandleWatchStoppedBefore(t *testing.T) { // ResultChan is only called once and that Stop is called after ResultChan. func TestReflectorHandleWatchStoppedAfter(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, 0) var calls []string - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) resultCh := make(chan watch.Event) fw := watch.MockWatcher{ StopFunc: func() { @@ -265,12 +260,12 @@ func TestReflectorHandleWatchStoppedAfter(t *testing.T) { // caller, after watching has started. go func() { time.Sleep(10 * time.Millisecond) - close(stopCh) + cancel(errors.New("10ms timeout reached")) }() return resultCh }, } - err := handleWatch(time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc, stopCh) + err := handleWatch(ctx, time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc) if err == nil { t.Errorf("unexpected non-error") } @@ -284,7 +279,8 @@ func TestReflectorHandleWatchStoppedAfter(t *testing.T) { // stops when the result channel is closed before handleWatch was called. func TestReflectorHandleWatchResultChanClosedBefore(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, 0) + _, ctx := ktesting.NewTestContext(t) var calls []string resultCh := make(chan watch.Event) fw := watch.MockWatcher{ @@ -298,7 +294,7 @@ func TestReflectorHandleWatchResultChanClosedBefore(t *testing.T) { } // Simulate the result channel being closed by the producer before handleWatch is called. close(resultCh) - err := handleWatch(time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc, wait.NeverStop) + err := handleWatch(ctx, time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc) if err == nil { t.Errorf("unexpected non-error") } @@ -312,7 +308,8 @@ func TestReflectorHandleWatchResultChanClosedBefore(t *testing.T) { // stops when the result channel is closed after handleWatch has started watching. func TestReflectorHandleWatchResultChanClosedAfter(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, 0) + _, ctx := ktesting.NewTestContext(t) var calls []string resultCh := make(chan watch.Event) fw := watch.MockWatcher{ @@ -331,7 +328,7 @@ func TestReflectorHandleWatchResultChanClosedAfter(t *testing.T) { return resultCh }, } - err := handleWatch(time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc, wait.NeverStop) + err := handleWatch(ctx, time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc) if err == nil { t.Errorf("unexpected non-error") } @@ -343,16 +340,17 @@ func TestReflectorHandleWatchResultChanClosedAfter(t *testing.T) { func TestReflectorWatchHandler(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, 0) // Wrap setLastSyncResourceVersion so we can tell the watchHandler to stop // watching after all the events have been consumed. This avoids race // conditions which can happen if the producer calls Stop(), instead of the // consumer. - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) setLastSyncResourceVersion := func(rv string) { g.setLastSyncResourceVersion(rv) if rv == "32" { - close(stopCh) + cancel(errors.New("LastSyncResourceVersion is 32")) } } fw := watch.NewFake() @@ -365,7 +363,7 @@ func TestReflectorWatchHandler(t *testing.T) { fw.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "baz", ResourceVersion: "32"}}) fw.Stop() }() - err := handleWatch(time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, setLastSyncResourceVersion, g.clock, nevererrc, stopCh) + err := handleWatch(ctx, time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, setLastSyncResourceVersion, g.clock, nevererrc) // TODO(karlkfi): Fix FakeWatcher to avoid race condition between watcher.Stop() & close(stopCh) if err != nil && !errors.Is(err, errorStopRequested) { t.Errorf("unexpected error %v", err) @@ -406,24 +404,28 @@ func TestReflectorWatchHandler(t *testing.T) { func TestReflectorStopWatch(t *testing.T) { s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) + g := NewReflector(&ListWatch{}, &v1.Pod{}, s, 0) fw := watch.NewFake() - stopWatch := make(chan struct{}) - close(stopWatch) - err := handleWatch(time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc, stopWatch) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) + cancel(errors.New("don't run")) + err := handleWatch(ctx, time.Now(), fw, s, g.expectedType, g.expectedGVK, g.name, g.typeDescription, g.setLastSyncResourceVersion, g.clock, nevererrc) if err != errorStopRequested { t.Errorf("expected stop error, got %q", err) } } func TestReflectorListAndWatch(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancel(ctx) + defer cancel() createdFakes := make(chan *watch.FakeWatcher) // The ListFunc says that it's at revision 1. Therefore, we expect our WatchFunc // to get called at the beginning of the watch with 1, and again with 3 when we // inject an error. expectedRVs := []string{"1", "3"} - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { rv := options.ResourceVersion fw := watch.NewFake() @@ -442,7 +444,7 @@ func TestReflectorListAndWatch(t *testing.T) { } s := NewFIFO(MetaNamespaceKeyFunc) r := NewReflector(lw, &v1.Pod{}, s, 0) - go r.ListAndWatch(wait.NeverStop) + go func() { assert.NoError(t, r.ListAndWatchWithContext(ctx)) }() ids := []string{"foo", "bar", "baz", "qux", "zoo"} var fw *watch.FakeWatcher @@ -539,8 +541,9 @@ func TestReflectorListAndWatchWithErrors(t *testing.T) { } } watchRet, watchErr := item.events, item.watchErr - stopCh := make(chan struct{}) - lw := &testLW{ + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if watchErr != nil { return nil, watchErr @@ -557,7 +560,7 @@ func TestReflectorListAndWatchWithErrors(t *testing.T) { // result channel, and wait for the consumer to stop the // watcher, to avoid race conditions. // TODO: Fix the FakeWatcher to separate watcher.Stop from close(resultCh) - close(stopCh) + cancel(errors.New("done")) }() return fw, nil }, @@ -566,7 +569,7 @@ func TestReflectorListAndWatchWithErrors(t *testing.T) { }, } r := NewReflector(lw, &v1.Pod{}, s, 0) - err := r.ListAndWatch(stopCh) + err := r.ListAndWatchWithContext(ctx) if item.listErr != nil && !errors.Is(err, item.listErr) { t.Errorf("unexpected ListAndWatch error: %v", err) } @@ -593,7 +596,8 @@ func TestReflectorListAndWatchInitConnBackoff(t *testing.T) { for _, test := range table { t.Run(fmt.Sprintf("%d connection failures takes at least %d ms", test.numConnFails, 1< 0 { connFails-- return nil, syscall.ECONNREFUSED } - close(stopCh) + cancel(errors.New("done")) return watch.NewFake(), nil }, ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { @@ -637,10 +641,10 @@ func TestReflectorListAndWatchInitConnBackoff(t *testing.T) { store: NewFIFO(MetaNamespaceKeyFunc), backoffManager: bm, clock: fakeClock, - watchErrorHandler: WatchErrorHandler(DefaultWatchErrorHandler), + watchErrorHandler: WatchErrorHandlerWithContext(DefaultWatchErrorHandler), } start := fakeClock.Now() - err := r.ListAndWatch(stopCh) + err := r.ListAndWatchWithContext(ctx) elapsed := fakeClock.Since(start) if err != nil { t.Errorf("unexpected error %v", err) @@ -666,11 +670,12 @@ func (f *fakeBackoff) Backoff() clock.Timer { } func TestBackoffOnTooManyRequests(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) err := apierrors.NewTooManyRequests("too many requests", 1) clock := &clock.RealClock{} bm := &fakeBackoff{clock: clock} - lw := &testLW{ + lw := &ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "1"}}, nil }, @@ -697,11 +702,11 @@ func TestBackoffOnTooManyRequests(t *testing.T) { store: NewFIFO(MetaNamespaceKeyFunc), backoffManager: bm, clock: clock, - watchErrorHandler: WatchErrorHandler(DefaultWatchErrorHandler), + watchErrorHandler: WatchErrorHandlerWithContext(DefaultWatchErrorHandler), } stopCh := make(chan struct{}) - if err := r.ListAndWatch(stopCh); err != nil { + if err := r.ListAndWatchWithContext(ctx); err != nil { t.Fatal(err) } close(stopCh) @@ -716,7 +721,7 @@ func TestNoRelistOnTooManyRequests(t *testing.T) { bm := &fakeBackoff{clock: clock} listCalls, watchCalls := 0, 0 - lw := &testLW{ + lw := &ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { listCalls++ return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "1"}}, nil @@ -738,14 +743,15 @@ func TestNoRelistOnTooManyRequests(t *testing.T) { store: NewFIFO(MetaNamespaceKeyFunc), backoffManager: bm, clock: clock, - watchErrorHandler: WatchErrorHandler(DefaultWatchErrorHandler), + watchErrorHandler: WatchErrorHandlerWithContext(DefaultWatchErrorHandler), } - stopCh := make(chan struct{}) - if err := r.ListAndWatch(stopCh); err != nil { + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) + if err := r.ListAndWatchWithContext(ctx); err != nil { t.Fatal(err) } - close(stopCh) + cancel(errors.New("done")) if listCalls != 1 { t.Errorf("unexpected list calls: %d", listCalls) } @@ -786,7 +792,7 @@ func TestRetryInternalError(t *testing.T) { counter := 0 - lw := &testLW{ + lw := &ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "1"}}, nil }, @@ -812,14 +818,15 @@ func TestRetryInternalError(t *testing.T) { store: NewFIFO(MetaNamespaceKeyFunc), backoffManager: bm, clock: fakeClock, - watchErrorHandler: WatchErrorHandler(DefaultWatchErrorHandler), + watchErrorHandler: WatchErrorHandlerWithContext(DefaultWatchErrorHandler), } r.MaxInternalErrorRetryDuration = tc.maxInternalDuration - stopCh := make(chan struct{}) - r.ListAndWatch(stopCh) - close(stopCh) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) + require.NoError(t, r.ListAndWatchWithContext(ctx)) + cancel(errors.New("done")) if counter-1 != tc.wantRetries { t.Errorf("%v unexpected number of retries: %d", tc, counter-1) @@ -829,7 +836,7 @@ func TestRetryInternalError(t *testing.T) { func TestReflectorResync(t *testing.T) { iteration := 0 - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) rerr := errors.New("expected resync reached") s := &FakeCustomStore{ ResyncFunc: func() error { @@ -841,7 +848,7 @@ func TestReflectorResync(t *testing.T) { }, } - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { fw := watch.NewFake() return fw, nil @@ -852,7 +859,7 @@ func TestReflectorResync(t *testing.T) { } resyncPeriod := 1 * time.Millisecond r := NewReflector(lw, &v1.Pod{}, s, resyncPeriod) - if err := r.ListAndWatch(stopCh); err != nil { + if err := r.ListAndWatchWithContext(ctx); err != nil { // error from Resync is not propaged up to here. t.Errorf("expected error %v", err) } @@ -862,13 +869,14 @@ func TestReflectorResync(t *testing.T) { } func TestReflectorWatchListPageSize(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) s := NewStore(MetaNamespaceKeyFunc) - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) fw := watch.NewFake() return fw, nil }, @@ -898,7 +906,7 @@ func TestReflectorWatchListPageSize(t *testing.T) { r.setLastSyncResourceVersion("10") // Set the reflector to paginate the list request in 4 item chunks. r.WatchListPageSize = 4 - r.ListAndWatch(stopCh) + require.NoError(t, r.ListAndWatchWithContext(ctx)) results := s.List() if len(results) != 10 { @@ -907,13 +915,14 @@ func TestReflectorWatchListPageSize(t *testing.T) { } func TestReflectorNotPaginatingNotConsistentReads(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) s := NewStore(MetaNamespaceKeyFunc) - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) fw := watch.NewFake() return fw, nil }, @@ -933,7 +942,7 @@ func TestReflectorNotPaginatingNotConsistentReads(t *testing.T) { } r := NewReflector(lw, &v1.Pod{}, s, 0) r.setLastSyncResourceVersion("10") - r.ListAndWatch(stopCh) + require.NoError(t, r.ListAndWatchWithContext(ctx)) results := s.List() if len(results) != 10 { @@ -942,13 +951,14 @@ func TestReflectorNotPaginatingNotConsistentReads(t *testing.T) { } func TestReflectorPaginatingNonConsistentReadsIfWatchCacheDisabled(t *testing.T) { - var stopCh chan struct{} + _, ctx := ktesting.NewTestContext(t) + var cancel func(error) s := NewStore(MetaNamespaceKeyFunc) - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) fw := watch.NewFake() return fw, nil }, @@ -977,16 +987,17 @@ func TestReflectorPaginatingNonConsistentReadsIfWatchCacheDisabled(t *testing.T) r := NewReflector(lw, &v1.Pod{}, s, 0) // Initial list should initialize paginatedResult in the reflector. - stopCh = make(chan struct{}) - r.ListAndWatch(stopCh) + var cancelCtx context.Context + cancelCtx, cancel = context.WithCancelCause(ctx) + require.NoError(t, r.ListAndWatchWithContext(cancelCtx)) if results := s.List(); len(results) != 10 { t.Errorf("Expected 10 results, got %d", len(results)) } // Since initial list for ResourceVersion="0" was paginated, the subsequent // ones should also be paginated. - stopCh = make(chan struct{}) - r.ListAndWatch(stopCh) + cancelCtx, cancel = context.WithCancelCause(ctx) + require.NoError(t, r.ListAndWatchWithContext(cancelCtx)) if results := s.List(); len(results) != 10 { t.Errorf("Expected 10 results, got %d", len(results)) } @@ -996,14 +1007,15 @@ func TestReflectorPaginatingNonConsistentReadsIfWatchCacheDisabled(t *testing.T) // it in relist requests to prevent the reflector from traveling back in time if the relist is to a api-server or // etcd that is partitioned and serving older data than the reflector has already processed. func TestReflectorResyncWithResourceVersion(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + cancelCtx, cancel := context.WithCancelCause(ctx) s := NewStore(MetaNamespaceKeyFunc) listCallRVs := []string{} - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) fw := watch.NewFake() return fw, nil }, @@ -1027,7 +1039,7 @@ func TestReflectorResyncWithResourceVersion(t *testing.T) { r := NewReflector(lw, &v1.Pod{}, s, 0) // Initial list should use RV=0 - r.ListAndWatch(stopCh) + require.NoError(t, r.ListAndWatchWithContext(cancelCtx)) results := s.List() if len(results) != 4 { @@ -1035,8 +1047,8 @@ func TestReflectorResyncWithResourceVersion(t *testing.T) { } // relist should use lastSyncResourceVersions (RV=10) - stopCh = make(chan struct{}) - r.ListAndWatch(stopCh) + cancelCtx, cancel = context.WithCancelCause(ctx) + require.NoError(t, r.ListAndWatchWithContext(cancelCtx)) results = s.List() if len(results) != 8 { @@ -1055,14 +1067,16 @@ func TestReflectorResyncWithResourceVersion(t *testing.T) { // (In kubernetes 1.17, or when the watch cache is enabled, the List will instead return the list that is no older than // the requested ResourceVersion). func TestReflectorExpiredExactResourceVersion(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + var cancelCtx context.Context + var cancel func(error) s := NewStore(MetaNamespaceKeyFunc) listCallRVs := []string{} - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) fw := watch.NewFake() return fw, nil }, @@ -1089,7 +1103,8 @@ func TestReflectorExpiredExactResourceVersion(t *testing.T) { r := NewReflector(lw, &v1.Pod{}, s, 0) // Initial list should use RV=0 - r.ListAndWatch(stopCh) + cancelCtx, cancel = context.WithCancelCause(ctx) + require.NoError(t, r.ListAndWatchWithContext(cancelCtx)) results := s.List() if len(results) != 4 { @@ -1097,8 +1112,8 @@ func TestReflectorExpiredExactResourceVersion(t *testing.T) { } // relist should use lastSyncResourceVersions (RV=10) and since RV=10 is expired, it should retry with RV="". - stopCh = make(chan struct{}) - r.ListAndWatch(stopCh) + cancelCtx, cancel = context.WithCancelCause(ctx) + require.NoError(t, r.ListAndWatchWithContext(cancelCtx)) results = s.List() if len(results) != 8 { @@ -1112,14 +1127,16 @@ func TestReflectorExpiredExactResourceVersion(t *testing.T) { } func TestReflectorFullListIfExpired(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + var cancelCtx context.Context + var cancel func(error) s := NewStore(MetaNamespaceKeyFunc) listCallRVs := []string{} - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) fw := watch.NewFake() return fw, nil }, @@ -1156,7 +1173,8 @@ func TestReflectorFullListIfExpired(t *testing.T) { r.WatchListPageSize = 4 // Initial list should use RV=0 - if err := r.ListAndWatch(stopCh); err != nil { + cancelCtx, cancel = context.WithCancelCause(ctx) + if err := r.ListAndWatchWithContext(cancelCtx); err != nil { t.Fatal(err) } @@ -1166,8 +1184,8 @@ func TestReflectorFullListIfExpired(t *testing.T) { } // relist should use lastSyncResourceVersions (RV=10) and since second page of that expired, it should full list with RV=10 - stopCh = make(chan struct{}) - if err := r.ListAndWatch(stopCh); err != nil { + cancelCtx, cancel = context.WithCancelCause(ctx) + if err := r.ListAndWatchWithContext(cancelCtx); err != nil { t.Fatal(err) } @@ -1183,15 +1201,17 @@ func TestReflectorFullListIfExpired(t *testing.T) { } func TestReflectorFullListIfTooLarge(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + var cancelCtx context.Context + var cancel func(error) s := NewStore(MetaNamespaceKeyFunc) listCallRVs := []string{} version := 30 - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) fw := watch.NewFake() return fw, nil }, @@ -1229,7 +1249,8 @@ func TestReflectorFullListIfTooLarge(t *testing.T) { r := NewReflector(lw, &v1.Pod{}, s, 0) // Initial list should use RV=0 - if err := r.ListAndWatch(stopCh); err != nil { + cancelCtx, cancel = context.WithCancelCause(ctx) + if err := r.ListAndWatchWithContext(cancelCtx); err != nil { t.Fatal(err) } @@ -1241,8 +1262,8 @@ func TestReflectorFullListIfTooLarge(t *testing.T) { // done we simply try to relist from now to avoid continuous errors on relists. for i := 1; i <= 3; i++ { // relist twice to cover the two variants of TooLargeResourceVersion api errors - stopCh = make(chan struct{}) - if err := r.ListAndWatch(stopCh); err != nil { + cancelCtx, cancel = context.WithCancelCause(ctx) + if err := r.ListAndWatchWithContext(cancelCtx); err != nil { t.Fatal(err) } } @@ -1356,11 +1377,12 @@ func TestWatchTimeout(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) s := NewStore(MetaNamespaceKeyFunc) var gotTimeoutSeconds int64 - lw := &testLW{ + lw := &ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "10"}}, nil }, @@ -1370,7 +1392,7 @@ func TestWatchTimeout(t *testing.T) { } // Stop once the reflector begins watching since we're only interested in the list. - close(stopCh) + cancel(errors.New("done")) return watch.NewFake(), nil }, } @@ -1379,7 +1401,7 @@ func TestWatchTimeout(t *testing.T) { MinWatchTimeout: tc.minWatchTimeout, } r := NewReflectorWithOptions(lw, &v1.Pod{}, s, opts) - if err := r.ListAndWatch(stopCh); err != nil { + if err := r.ListAndWatchWithContext(ctx); err != nil { t.Fatal(err) } @@ -1412,10 +1434,11 @@ func newStoreWithRV() *storeWithRV { func TestReflectorResourceVersionUpdate(t *testing.T) { s := newStoreWithRV() - stopCh := make(chan struct{}) + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancelCause(ctx) fw := watch.NewFake() - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return fw, nil }, @@ -1434,11 +1457,11 @@ func TestReflectorResourceVersionUpdate(t *testing.T) { fw.Action(watch.Modified, makePod("20")) fw.Action(watch.Bookmark, makePod("30")) fw.Action(watch.Deleted, makePod("40")) - close(stopCh) + cancel(errors.New("done")) }() // Initial list should use RV=0 - if err := r.ListAndWatch(stopCh); err != nil { + if err := r.ListAndWatchWithContext(ctx); err != nil { t.Fatal(err) } @@ -1680,6 +1703,7 @@ func (t *TestPagingPodsLW) Watch(options metav1.ListOptions) (watch.Interface, e } func TestReflectorListExtract(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) store := NewStore(func(obj interface{}) (string, error) { pod, ok := obj.(*v1.Pod) if !ok { @@ -1693,8 +1717,7 @@ func TestReflectorListExtract(t *testing.T) { reflector.WatchListPageSize = fakeItemsNum // execute list to fill store - stopCh := make(chan struct{}) - if err := reflector.list(stopCh); err != nil { + if err := reflector.list(ctx); err != nil { t.Fatal(err) } @@ -1831,7 +1854,7 @@ func TestReflectorReplacesStoreOnUnsafeDelete(t *testing.T) { } var once sync.Once - lw := &testLW{ + lw := &ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { fw := watch.NewFake() go func() { @@ -1857,6 +1880,7 @@ func TestReflectorReplacesStoreOnUnsafeDelete(t *testing.T) { doneCh, stopCh := make(chan struct{}), make(chan struct{}) go func() { defer close(doneCh) + //nolint:logcheck // Intentionally uses the old API. r.Run(stopCh) }() @@ -2031,9 +2055,6 @@ func BenchmarkEachListItemWithAlloc(b *testing.B) { } func BenchmarkReflectorList(b *testing.B) { - ctx, cancel := context.WithTimeout(context.Background(), wait.ForeverTestTimeout) - defer cancel() - store := NewStore(func(obj interface{}) (string, error) { o, err := meta.Accessor(obj) if err != nil { @@ -2067,6 +2088,7 @@ func BenchmarkReflectorList(b *testing.B) { for _, tc := range tests { b.Run(tc.name, func(b *testing.B) { + _, ctx := ktesting.NewTestContext(b) sample := tc.sample() reflector := NewReflector(newPageTestLW(pageNum), &sample, store, 0) @@ -2074,7 +2096,7 @@ func BenchmarkReflectorList(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - err := reflector.list(ctx.Done()) + err := reflector.list(ctx) if err != nil { b.Fatalf("reflect list: %v", err) } diff --git a/tools/cache/reflector_watchlist_test.go b/tools/cache/reflector_watchlist_test.go index c2fbeca82e..4bf1817d4c 100644 --- a/tools/cache/reflector_watchlist_test.go +++ b/tools/cache/reflector_watchlist_test.go @@ -17,6 +17,7 @@ limitations under the License. package cache import ( + "context" "errors" "fmt" "sort" @@ -35,6 +36,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" + "k8s.io/klog/v2/ktesting" testingclock "k8s.io/utils/clock/testing" "k8s.io/utils/pointer" "k8s.io/utils/ptr" @@ -51,8 +53,9 @@ func TestInitialEventsEndBookmarkTicker(t *testing.T) { } t.Run("testing NoopInitialEventsEndBookmarkTicker", func(t *testing.T) { + logger, _ := ktesting.NewTestContext(t) clock := testingclock.NewFakeClock(time.Now()) - target := newInitialEventsEndBookmarkTickerInternal("testName", clock, clock.Now(), time.Second, false) + target := newInitialEventsEndBookmarkTickerInternal(logger, "testName", clock, clock.Now(), time.Second, false) clock.Step(30 * time.Second) assertNoEvents(t, target.C()) @@ -73,8 +76,9 @@ func TestInitialEventsEndBookmarkTicker(t *testing.T) { }) t.Run("testing InitialEventsEndBookmarkTicker backed by a fake clock", func(t *testing.T) { + logger, _ := ktesting.NewTestContext(t) clock := testingclock.NewFakeClock(time.Now()) - target := newInitialEventsEndBookmarkTickerInternal("testName", clock, clock.Now(), time.Second, true) + target := newInitialEventsEndBookmarkTickerInternal(logger, "testName", clock, clock.Now(), time.Second, true) clock.Step(500 * time.Millisecond) assertNoEvents(t, target.C()) @@ -469,7 +473,8 @@ func TestWatchList(t *testing.T) { for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { scenario := s // capture as local variable - listWatcher, store, reflector, stopCh := testData() + _, ctx := ktesting.NewTestContext(t) + listWatcher, store, reflector, ctx, cancel := testData(ctx) go func() { for i, e := range scenario.watchEvents { listWatcher.fakeWatcher.Action(e.Type, e.Object) @@ -478,7 +483,7 @@ func TestWatchList(t *testing.T) { continue } if i+1 == scenario.closeAfterWatchEvents { - close(stopCh) + cancel(fmt.Errorf("done after %d watch events", i)) } } }() @@ -490,7 +495,7 @@ func TestWatchList(t *testing.T) { reflector.UseWatchList = ptr.To(false) } - err := reflector.ListAndWatch(stopCh) + err := reflector.ListAndWatchWithContext(ctx) if scenario.expectedError != nil && err == nil { t.Fatalf("expected error %q, got nil", scenario.expectedError) } @@ -567,19 +572,19 @@ func makePod(name, rv string) *v1.Pod { return &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name, ResourceVersion: rv, UID: types.UID(name)}} } -func testData() (*fakeListWatcher, Store, *Reflector, chan struct{}) { +func testData(ctx context.Context) (*fakeListWatcher, Store, *Reflector, context.Context, func(error)) { + ctx, cancel := context.WithCancelCause(ctx) s := NewStore(MetaNamespaceKeyFunc) - stopCh := make(chan struct{}) lw := &fakeListWatcher{ fakeWatcher: watch.NewFake(), stop: func() { - close(stopCh) + cancel(errors.New("time to stop")) }, } r := NewReflector(lw, &v1.Pod{}, s, 0) r.UseWatchList = ptr.To(true) - return lw, s, r, stopCh + return lw, s, r, ctx, cancel } type fakeListWatcher struct { diff --git a/tools/cache/shared_informer.go b/tools/cache/shared_informer.go index c805030bd7..9f194ff640 100644 --- a/tools/cache/shared_informer.go +++ b/tools/cache/shared_informer.go @@ -17,6 +17,7 @@ limitations under the License. package cache import ( + "context" "errors" "fmt" "sync" @@ -29,6 +30,7 @@ import ( "k8s.io/client-go/tools/cache/synctrack" "k8s.io/utils/buffer" "k8s.io/utils/clock" + "k8s.io/utils/ptr" "k8s.io/klog/v2" @@ -142,6 +144,8 @@ type SharedInformer interface { // It returns a registration handle for the handler that can be used to // remove the handler again, or to tell if the handler is synced (has // seen every item in the initial list). + // + // Contextual logging: AddEventHandlerWithOptions together with a logger in the options should be used instead of AddEventHandler in code which supports contextual logging. AddEventHandler(handler ResourceEventHandler) (ResourceEventHandlerRegistration, error) // AddEventHandlerWithResyncPeriod adds an event handler to the // shared informer with the requested resync period; zero means @@ -159,7 +163,12 @@ type SharedInformer interface { // be competing load and scheduling noise. // It returns a registration handle for the handler that can be used to remove // the handler again and an error if the handler cannot be added. + // + // Contextual logging: AddEventHandlerWithOptions together with a logger in the options should be used instead of AddEventHandlerWithResyncPeriod in code which supports contextual logging. AddEventHandlerWithResyncPeriod(handler ResourceEventHandler, resyncPeriod time.Duration) (ResourceEventHandlerRegistration, error) + // AddEventHandlerWithOptions is a variant of AddEventHandlerWithResyncPeriod where + // all optional parameters are passed in a struct. + AddEventHandlerWithOptions(handler ResourceEventHandler, options HandlerOptions) (ResourceEventHandlerRegistration, error) // RemoveEventHandler removes a formerly added event handler given by // its registration handle. // This function is guaranteed to be idempotent, and thread-safe. @@ -170,7 +179,12 @@ type SharedInformer interface { GetController() Controller // Run starts and runs the shared informer, returning after it stops. // The informer will be stopped when stopCh is closed. + // + // Contextual logging: RunWithContext should be used instead of Run in code which uses contextual logging. Run(stopCh <-chan struct{}) + // RunWithContext starts and runs the shared informer, returning after it stops. + // The informer will be stopped when the context is canceled. + RunWithContext(ctx context.Context) // HasSynced returns true if the shared informer's store has been // informed by at least one full LIST of the authoritative state // of the informer's object collection. This is unrelated to "resync". @@ -197,8 +211,14 @@ type SharedInformer interface { // The handler is intended for visibility, not to e.g. pause the consumers. // The handler should return quickly - any expensive processing should be // offloaded. + // + // Contextual logging: SetWatchErrorHandlerWithContext should be used instead of SetWatchErrorHandler in code which supports contextual logging. SetWatchErrorHandler(handler WatchErrorHandler) error + // SetWatchErrorHandlerWithContext is a variant of SetWatchErrorHandler where + // the handler is passed an additional context parameter. + SetWatchErrorHandlerWithContext(handler WatchErrorHandlerWithContext) error + // The TransformFunc is called for each object which is about to be stored. // // This function is intended for you to take the opportunity to @@ -228,6 +248,21 @@ type ResourceEventHandlerRegistration interface { HasSynced() bool } +// Optional configuration options for [SharedInformer.AddEventHandlerWithOptions]. +// May be left empty. +type HandlerOptions struct { + // Logger overrides the default klog.Background() logger. + Logger *klog.Logger + + // ResyncPeriod requests a certain resync period from an informer. Zero + // means the handler does not care about resyncs. Not all informers do + // resyncs, even if requested. See + // [SharedInformer.AddEventHandlerWithResyncPeriod] for details. + // + // If nil, the default resync period of the shared informer is used. + ResyncPeriod *time.Duration +} + // SharedIndexInformer provides add and get Indexers ability based on SharedInformer. type SharedIndexInformer interface { SharedInformer @@ -309,15 +344,38 @@ const ( // WaitForNamedCacheSync is a wrapper around WaitForCacheSync that generates log messages // indicating that the caller identified by name is waiting for syncs, followed by // either a successful or failed sync. +// +// Contextual logging: WaitForNamedCacheSyncWithContext should be used instead of WaitForNamedCacheSync in code which supports contextual logging. func WaitForNamedCacheSync(controllerName string, stopCh <-chan struct{}, cacheSyncs ...InformerSynced) bool { - klog.Infof("Waiting for caches to sync for %s", controllerName) + klog.Background().Info("Waiting for caches to sync", "controller", controllerName) if !WaitForCacheSync(stopCh, cacheSyncs...) { - utilruntime.HandleError(fmt.Errorf("unable to sync caches for %s", controllerName)) + utilruntime.HandleErrorWithContext(context.Background(), nil, "Unable to sync caches", "controller", controllerName) + return false + } + + klog.Background().Info("Caches are synced", "controller", controllerName) + return true +} + +// WaitForNamedCacheSyncWithContext is a wrapper around WaitForCacheSyncWithContext that generates log messages +// indicating that the caller is waiting for syncs, followed by either a successful or failed sync. +// +// Contextual logging can be used to identify the caller in those log messages. The log level is zero, +// the same as in [WaitForNamedCacheSync]. If this is too verbose, then store a logger with an increased +// threshold in the context: +// +// WaitForNamedCacheSyncWithContext(klog.NewContext(ctx, logger.V(5)), ...) +func WaitForNamedCacheSyncWithContext(ctx context.Context, cacheSyncs ...InformerSynced) bool { + logger := klog.FromContext(ctx) + logger.Info("Waiting for caches to sync") + + if !WaitForCacheSync(ctx.Done(), cacheSyncs...) { + utilruntime.HandleErrorWithContext(ctx, nil, "Unable to sync caches") return false } - klog.Infof("Caches are synced for %s", controllerName) + logger.Info("Caches are synced") return true } @@ -389,7 +447,7 @@ type sharedIndexInformer struct { blockDeltas sync.Mutex // Called whenever the ListAndWatch drops the connection with an error. - watchErrorHandler WatchErrorHandler + watchErrorHandler WatchErrorHandlerWithContext transform TransformFunc } @@ -403,6 +461,9 @@ type dummyController struct { informer *sharedIndexInformer } +func (v *dummyController) RunWithContext(context.Context) { +} + func (v *dummyController) Run(stopCh <-chan struct{}) { } @@ -433,6 +494,12 @@ type deleteNotification struct { } func (s *sharedIndexInformer) SetWatchErrorHandler(handler WatchErrorHandler) error { + return s.SetWatchErrorHandlerWithContext(func(_ context.Context, r *Reflector, err error) { + handler(r, err) + }) +} + +func (s *sharedIndexInformer) SetWatchErrorHandlerWithContext(handler WatchErrorHandlerWithContext) error { s.startedLock.Lock() defer s.startedLock.Unlock() @@ -457,10 +524,15 @@ func (s *sharedIndexInformer) SetTransform(handler TransformFunc) error { } func (s *sharedIndexInformer) Run(stopCh <-chan struct{}) { - defer utilruntime.HandleCrash() + s.RunWithContext(wait.ContextForChannel(stopCh)) +} + +func (s *sharedIndexInformer) RunWithContext(ctx context.Context) { + defer utilruntime.HandleCrashWithContext(ctx) + logger := klog.FromContext(ctx) if s.HasStarted() { - klog.Warningf("The sharedIndexInformer has started, run more than once is not allowed") + logger.Info("Warning: the sharedIndexInformer has started, run more than once is not allowed") return } @@ -468,11 +540,16 @@ func (s *sharedIndexInformer) Run(stopCh <-chan struct{}) { s.startedLock.Lock() defer s.startedLock.Unlock() - fifo := NewDeltaFIFOWithOptions(DeltaFIFOOptions{ - KnownObjects: s.indexer, - EmitDeltaTypeReplaced: true, - Transformer: s.transform, - }) + var fifo Queue + if clientgofeaturegate.FeatureGates().Enabled(clientgofeaturegate.InOrderInformers) { + fifo = NewRealFIFO(MetaNamespaceKeyFunc, s.indexer, s.transform) + } else { + fifo = NewDeltaFIFOWithOptions(DeltaFIFOOptions{ + KnownObjects: s.indexer, + EmitDeltaTypeReplaced: true, + Transformer: s.transform, + }) + } cfg := &Config{ Queue: fifo, @@ -480,11 +557,10 @@ func (s *sharedIndexInformer) Run(stopCh <-chan struct{}) { ObjectType: s.objectType, ObjectDescription: s.objectDescription, FullResyncPeriod: s.resyncCheckPeriod, - RetryOnError: false, ShouldResync: s.processor.shouldResync, - Process: s.HandleDeltas, - WatchErrorHandler: s.watchErrorHandler, + Process: s.HandleDeltas, + WatchErrorHandlerWithContext: s.watchErrorHandler, } s.controller = New(cfg) @@ -492,20 +568,24 @@ func (s *sharedIndexInformer) Run(stopCh <-chan struct{}) { s.started = true }() - // Separate stop channel because Processor should be stopped strictly after controller - processorStopCh := make(chan struct{}) + // Separate stop context because Processor should be stopped strictly after controller. + // Cancelation in the parent context is ignored and all values are passed on, + // including - but not limited to - a logger. + processorStopCtx, stopProcessor := context.WithCancelCause(context.WithoutCancel(ctx)) var wg wait.Group - defer wg.Wait() // Wait for Processor to stop - defer close(processorStopCh) // Tell Processor to stop - wg.StartWithChannel(processorStopCh, s.cacheMutationDetector.Run) - wg.StartWithChannel(processorStopCh, s.processor.run) + defer wg.Wait() // Wait for Processor to stop + defer stopProcessor(errors.New("informer is stopping")) // Tell Processor to stop + // TODO: extend the MutationDetector interface so that it optionally + // has a RunWithContext method that we can use here. + wg.StartWithChannel(processorStopCtx.Done(), s.cacheMutationDetector.Run) + wg.StartWithContext(processorStopCtx, s.processor.run) defer func() { s.startedLock.Lock() defer s.startedLock.Unlock() s.stopped = true // Don't want any new listeners }() - s.controller.Run(stopCh) + s.controller.RunWithContext(ctx) } func (s *sharedIndexInformer) HasStarted() bool { @@ -558,19 +638,19 @@ func (s *sharedIndexInformer) GetController() Controller { } func (s *sharedIndexInformer) AddEventHandler(handler ResourceEventHandler) (ResourceEventHandlerRegistration, error) { - return s.AddEventHandlerWithResyncPeriod(handler, s.defaultEventHandlerResyncPeriod) + return s.AddEventHandlerWithOptions(handler, HandlerOptions{}) } -func determineResyncPeriod(desired, check time.Duration) time.Duration { +func determineResyncPeriod(logger klog.Logger, desired, check time.Duration) time.Duration { if desired == 0 { return desired } if check == 0 { - klog.Warningf("The specified resyncPeriod %v is invalid because this shared informer doesn't support resyncing", desired) + logger.Info("Warning: the specified resyncPeriod is invalid because this shared informer doesn't support resyncing", "desired", desired) return 0 } if desired < check { - klog.Warningf("The specified resyncPeriod %v is being increased to the minimum resyncCheckPeriod %v", desired, check) + logger.Info("Warning: the specified resyncPeriod is being increased to the minimum resyncCheckPeriod", "desired", desired, "resyncCheckPeriod", check) return check } return desired @@ -579,6 +659,10 @@ func determineResyncPeriod(desired, check time.Duration) time.Duration { const minimumResyncPeriod = 1 * time.Second func (s *sharedIndexInformer) AddEventHandlerWithResyncPeriod(handler ResourceEventHandler, resyncPeriod time.Duration) (ResourceEventHandlerRegistration, error) { + return s.AddEventHandlerWithOptions(handler, HandlerOptions{ResyncPeriod: &resyncPeriod}) +} + +func (s *sharedIndexInformer) AddEventHandlerWithOptions(handler ResourceEventHandler, options HandlerOptions) (ResourceEventHandlerRegistration, error) { s.startedLock.Lock() defer s.startedLock.Unlock() @@ -586,27 +670,30 @@ func (s *sharedIndexInformer) AddEventHandlerWithResyncPeriod(handler ResourceEv return nil, fmt.Errorf("handler %v was not added to shared informer because it has stopped already", handler) } + logger := ptr.Deref(options.Logger, klog.Background()) + resyncPeriod := ptr.Deref(options.ResyncPeriod, s.defaultEventHandlerResyncPeriod) if resyncPeriod > 0 { if resyncPeriod < minimumResyncPeriod { - klog.Warningf("resyncPeriod %v is too small. Changing it to the minimum allowed value of %v", resyncPeriod, minimumResyncPeriod) + logger.Info("Warning: resync period is too small. Changing it to the minimum allowed value", "resyncPeriod", resyncPeriod, "minimumResyncPeriod", minimumResyncPeriod) resyncPeriod = minimumResyncPeriod } if resyncPeriod < s.resyncCheckPeriod { if s.started { - klog.Warningf("resyncPeriod %v is smaller than resyncCheckPeriod %v and the informer has already started. Changing it to %v", resyncPeriod, s.resyncCheckPeriod, s.resyncCheckPeriod) + logger.Info("Warning: resync period is smaller than resync check period and the informer has already started. Changing it to the resync check period", "resyncPeriod", resyncPeriod, "resyncCheckPeriod", s.resyncCheckPeriod) + resyncPeriod = s.resyncCheckPeriod } else { // if the event handler's resyncPeriod is smaller than the current resyncCheckPeriod, update // resyncCheckPeriod to match resyncPeriod and adjust the resync periods of all the listeners // accordingly s.resyncCheckPeriod = resyncPeriod - s.processor.resyncCheckPeriodChanged(resyncPeriod) + s.processor.resyncCheckPeriodChanged(logger, resyncPeriod) } } } - listener := newProcessListener(handler, resyncPeriod, determineResyncPeriod(resyncPeriod, s.resyncCheckPeriod), s.clock.Now(), initialBufferSize, s.HasSynced) + listener := newProcessListener(logger, handler, resyncPeriod, determineResyncPeriod(logger, resyncPeriod, s.resyncCheckPeriod), s.clock.Now(), initialBufferSize, s.HasSynced) if !s.started { return s.processor.addListener(listener), nil @@ -648,7 +735,7 @@ func (s *sharedIndexInformer) HandleDeltas(obj interface{}, isInInitialList bool // Conforms to ResourceEventHandler func (s *sharedIndexInformer) OnAdd(obj interface{}, isInInitialList bool) { // Invocation of this function is locked under s.blockDeltas, so it is - // save to distribute the notification + // safe to distribute the notification s.cacheMutationDetector.AddObject(obj) s.processor.distribute(addNotification{newObj: obj, isInInitialList: isInInitialList}, false) } @@ -670,7 +757,7 @@ func (s *sharedIndexInformer) OnUpdate(old, new interface{}) { } // Invocation of this function is locked under s.blockDeltas, so it is - // save to distribute the notification + // safe to distribute the notification s.cacheMutationDetector.AddObject(new) s.processor.distribute(updateNotification{oldObj: old, newObj: new}, isSync) } @@ -678,7 +765,7 @@ func (s *sharedIndexInformer) OnUpdate(old, new interface{}) { // Conforms to ResourceEventHandler func (s *sharedIndexInformer) OnDelete(old interface{}) { // Invocation of this function is locked under s.blockDeltas, so it is - // save to distribute the notification + // safe to distribute the notification s.processor.distribute(deleteNotification{oldObj: old}, false) } @@ -794,7 +881,7 @@ func (p *sharedProcessor) distribute(obj interface{}, sync bool) { } } -func (p *sharedProcessor) run(stopCh <-chan struct{}) { +func (p *sharedProcessor) run(ctx context.Context) { func() { p.listenersLock.RLock() defer p.listenersLock.RUnlock() @@ -804,7 +891,7 @@ func (p *sharedProcessor) run(stopCh <-chan struct{}) { } p.listenersStarted = true }() - <-stopCh + <-ctx.Done() p.listenersLock.Lock() defer p.listenersLock.Unlock() @@ -844,13 +931,13 @@ func (p *sharedProcessor) shouldResync() bool { return resyncNeeded } -func (p *sharedProcessor) resyncCheckPeriodChanged(resyncCheckPeriod time.Duration) { +func (p *sharedProcessor) resyncCheckPeriodChanged(logger klog.Logger, resyncCheckPeriod time.Duration) { p.listenersLock.RLock() defer p.listenersLock.RUnlock() for listener := range p.listeners { resyncPeriod := determineResyncPeriod( - listener.requestedResyncPeriod, resyncCheckPeriod) + logger, listener.requestedResyncPeriod, resyncCheckPeriod) listener.setResyncPeriod(resyncPeriod) } } @@ -867,6 +954,7 @@ func (p *sharedProcessor) resyncCheckPeriodChanged(resyncCheckPeriod time.Durati // processorListener also keeps track of the adjusted requested resync // period of the listener. type processorListener struct { + logger klog.Logger nextCh chan interface{} addCh chan interface{} @@ -910,8 +998,9 @@ func (p *processorListener) HasSynced() bool { return p.syncTracker.HasSynced() } -func newProcessListener(handler ResourceEventHandler, requestedResyncPeriod, resyncPeriod time.Duration, now time.Time, bufferSize int, hasSynced func() bool) *processorListener { +func newProcessListener(logger klog.Logger, handler ResourceEventHandler, requestedResyncPeriod, resyncPeriod time.Duration, now time.Time, bufferSize int, hasSynced func() bool) *processorListener { ret := &processorListener{ + logger: logger, nextCh: make(chan interface{}), addCh: make(chan interface{}), handler: handler, @@ -934,7 +1023,7 @@ func (p *processorListener) add(notification interface{}) { } func (p *processorListener) pop() { - defer utilruntime.HandleCrash() + defer utilruntime.HandleCrashWithLogger(p.logger) defer close(p.nextCh) // Tell .run() to stop var nextCh chan<- interface{} @@ -966,11 +1055,21 @@ func (p *processorListener) pop() { func (p *processorListener) run() { // this call blocks until the channel is closed. When a panic happens during the notification // we will catch it, **the offending item will be skipped!**, and after a short delay (one second) - // the next notification will be attempted. This is usually better than the alternative of never + // the next notification will be attempted. This is usually better than the alternative of never // delivering again. - stopCh := make(chan struct{}) - wait.Until(func() { - for next := range p.nextCh { + // + // This only applies if utilruntime is configured to not panic, which is not the default. + sleepAfterCrash := false + for next := range p.nextCh { + if sleepAfterCrash { + // Sleep before processing the next item. + time.Sleep(time.Second) + } + func() { + // Gets reset below, but only if we get that far. + sleepAfterCrash = true + defer utilruntime.HandleCrashWithLogger(p.logger) + switch notification := next.(type) { case updateNotification: p.handler.OnUpdate(notification.oldObj, notification.newObj) @@ -982,15 +1081,14 @@ func (p *processorListener) run() { case deleteNotification: p.handler.OnDelete(notification.oldObj) default: - utilruntime.HandleError(fmt.Errorf("unrecognized notification: %T", next)) + utilruntime.HandleErrorWithLogger(p.logger, nil, "unrecognized notification", "notificationType", fmt.Sprintf("%T", next)) } - } - // the only way to get here is if the p.nextCh is empty and closed - close(stopCh) - }, 1*time.Second, stopCh) + sleepAfterCrash = false + }() + } } -// shouldResync deterimines if the listener needs a resync. If the listener's resyncPeriod is 0, +// shouldResync determines if the listener needs a resync. If the listener's resyncPeriod is 0, // this always returns false. func (p *processorListener) shouldResync(now time.Time) bool { p.resyncLock.Lock() diff --git a/tools/cache/shared_informer_test.go b/tools/cache/shared_informer_test.go index 1e4ed9d560..39f4eabce4 100644 --- a/tools/cache/shared_informer_test.go +++ b/tools/cache/shared_informer_test.go @@ -20,6 +20,7 @@ import ( "context" "fmt" "math/rand" + "runtime" "strconv" "strings" "sync" @@ -29,12 +30,18 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" fcache "k8s.io/client-go/tools/cache/testing" + "k8s.io/klog/v2" + "k8s.io/klog/v2/ktesting" + "k8s.io/klog/v2/textlogger" testingclock "k8s.io/utils/clock/testing" ) @@ -123,7 +130,7 @@ func isRegistered(i SharedInformer, h ResourceEventHandlerRegistration) bool { func TestIndexer(t *testing.T) { assert := assert.New(t) // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) pod1 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", Labels: map[string]string{"a": "a-val", "b": "b-val1"}}} pod2 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod2", Labels: map[string]string{"b": "b-val2"}}} pod3 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod3", Labels: map[string]string{"a": "a-val2"}}} @@ -144,10 +151,15 @@ func TestIndexer(t *testing.T) { if err != nil { t.Fatal(err) } + + var wg wait.Group stop := make(chan struct{}) - defer close(stop) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() - go informer.Run(stop) WaitForCacheSync(stop, informer.HasSynced) cmpOps := cmpopts.SortSlices(func(a, b any) bool { @@ -197,7 +209,7 @@ func TestIndexer(t *testing.T) { func TestListenerResyncPeriods(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod2"}}) @@ -221,10 +233,13 @@ func TestListenerResyncPeriods(t *testing.T) { informer.AddEventHandlerWithResyncPeriod(listener3, listener3.resyncPeriod) listeners := []*testListener{listener1, listener2, listener3} + var wg wait.Group stop := make(chan struct{}) - defer close(stop) - - go informer.Run(stop) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() // ensure all listeners got the initial List for _, listener := range listeners { @@ -284,7 +299,7 @@ func TestListenerResyncPeriods(t *testing.T) { func TestResyncCheckPeriod(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) // create the shared informer and resync every 12 hours informer := NewSharedInformer(source, &v1.Pod{}, 12*time.Hour).(*sharedIndexInformer) @@ -356,14 +371,18 @@ func TestResyncCheckPeriod(t *testing.T) { // verify that https://github.com/kubernetes/kubernetes/issues/59822 is fixed func TestSharedInformerInitializationRace(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) listener := newTestListener("raceListener", 0) - stop := make(chan struct{}) go informer.AddEventHandlerWithResyncPeriod(listener, listener.resyncPeriod) - go informer.Run(stop) - close(stop) + var wg wait.Group + stop := make(chan struct{}) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() } // TestSharedInformerWatchDisruption simulates a watch that was closed @@ -371,7 +390,7 @@ func TestSharedInformerInitializationRace(t *testing.T) { // resync and no resync see the expected state. func TestSharedInformerWatchDisruption(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: "pod1", ResourceVersion: "1"}}) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod2", UID: "pod2", ResourceVersion: "2"}}) @@ -391,10 +410,13 @@ func TestSharedInformerWatchDisruption(t *testing.T) { informer.AddEventHandlerWithResyncPeriod(listenerResync, listenerResync.resyncPeriod) listeners := []*testListener{listenerNoResync, listenerResync} + var wg wait.Group stop := make(chan struct{}) - defer close(stop) - - go informer.Run(stop) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() for _, listener := range listeners { if !listener.ok() { @@ -446,7 +468,7 @@ func TestSharedInformerWatchDisruption(t *testing.T) { } func TestSharedInformerErrorHandling(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) source.ListError = fmt.Errorf("Access Denied") @@ -457,8 +479,13 @@ func TestSharedInformerErrorHandling(t *testing.T) { errCh <- err }) + var wg wait.Group stop := make(chan struct{}) - go informer.Run(stop) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() select { case err := <-errCh: @@ -468,13 +495,12 @@ func TestSharedInformerErrorHandling(t *testing.T) { case <-time.After(time.Second): t.Errorf("Timeout waiting for error handler call") } - close(stop) } // TestSharedInformerStartRace is a regression test to ensure there is no race between // Run and SetWatchErrorHandler, and Run and SetTransform. func TestSharedInformerStartRace(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) stop := make(chan struct{}) go func() { @@ -493,14 +519,17 @@ func TestSharedInformerStartRace(t *testing.T) { } }() - go informer.Run(stop) - - close(stop) + var wg wait.Group + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() } func TestSharedInformerTransformer(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: "pod1", ResourceVersion: "1"}}) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod2", UID: "pod2", ResourceVersion: "2"}}) @@ -521,9 +550,13 @@ func TestSharedInformerTransformer(t *testing.T) { listenerTransformer := newTestListener("listenerTransformer", 0, "POD1", "POD2") informer.AddEventHandler(listenerTransformer) + var wg wait.Group stop := make(chan struct{}) - go informer.Run(stop) - defer close(stop) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() if !listenerTransformer.ok() { t.Errorf("%s: expected %v, got %v", listenerTransformer.name, listenerTransformer.expectedItemNames, listenerTransformer.receivedItemNames) @@ -531,7 +564,7 @@ func TestSharedInformerTransformer(t *testing.T) { } func TestSharedInformerRemoveHandler(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second) @@ -569,12 +602,12 @@ func TestSharedInformerRemoveHandler(t *testing.T) { } func TestSharedInformerRemoveForeignHandler(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) - source2 := fcache.NewFakeControllerSource() + source2 := newFakeControllerSource(t) source2.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer2 := NewSharedInformer(source2, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) @@ -651,7 +684,7 @@ func TestSharedInformerRemoveForeignHandler(t *testing.T) { } func TestSharedInformerMultipleRegistration(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) @@ -719,7 +752,7 @@ func TestSharedInformerMultipleRegistration(t *testing.T) { } func TestRemovingRemovedSharedInformer(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) @@ -751,14 +784,16 @@ func TestRemovingRemovedSharedInformer(t *testing.T) { // listeners without tripping it up. There are not really many assertions in this // test. Meant to be run with -race to find race conditions func TestSharedInformerHandlerAbuse(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) ctx, cancel := context.WithCancel(context.Background()) informerCtx, informerCancel := context.WithCancel(context.Background()) - go func() { - informer.Run(informerCtx.Done()) + var informerWg wait.Group + informerWg.StartWithChannel(informerCtx.Done(), informer.Run) + defer func() { cancel() + informerWg.Wait() }() worker := func() { @@ -865,7 +900,7 @@ func TestSharedInformerHandlerAbuse(t *testing.T) { } func TestStateSharedInformer(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) @@ -880,8 +915,10 @@ func TestStateSharedInformer(t *testing.T) { t.Errorf("informer already stopped after creation") return } + var wg wait.Group stop := make(chan struct{}) - go informer.Run(stop) + wg.StartWithChannel(stop, informer.Run) + defer wg.Wait() if !listener.ok() { t.Errorf("informer did not report initial objects") close(stop) @@ -914,13 +951,15 @@ func TestStateSharedInformer(t *testing.T) { } func TestAddOnStoppedSharedInformer(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) listener := newTestListener("listener", 0, "pod1") stop := make(chan struct{}) - go informer.Run(stop) + var wg wait.Group + wg.StartWithChannel(stop, informer.Run) + defer wg.Wait() close(stop) err := wait.PollImmediate(100*time.Millisecond, 2*time.Second, func() (bool, error) { @@ -947,7 +986,7 @@ func TestAddOnStoppedSharedInformer(t *testing.T) { } func TestRemoveOnStoppedSharedInformer(t *testing.T) { - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) @@ -958,7 +997,9 @@ func TestRemoveOnStoppedSharedInformer(t *testing.T) { return } stop := make(chan struct{}) - go informer.Run(stop) + var wg wait.Group + wg.StartWithChannel(stop, informer.Run) + defer wg.Wait() close(stop) fmt.Println("sleeping") time.Sleep(1 * time.Second) @@ -976,7 +1017,7 @@ func TestRemoveOnStoppedSharedInformer(t *testing.T) { func TestRemoveWhileActive(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) // create the shared informer and resync every 12 hours informer := NewSharedInformer(source, &v1.Pod{}, 0).(*sharedIndexInformer) @@ -985,9 +1026,13 @@ func TestRemoveWhileActive(t *testing.T) { handle, _ := informer.AddEventHandler(listener) stop := make(chan struct{}) - defer close(stop) + var wg wait.Group + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() - go informer.Run(stop) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) if !listener.ok() { @@ -1012,7 +1057,7 @@ func TestRemoveWhileActive(t *testing.T) { func TestAddWhileActive(t *testing.T) { // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() + source := newFakeControllerSource(t) // create the shared informer and resync every 12 hours informer := NewSharedInformer(source, &v1.Pod{}, 0).(*sharedIndexInformer) @@ -1025,9 +1070,13 @@ func TestAddWhileActive(t *testing.T) { } stop := make(chan struct{}) - defer close(stop) + var wg wait.Group + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() - go informer.Run(stop) source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) if !listener1.ok() { @@ -1072,3 +1121,212 @@ func TestAddWhileActive(t *testing.T) { return } } + +// TestShutdown depends on goleak.VerifyTestMain in main_test.go to verify that +// all goroutines really have stopped in the different scenarios. +func TestShutdown(t *testing.T) { + t.Run("no-context", func(t *testing.T) { + source := newFakeControllerSource(t) + + informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second) + handler, err := informer.AddEventHandler(ResourceEventHandlerFuncs{ + AddFunc: func(_ any) {}, + }) + require.NoError(t, err) + defer func() { + assert.NoError(t, informer.RemoveEventHandler(handler)) + }() + + var wg wait.Group + stop := make(chan struct{}) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() + + require.Eventually(t, informer.HasSynced, time.Minute, time.Millisecond, "informer has synced") + }) + + t.Run("no-context-later", func(t *testing.T) { + source := newFakeControllerSource(t) + informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second) + + var wg wait.Group + stop := make(chan struct{}) + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + wg.Wait() + }() + + require.Eventually(t, informer.HasSynced, time.Minute, time.Millisecond, "informer has synced") + + handler, err := informer.AddEventHandler(ResourceEventHandlerFuncs{ + AddFunc: func(_ any) {}, + }) + require.NoError(t, err) + assert.NoError(t, informer.RemoveEventHandler(handler)) + }) + + t.Run("no-run", func(t *testing.T) { + source := newFakeControllerSource(t) + informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second) + _, err := informer.AddEventHandler(ResourceEventHandlerFuncs{ + AddFunc: func(_ any) {}, + }) + require.NoError(t, err) + + // At this point, neither informer nor handler have any goroutines running + // and it doesn't matter that nothing gets stopped or removed. + }) +} + +func TestEventPanics(t *testing.T) { + // timeInUTC := time.Date(2009, 12, 1, 13, 30, 40, 42000, time.UTC) + // timeString := "1201 13:30:40.000042" + // Initialized by init. + var ( + buffer threadSafeBuffer + logger klog.Logger + source *fcache.FakeControllerSource + ) + + init := func(t *testing.T) { + // Restoring state is very sensitive to ordering. All goroutines spawned + // by a test must have completed and there has to be a check that they + // have completed that is visible to the race detector. This also + // applies to all other tests! + t.Cleanup(klog.CaptureState().Restore) //nolint:logcheck // CaptureState shouldn't be used in packages with contextual logging, but here it is okay. + buffer.buffer.Reset() + logger = textlogger.NewLogger(textlogger.NewConfig( + // textlogger.FixedTime(timeInUTC), + textlogger.Output(&buffer), + )) + oldReallyCrash := utilruntime.ReallyCrash + utilruntime.ReallyCrash = false + t.Cleanup(func() { utilruntime.ReallyCrash = oldReallyCrash }) + + source = newFakeControllerSource(t) + source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) + } + + newHandler := func(ctx context.Context) ResourceEventHandlerFuncs { + logger := klog.FromContext(ctx) + return ResourceEventHandlerFuncs{ + AddFunc: func(obj any) { + logger.Info("Add func will panic now", "pod", klog.KObj(obj.(*v1.Pod))) + panic("fake panic") + }, + } + } + _, _, panicLine, _ := runtime.Caller(0) + panicLine -= 4 + expectedLog := func(name string) string { + if name == "" { + return fmt.Sprintf(`shared_informer_test.go:%d] "Observed a panic" panic="fake panic"`, panicLine) + } + return fmt.Sprintf(`shared_informer_test.go:%d] "Observed a panic" logger=%q panic="fake panic"`, panicLine, name) + } + handler := newHandler(context.Background()) + + t.Run("simple", func(t *testing.T) { + init(t) + klog.SetLogger(logger) + stop := make(chan struct{}) + informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second) + handle, err := informer.AddEventHandler(handler) + require.NoError(t, err) + defer func() { + assert.NoError(t, informer.RemoveEventHandler(handle)) + }() + var wg wait.Group + wg.StartWithChannel(stop, informer.Run) + defer func() { + close(stop) + assert.Eventually(t, informer.IsStopped, time.Minute, time.Millisecond, "informer has stopped") + wg.Wait() // For race detector... + }() + require.Eventually(t, informer.HasSynced, time.Minute, time.Millisecond, "informer has synced") + + // This times out (https://github.com/kubernetes/kubernetes/issues/129024) because the + // handler never syncs when the callback panics: + // require.Eventually(t, handle.HasSynced, time.Minute, time.Millisecond, "handler has synced") + // + // Wait for a non-empty buffer instead. This implies that we have to make + // the buffer thread-safe, which wouldn't be necessary otherwise. + assert.EventuallyWithT(t, func(t *assert.CollectT) { + assert.Contains(t, buffer.String(), expectedLog("")) + }, time.Minute, time.Millisecond, "handler has panicked") + }) + + t.Run("many", func(t *testing.T) { + init(t) + // One pod was already created in init, add some more. + numPods := 5 + for i := 1; i < numPods; i++ { + source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("pod%d", i+1)}}) + } + _, ctx := ktesting.NewTestContext(t) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second) + name1 := "fake-event-handler-1" + logger1 := klog.LoggerWithName(logger, name1) + ctx1 := klog.NewContext(ctx, logger1) + handle1, err := informer.AddEventHandlerWithOptions(newHandler(ctx1), HandlerOptions{Logger: &logger1}) + require.NoError(t, err) + defer func() { + assert.NoError(t, informer.RemoveEventHandler(handle1)) + }() + name2 := "fake-event-handler-2" + logger2 := klog.LoggerWithName(logger, name2) + ctx2 := klog.NewContext(ctx, logger2) + handle2, err := informer.AddEventHandlerWithOptions(newHandler(ctx2), HandlerOptions{Logger: &logger2}) + require.NoError(t, err) + defer func() { + assert.NoError(t, informer.RemoveEventHandler(handle2)) + }() + + start := time.Now() + var wg wait.Group + informerName := "informer" + informerLogger := klog.LoggerWithName(logger, informerName) + informerCtx := klog.NewContext(ctx, informerLogger) + wg.StartWithContext(informerCtx, informer.RunWithContext) + defer func() { + cancel() + assert.Eventually(t, informer.IsStopped, time.Minute, time.Millisecond, "informer has stopped") + wg.Wait() // For race detector... + }() + require.Eventually(t, informer.HasSynced, time.Minute, time.Millisecond, "informer has synced") + + assert.EventuallyWithT(t, func(t *assert.CollectT) { + output := buffer.String() + expected := expectedLog(name1) + if !assert.Equal(t, numPods, numOccurrences(output, expected), "Log output should have the right number of panics for %q (search string: %q), got instead:\n%s", name1, expected, output) { + return + } + expected = expectedLog(name2) + assert.Equal(t, numPods, numOccurrences(output, expected), "Log output should have the right number of panics for %q (search string %q, got instead:\n%s", name2, expected, output) + }, 30*time.Second, time.Millisecond, "handler has panicked") + + // Both handlers should have slept for one second after each panic, + // except after the last pod event because then the input channel + // gets closed. + assert.GreaterOrEqual(t, time.Since(start), time.Duration(numPods-1)*time.Second, "Delay in processorListener.run") + }) +} + +func numOccurrences(hay, needle string) int { + count := 0 + for { + index := strings.Index(hay, needle) + if index < 0 { + return count + } + count++ + hay = hay[index+len(needle):] + } +} diff --git a/tools/cache/the_real_fifo.go b/tools/cache/the_real_fifo.go new file mode 100644 index 0000000000..9be14ff381 --- /dev/null +++ b/tools/cache/the_real_fifo.go @@ -0,0 +1,407 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cache + +import ( + "fmt" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/sets" + utiltrace "k8s.io/utils/trace" + "sync" + "time" +) + +// RealFIFO is a Queue in which every notification from the Reflector is passed +// in order to the Queue via Pop. +// This means that it +// 1. delivers notifications for items that have been deleted +// 2. delivers multiple notifications per item instead of simply the most recent value +type RealFIFO struct { + lock sync.RWMutex + cond sync.Cond + + items []Delta + + // populated is true if the first batch of items inserted by Replace() has been populated + // or Delete/Add/Update was called first. + populated bool + // initialPopulationCount is the number of items inserted by the first call of Replace() + initialPopulationCount int + + // keyFunc is used to make the key used for queued item insertion and retrieval, and + // should be deterministic. + keyFunc KeyFunc + + // knownObjects list keys that are "known" --- affecting Delete(), + // Replace(), and Resync() + knownObjects KeyListerGetter + + // Indication the queue is closed. + // Used to indicate a queue is closed so a control loop can exit when a queue is empty. + // Currently, not used to gate any of CRUD operations. + closed bool + + // Called with every object if non-nil. + transformer TransformFunc +} + +var ( + _ = Queue(&RealFIFO{}) // RealFIFO is a Queue +) + +// Close the queue. +func (f *RealFIFO) Close() { + f.lock.Lock() + defer f.lock.Unlock() + f.closed = true + f.cond.Broadcast() +} + +// KeyOf exposes f's keyFunc, but also detects the key of a Deltas object or +// DeletedFinalStateUnknown objects. +func (f *RealFIFO) keyOf(obj interface{}) (string, error) { + if d, ok := obj.(Deltas); ok { + if len(d) == 0 { + return "", KeyError{obj, ErrZeroLengthDeltasObject} + } + obj = d.Newest().Object + } + if d, ok := obj.(Delta); ok { + obj = d.Object + } + if d, ok := obj.(DeletedFinalStateUnknown); ok { + return d.Key, nil + } + return f.keyFunc(obj) +} + +// HasSynced returns true if an Add/Update/Delete are called first, +// or the first batch of items inserted by Replace() has been popped. +func (f *RealFIFO) HasSynced() bool { + f.lock.Lock() + defer f.lock.Unlock() + return f.hasSynced_locked() +} + +// ignoring lint to reduce delta to the original for review. It's ok adjust later. +// +//lint:file-ignore ST1003: should not use underscores in Go names +func (f *RealFIFO) hasSynced_locked() bool { + return f.populated && f.initialPopulationCount == 0 +} + +// addToItems_locked appends to the delta list. +func (f *RealFIFO) addToItems_locked(deltaActionType DeltaType, skipTransform bool, obj interface{}) error { + // we must be able to read the keys in order to determine whether the knownObjcts and the items + // in this FIFO overlap + _, err := f.keyOf(obj) + if err != nil { + return KeyError{obj, err} + } + + // Every object comes through this code path once, so this is a good + // place to call the transform func. + // + // If obj is a DeletedFinalStateUnknown tombstone or the action is a Sync, + // then the object have already gone through the transformer. + // + // If the objects already present in the cache are passed to Replace(), + // the transformer must be idempotent to avoid re-mutating them, + // or coordinate with all readers from the cache to avoid data races. + // Default informers do not pass existing objects to Replace. + if f.transformer != nil { + _, isTombstone := obj.(DeletedFinalStateUnknown) + if !isTombstone && !skipTransform { + var err error + obj, err = f.transformer(obj) + if err != nil { + return err + } + } + } + + f.items = append(f.items, Delta{ + Type: deltaActionType, + Object: obj, + }) + f.cond.Broadcast() + + return nil +} + +// Add inserts an item, and puts it in the queue. The item is only enqueued +// if it doesn't already exist in the set. +func (f *RealFIFO) Add(obj interface{}) error { + f.lock.Lock() + defer f.lock.Unlock() + + f.populated = true + retErr := f.addToItems_locked(Added, false, obj) + + return retErr +} + +// Update is the same as Add in this implementation. +func (f *RealFIFO) Update(obj interface{}) error { + f.lock.Lock() + defer f.lock.Unlock() + + f.populated = true + retErr := f.addToItems_locked(Updated, false, obj) + + return retErr +} + +// Delete removes an item. It doesn't add it to the queue, because +// this implementation assumes the consumer only cares about the objects, +// not the order in which they were created/added. +func (f *RealFIFO) Delete(obj interface{}) error { + f.lock.Lock() + defer f.lock.Unlock() + + f.populated = true + retErr := f.addToItems_locked(Deleted, false, obj) + + return retErr +} + +// IsClosed checks if the queue is closed +func (f *RealFIFO) IsClosed() bool { + f.lock.Lock() + defer f.lock.Unlock() + return f.closed +} + +// Pop waits until an item is ready and processes it. If multiple items are +// ready, they are returned in the order in which they were added/updated. +// The item is removed from the queue (and the store) before it is processed. +// process function is called under lock, so it is safe +// update data structures in it that need to be in sync with the queue. +func (f *RealFIFO) Pop(process PopProcessFunc) (interface{}, error) { + f.lock.Lock() + defer f.lock.Unlock() + + for len(f.items) == 0 { + // When the queue is empty, invocation of Pop() is blocked until new item is enqueued. + // When Close() is called, the f.closed is set and the condition is broadcasted. + // Which causes this loop to continue and return from the Pop(). + if f.closed { + return nil, ErrFIFOClosed + } + + f.cond.Wait() + } + + isInInitialList := !f.hasSynced_locked() + item := f.items[0] + // The underlying array still exists and references this object, so the object will not be garbage collected unless we zero the reference. + f.items[0] = Delta{} + f.items = f.items[1:] + if f.initialPopulationCount > 0 { + f.initialPopulationCount-- + } + + // Only log traces if the queue depth is greater than 10 and it takes more than + // 100 milliseconds to process one item from the queue. + // Queue depth never goes high because processing an item is locking the queue, + // and new items can't be added until processing finish. + // https://github.com/kubernetes/kubernetes/issues/103789 + if len(f.items) > 10 { + id, _ := f.keyOf(item) + trace := utiltrace.New("RealFIFO Pop Process", + utiltrace.Field{Key: "ID", Value: id}, + utiltrace.Field{Key: "Depth", Value: len(f.items)}, + utiltrace.Field{Key: "Reason", Value: "slow event handlers blocking the queue"}) + defer trace.LogIfLong(100 * time.Millisecond) + } + + // we wrap in Deltas here to be compatible with preview Pop functions and those interpreting the return value. + err := process(Deltas{item}, isInInitialList) + return Deltas{item}, err +} + +// Replace +// 1. finds those items in f.items that are not in newItems and creates synthetic deletes for them +// 2. finds items in knownObjects that are not in newItems and creates synthetic deletes for them +// 3. adds the newItems to the queue +func (f *RealFIFO) Replace(newItems []interface{}, resourceVersion string) error { + f.lock.Lock() + defer f.lock.Unlock() + + // determine the keys of everything we're adding. We cannot add the items until after the synthetic deletes have been + // created for items that don't existing in newItems + newKeys := sets.Set[string]{} + for _, obj := range newItems { + key, err := f.keyOf(obj) + if err != nil { + return KeyError{obj, err} + } + newKeys.Insert(key) + } + + queuedItems := f.items + queuedKeys := []string{} + lastQueuedItemForKey := map[string]Delta{} + for _, queuedItem := range queuedItems { + queuedKey, err := f.keyOf(queuedItem.Object) + if err != nil { + return KeyError{queuedItem.Object, err} + } + + if _, seen := lastQueuedItemForKey[queuedKey]; !seen { + queuedKeys = append(queuedKeys, queuedKey) + } + lastQueuedItemForKey[queuedKey] = queuedItem + } + + // all the deletes already in the queue are important. There are two cases + // 1. queuedItems has delete for key/X and newItems has replace for key/X. This means the queued UID was deleted and a new one was created. + // 2. queuedItems has a delete for key/X and newItems does NOT have key/X. This means the queued item was deleted. + // Do deletion detection against objects in the queue. + for _, queuedKey := range queuedKeys { + if newKeys.Has(queuedKey) { + continue + } + + // Delete pre-existing items not in the new list. + // This could happen if watch deletion event was missed while + // disconnected from apiserver. + lastQueuedItem := lastQueuedItemForKey[queuedKey] + // if we've already got the item marked as deleted, no need to add another delete + if lastQueuedItem.Type == Deleted { + continue + } + + // if we got here, then the last entry we have for the queued item is *not* a deletion and we need to add a delete + deletedObj := lastQueuedItem.Object + + retErr := f.addToItems_locked(Deleted, true, DeletedFinalStateUnknown{ + Key: queuedKey, + Obj: deletedObj, + }) + if retErr != nil { + return fmt.Errorf("couldn't enqueue object: %w", retErr) + } + } + + // Detect deletions for objects not present in the queue, but present in KnownObjects + knownKeys := f.knownObjects.ListKeys() + for _, knownKey := range knownKeys { + if newKeys.Has(knownKey) { // still present + continue + } + if _, inQueuedItems := lastQueuedItemForKey[knownKey]; inQueuedItems { // already added delete for these + continue + } + + deletedObj, exists, err := f.knownObjects.GetByKey(knownKey) + if err != nil { + deletedObj = nil + utilruntime.HandleError(fmt.Errorf("error during lookup, placing DeleteFinalStateUnknown marker without object: key=%q, err=%w", knownKey, err)) + } else if !exists { + deletedObj = nil + utilruntime.HandleError(fmt.Errorf("key does not exist in known objects store, placing DeleteFinalStateUnknown marker without object: key=%q", knownKey)) + } + retErr := f.addToItems_locked(Deleted, false, DeletedFinalStateUnknown{ + Key: knownKey, + Obj: deletedObj, + }) + if retErr != nil { + return fmt.Errorf("couldn't enqueue object: %w", retErr) + } + } + + // now that we have the deletes we need for items, we can add the newItems to the items queue + for _, obj := range newItems { + retErr := f.addToItems_locked(Replaced, false, obj) + if retErr != nil { + return fmt.Errorf("couldn't enqueue object: %w", retErr) + } + } + + if !f.populated { + f.populated = true + f.initialPopulationCount = len(f.items) + } + + return nil +} + +// Resync will ensure that every object in the Store has its key in the queue. +// This should be a no-op, because that property is maintained by all operations. +func (f *RealFIFO) Resync() error { + // TODO this cannot logically be done by the FIFO, it can only be done by the indexer + f.lock.Lock() + defer f.lock.Unlock() + + if f.knownObjects == nil { + return nil + } + + keysInQueue := sets.Set[string]{} + for _, item := range f.items { + key, err := f.keyOf(item.Object) + if err != nil { + return KeyError{item, err} + } + keysInQueue.Insert(key) + } + + knownKeys := f.knownObjects.ListKeys() + for _, knownKey := range knownKeys { + // If we are doing Resync() and there is already an event queued for that object, + // we ignore the Resync for it. This is to avoid the race, in which the resync + // comes with the previous value of object (since queueing an event for the object + // doesn't trigger changing the underlying store . + if keysInQueue.Has(knownKey) { + continue + } + + knownObj, exists, err := f.knownObjects.GetByKey(knownKey) + if err != nil { + utilruntime.HandleError(fmt.Errorf("unable to queue object for sync: key=%q, err=%w", knownKey, err)) + continue + } else if !exists { + utilruntime.HandleError(fmt.Errorf("key does not exist in known objects store, unable to queue object for sync: key=%q", knownKey)) + continue + } + + retErr := f.addToItems_locked(Sync, true, knownObj) + if retErr != nil { + return fmt.Errorf("couldn't queue object: %w", err) + } + } + + return nil +} + +// NewRealFIFO returns a Store which can be used to queue up items to +// process. +func NewRealFIFO(keyFunc KeyFunc, knownObjects KeyListerGetter, transformer TransformFunc) *RealFIFO { + if knownObjects == nil { + panic("coding error: knownObjects must be provided") + } + + f := &RealFIFO{ + items: make([]Delta, 0, 10), + keyFunc: keyFunc, + knownObjects: knownObjects, + transformer: transformer, + } + f.cond.L = &f.lock + return f +} diff --git a/tools/cache/the_real_fifo_test.go b/tools/cache/the_real_fifo_test.go new file mode 100644 index 0000000000..649ea36872 --- /dev/null +++ b/tools/cache/the_real_fifo_test.go @@ -0,0 +1,976 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cache + +import ( + "fmt" + "reflect" + "runtime" + "testing" + "time" +) + +func (f *RealFIFO) getItems() []Delta { + f.lock.Lock() + defer f.lock.Unlock() + + ret := make([]Delta, len(f.items)) + copy(ret, f.items) + return ret +} + +const closedFIFOName = "FIFO WAS CLOSED" + +func popN(queue Queue, count int) []interface{} { + result := []interface{}{} + for i := 0; i < count; i++ { + queue.Pop(func(obj interface{}, isInInitialList bool) error { + result = append(result, obj) + return nil + }) + } + return result +} + +// helper function to reduce stuttering +func testRealFIFOPop(f *RealFIFO) testFifoObject { + val := Pop(f) + if val == nil { + return testFifoObject{name: closedFIFOName} + } + return val.(Deltas).Newest().Object.(testFifoObject) +} + +func emptyKnownObjects() KeyListerGetter { + return literalListerGetter( + func() []testFifoObject { + return []testFifoObject{} + }, + ) +} + +func TestRealFIFO_basic(t *testing.T) { + f := NewRealFIFO(testFifoObjectKeyFunc, emptyKnownObjects(), nil) + const amount = 500 + go func() { + for i := 0; i < amount; i++ { + f.Add(mkFifoObj(string([]rune{'a', rune(i)}), i+1)) + } + }() + go func() { + for u := uint64(0); u < amount; u++ { + f.Add(mkFifoObj(string([]rune{'b', rune(u)}), u+1)) + } + }() + + lastInt := int(0) + lastUint := uint64(0) + for i := 0; i < amount*2; i++ { + switch obj := testRealFIFOPop(f).val.(type) { + case int: + if obj <= lastInt { + t.Errorf("got %v (int) out of order, last was %v", obj, lastInt) + } + lastInt = obj + case uint64: + if obj <= lastUint { + t.Errorf("got %v (uint) out of order, last was %v", obj, lastUint) + } else { + lastUint = obj + } + default: + t.Fatalf("unexpected type %#v", obj) + } + } +} + +// TestRealFIFO_replaceWithDeleteDeltaIn tests that a `Sync` delta for an +// object `O` with ID `X` is added when .Replace is called and `O` is among the +// replacement objects even if the RealFIFO already stores in terminal position +// a delta of type `Delete` for ID `X`. Not adding the `Sync` delta causes +// SharedIndexInformers to miss `O`'s create notification, see https://github.com/kubernetes/kubernetes/issues/83810 +// for more details. +func TestRealFIFO_replaceWithDeleteDeltaIn(t *testing.T) { + oldObj := mkFifoObj("foo", 1) + newObj := mkFifoObj("foo", 2) + + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{oldObj} + }), + nil, + ) + + f.Delete(oldObj) + f.Replace([]interface{}{newObj}, "") + + actualDeltas := f.getItems() + expectedDeltas := []Delta{ + {Type: Deleted, Object: oldObj}, + {Type: Replaced, Object: newObj}, + } + if !reflect.DeepEqual(expectedDeltas, actualDeltas) { + t.Errorf("expected %#v, got %#v", expectedDeltas, actualDeltas) + } +} + +func TestRealFIFOW_ReplaceMakesDeletionsForObjectsOnlyInQueue(t *testing.T) { + obj := mkFifoObj("foo", 2) + objV2 := mkFifoObj("foo", 3) + table := []struct { + name string + operations func(f *RealFIFO) + expectedDeltas Deltas + }{ + { + name: "Added object should be deleted on Replace", + operations: func(f *RealFIFO) { + f.Add(obj) + f.Replace([]interface{}{}, "0") + }, + expectedDeltas: Deltas{ + {Added, obj}, + {Deleted, DeletedFinalStateUnknown{Key: "foo", Obj: obj}}, + }, + }, + //{ + // // ATTENTION: difference with delta_fifo_test, there is no option for emitDeltaTypeReplaced + // name: "Replaced object should have only a single Delete", + // operations: func(f *RealFIFO) { + // f.emitDeltaTypeReplaced = true + // f.Add(obj) + // f.Replace([]interface{}{obj}, "0") + // f.Replace([]interface{}{}, "0") + // }, + // expectedDeltas: Deltas{ + // {Added, obj}, + // {Replaced, obj}, + // {Deleted, DeletedFinalStateUnknown{Key: "foo", Obj: obj}}, + // }, + //}, + { + name: "Deleted object should have only a single Delete", + operations: func(f *RealFIFO) { + f.Add(obj) + f.Delete(obj) + f.Replace([]interface{}{}, "0") + }, + expectedDeltas: Deltas{ + {Added, obj}, + {Deleted, obj}, + }, + }, + { + name: "Synced objects should have a single delete", + operations: func(f *RealFIFO) { + f.Add(obj) + f.Replace([]interface{}{obj}, "0") + f.Replace([]interface{}{obj}, "0") + f.Replace([]interface{}{}, "0") + }, + expectedDeltas: Deltas{ + {Added, obj}, + {Replaced, obj}, + {Replaced, obj}, + {Deleted, DeletedFinalStateUnknown{Key: "foo", Obj: obj}}, + }, + }, + { + name: "Added objects should have a single delete on multiple Replaces", + operations: func(f *RealFIFO) { + f.Add(obj) + f.Replace([]interface{}{}, "0") + f.Replace([]interface{}{}, "1") + }, + expectedDeltas: Deltas{ + {Added, obj}, + {Deleted, DeletedFinalStateUnknown{Key: "foo", Obj: obj}}, + }, + }, + { + name: "Added and deleted and added object should be deleted", + operations: func(f *RealFIFO) { + f.Add(obj) + f.Delete(obj) + f.Add(objV2) + f.Replace([]interface{}{}, "0") + }, + expectedDeltas: Deltas{ + {Added, obj}, + {Deleted, obj}, + {Added, objV2}, + {Deleted, DeletedFinalStateUnknown{Key: "foo", Obj: objV2}}, + }, + }, + } + for _, tt := range table { + tt := tt + + t.Run(tt.name, func(t *testing.T) { + // Test with a RealFIFO with a backing KnownObjects + fWithKnownObjects := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{} + }), + nil, + ) + tt.operations(fWithKnownObjects) + actualDeltasWithKnownObjects := popN(fWithKnownObjects, len(fWithKnownObjects.getItems())) + actualAsDeltas := collapseDeltas(actualDeltasWithKnownObjects) + if !reflect.DeepEqual(tt.expectedDeltas, actualAsDeltas) { + t.Errorf("expected %#v, got %#v", tt.expectedDeltas, actualAsDeltas) + } + if len(fWithKnownObjects.items) != 0 { + t.Errorf("expected no extra deltas (empty map), got %#v", fWithKnownObjects.items) + } + + // ATTENTION: difference with delta_fifo_test, there is no option without knownObjects + }) + } +} + +func collapseDeltas(ins []interface{}) Deltas { + ret := Deltas{} + for _, curr := range ins { + for _, delta := range curr.(Deltas) { + ret = append(ret, delta) + } + } + return ret +} + +// ATTENTION: difference with delta_fifo_test, there is no requeue option anymore +// func TestDeltaFIFO_requeueOnPop(t *testing.T) { + +func TestRealFIFO_addUpdate(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + nil, + ) + f.Add(mkFifoObj("foo", 10)) + f.Update(mkFifoObj("foo", 12)) + f.Delete(mkFifoObj("foo", 15)) + + // ATTENTION: difference with delta_fifo_test, all items on the list. DeltaFIFO.List only showed newest, but Pop processed all. + expected1 := []Delta{ + { + Type: Added, + Object: mkFifoObj("foo", 10), + }, + { + Type: Updated, + Object: mkFifoObj("foo", 12), + }, + { + Type: Deleted, + Object: mkFifoObj("foo", 15), + }, + } + if e, a := expected1, f.getItems(); !reflect.DeepEqual(e, a) { + t.Errorf("Expected %+v, got %+v", e, a) + } + + got := make(chan testFifoObject, 4) + done := make(chan struct{}) + go func() { + defer close(done) + for { + obj := testRealFIFOPop(f) + if obj.name == closedFIFOName { + break + } + t.Logf("got a thing %#v", obj) + t.Logf("D len: %v", len(f.items)) + got <- obj + } + }() + + first := <-got + if e, a := 10, first.val; e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + second := <-got + if e, a := 12, second.val; e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + third := <-got + if e, a := 15, third.val; e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + select { + case unexpected := <-got: + t.Errorf("Got second value %v", unexpected.val) + case <-time.After(50 * time.Millisecond): + } + + if e, a := 0, len(f.getItems()); e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + f.Close() + <-done +} + +func TestRealFIFO_transformer(t *testing.T) { + mk := func(name string, rv int) testFifoObject { + return mkFifoObj(name, &rvAndXfrm{rv, 0}) + } + xfrm := TransformFunc(func(obj interface{}) (interface{}, error) { + switch v := obj.(type) { + case testFifoObject: + v.val.(*rvAndXfrm).xfrm++ + case DeletedFinalStateUnknown: + if x := v.Obj.(testFifoObject).val.(*rvAndXfrm).xfrm; x != 1 { + return nil, fmt.Errorf("object has been transformed wrong number of times: %#v", obj) + } + default: + return nil, fmt.Errorf("unexpected object: %#v", obj) + } + return obj, nil + }) + + must := func(err error) { + if err != nil { + t.Fatal(err) + } + } + mustTransform := func(obj interface{}) interface{} { + ret, err := xfrm(obj) + must(err) + return ret + } + + f := NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + xfrm, + ) + must(f.Add(mk("foo", 10))) + must(f.Add(mk("bar", 11))) + must(f.Update(mk("foo", 12))) + must(f.Delete(mk("foo", 15))) + must(f.Replace([]interface{}{}, "")) + must(f.Add(mk("bar", 16))) + must(f.Replace([]interface{}{}, "")) + + // ATTENTION: difference with delta_fifo_test, without compression, we keep all the items, including bar being deleted multiple times. + // DeltaFIFO starts by checking keys, we start by checking types and keys + expected1 := []Delta{ + {Type: Added, Object: mustTransform(mk("foo", 10))}, + {Type: Added, Object: mustTransform(mk("bar", 11))}, + {Type: Updated, Object: mustTransform(mk("foo", 12))}, + {Type: Deleted, Object: mustTransform(mk("foo", 15))}, + {Type: Deleted, Object: DeletedFinalStateUnknown{Key: "bar", Obj: mustTransform(mk("bar", 11))}}, + {Type: Added, Object: mustTransform(mk("bar", 16))}, + {Type: Deleted, Object: DeletedFinalStateUnknown{Key: "bar", Obj: mustTransform(mk("bar", 16))}}, + } + actual1 := f.getItems() + if len(expected1) != len(actual1) { + t.Fatalf("Expected %+v, got %+v", expected1, actual1) + } + for i := 0; i < len(actual1); i++ { + e := expected1[i] + a := actual1[i] + if e.Type != a.Type { + t.Errorf("%d Expected %+v, got %+v", i, e, a) + } + eKey, err := f.keyOf(e) + if err != nil { + t.Fatal(err) + } + aKey, err := f.keyOf(a) + if err != nil { + t.Fatal(err) + } + if eKey != aKey { + t.Errorf("%d Expected %+v, got %+v", i, eKey, aKey) + } + } + + for i := 0; i < len(expected1); i++ { + obj, err := f.Pop(func(o interface{}, isInInitialList bool) error { return nil }) + if err != nil { + t.Fatalf("got nothing on try %v?", i) + } + a := obj.(Deltas)[0] + e := expected1[i] + if !reflect.DeepEqual(e, a) { + t.Errorf("%d Expected %+v, got %+v", i, e, a) + } + } +} + +func TestRealFIFO_enqueueingNoLister(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + nil, + ) + f.Add(mkFifoObj("foo", 10)) + f.Update(mkFifoObj("bar", 15)) + f.Add(mkFifoObj("qux", 17)) + f.Delete(mkFifoObj("qux", 18)) + + // RealFIFO queues everything + f.Delete(mkFifoObj("baz", 20)) + + // ATTENTION: difference with delta_fifo_test, without compression every item is queued + expectList := []int{10, 15, 17, 18, 20} + for _, expect := range expectList { + if e, a := expect, testRealFIFOPop(f).val; e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + } + if e, a := 0, len(f.getItems()); e != a { + t.Errorf("queue unexpectedly not empty: %v != %v\n%#v", e, a, f.getItems()) + } +} + +func TestRealFIFO_enqueueingWithLister(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} + }), + nil, + ) + f.Add(mkFifoObj("foo", 10)) + f.Update(mkFifoObj("bar", 15)) + + // This delete does enqueue the deletion, because "baz" is in the key lister. + f.Delete(mkFifoObj("baz", 20)) + + expectList := []int{10, 15, 20} + for _, expect := range expectList { + if e, a := expect, testRealFIFOPop(f).val; e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + } + if e, a := 0, len(f.items); e != a { + t.Errorf("queue unexpectedly not empty: %v != %v", e, a) + } +} + +func TestRealFIFO_addReplace(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + nil, + ) + f.Add(mkFifoObj("foo", 10)) + f.Replace([]interface{}{mkFifoObj("foo", 15)}, "0") + got := make(chan testFifoObject, 3) + done := make(chan struct{}) + go func() { + defer close(done) + for { + obj := testRealFIFOPop(f) + if obj.name == closedFIFOName { + break + } + got <- obj + } + }() + + // ATTENTION: difference with delta_fifo_test, we get every event instead of the .Newest making us skip some for the test, but not at runtime. + curr := <-got + if e, a := 10, curr.val; e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + curr = <-got + if e, a := 15, curr.val; e != a { + t.Errorf("Didn't get updated value (%v), got %v", e, a) + } + + select { + case unexpected := <-got: + t.Errorf("Got second value %v", unexpected.val) + case <-time.After(50 * time.Millisecond): + } + + if items := f.getItems(); len(items) > 0 { + t.Errorf("item did not get removed") + } + f.Close() + <-done +} + +func TestRealFIFO_ResyncNonExisting(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5)} + }), + nil, + ) + f.Delete(mkFifoObj("foo", 10)) + f.Resync() + + deltas := f.getItems() + if len(deltas) != 1 { + t.Fatalf("unexpected deltas length: %v", deltas) + } + if deltas[0].Type != Deleted { + t.Errorf("unexpected delta: %v", deltas[0]) + } +} + +func TestRealFIFO_Resync(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5)} + }), + nil, + ) + f.Resync() + + deltas := f.getItems() + if len(deltas) != 1 { + t.Fatalf("unexpected deltas length: %v", deltas) + } + if deltas[0].Type != Sync { + t.Errorf("unexpected delta: %v", deltas[0]) + } +} + +func TestRealFIFO_DeleteExistingNonPropagated(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + nil, + ) + f.Add(mkFifoObj("foo", 5)) + f.Delete(mkFifoObj("foo", 6)) + + deltas := f.getItems() + if len(deltas) != 2 { + t.Fatalf("unexpected deltas length: %v", deltas) + } + if deltas[len(deltas)-1].Type != Deleted { + t.Errorf("unexpected delta: %v", deltas[len(deltas)-1]) + } +} + +func TestRealFIFO_ReplaceMakesDeletions(t *testing.T) { + // We test with only one pre-existing object because there is no + // promise about how their deletes are ordered. + + // Try it with a pre-existing Delete + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} + }), + nil, + ) + f.Delete(mkFifoObj("baz", 10)) + f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") + + expectedList := []Deltas{ + {{Deleted, mkFifoObj("baz", 10)}}, + // ATTENTION: difference with delta_fifo_test, logically the deletes of known items should happen BEFORE newItems are added, so this delete happens early now + // Since "bar" didn't have a delete event and wasn't in the Replace list + // it should get a tombstone key with the right Obj. + {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 6)}}}, + {{Replaced, mkFifoObj("foo", 5)}}, + } + + for _, expected := range expectedList { + cur := Pop(f).(Deltas) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("Expected %#v, got %#v", e, a) + } + } + + // Now try starting with an Add instead of a Delete + f = NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} + }), + nil, + ) + f.Add(mkFifoObj("baz", 10)) + f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") + + // ATTENTION: difference with delta_fifo_test, every event is its own Deltas with one item + expectedList = []Deltas{ + {{Added, mkFifoObj("baz", 10)}}, + {{Deleted, DeletedFinalStateUnknown{Key: "baz", Obj: mkFifoObj("baz", 10)}}}, + // ATTENTION: difference with delta_fifo_test, logically the deletes of known items should happen BEFORE newItems are added, so this delete happens early now + // Since "bar" didn't have a delete event and wasn't in the Replace list + // it should get a tombstone key with the right Obj. + {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 6)}}}, + {{Replaced, mkFifoObj("foo", 5)}}, + } + + for _, expected := range expectedList { + cur := Pop(f).(Deltas) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("Expected %#v, got %#v", e, a) + } + } + + // Now try deleting and recreating the object in the queue, then delete it by a Replace call + f = NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} + }), + nil, + ) + f.Delete(mkFifoObj("bar", 6)) + f.Add(mkFifoObj("bar", 100)) + f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") + + // ATTENTION: difference with delta_fifo_test, every event is its own Deltas with one item + expectedList = []Deltas{ + {{Deleted, mkFifoObj("bar", 6)}}, + {{Added, mkFifoObj("bar", 100)}}, + // Since "bar" has a newer object in the queue than in the state, + // it should get a tombstone key with the latest object from the queue + {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 100)}}}, + // ATTENTION: difference with delta_fifo_test, logically the deletes of known items should happen BEFORE newItems are added, so this delete happens early now + {{Deleted, DeletedFinalStateUnknown{Key: "baz", Obj: mkFifoObj("baz", 7)}}}, + {{Replaced, mkFifoObj("foo", 5)}}, + } + + for _, expected := range expectedList { + cur := Pop(f).(Deltas) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("Expected %#v, got %#v", e, a) + } + } + + // Now try syncing it first to ensure the delete use the latest version + f = NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} + }), + nil, + ) + f.Replace([]interface{}{mkFifoObj("bar", 100), mkFifoObj("foo", 5)}, "0") + f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") + + // ATTENTION: difference with delta_fifo_test, every event is its own Deltas with one item + // ATTENTION: difference with delta_fifo_test, deltaFifo associated by key, but realFIFO orders across all keys, so this ordering changed + expectedList = []Deltas{ + // ATTENTION: difference with delta_fifo_test, logically the deletes of known items should happen BEFORE newItems are added, so this delete happens early now + // Since "baz" didn't have a delete event and wasn't in the Replace list + {{Deleted, DeletedFinalStateUnknown{Key: "baz", Obj: mkFifoObj("baz", 7)}}}, + {{Replaced, mkFifoObj("bar", 100)}}, + {{Replaced, mkFifoObj("foo", 5)}}, + // Since "bar" didn't have a delete event and wasn't in the Replace list + // it should get a tombstone key with the right Obj. + {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 100)}}}, + {{Replaced, mkFifoObj("foo", 5)}}, + } + + for i, expected := range expectedList { + cur := Pop(f).(Deltas) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("%d Expected %#v, got %#v", i, e, a) + } + } + + // Now try starting without an explicit KeyListerGetter + f = NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + nil, + ) + f.Add(mkFifoObj("baz", 10)) + f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") + + expectedList = []Deltas{ + {{Added, mkFifoObj("baz", 10)}}, + {{Deleted, DeletedFinalStateUnknown{Key: "baz", Obj: mkFifoObj("baz", 10)}}}, + {{Replaced, mkFifoObj("foo", 5)}}, + } + + for _, expected := range expectedList { + cur := Pop(f).(Deltas) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("Expected %#v, got %#v", e, a) + } + } +} + +// TestRealFIFO_ReplaceMakesDeletionsReplaced is the same as the above test, but +// ensures that a Replaced DeltaType is emitted. +func TestRealFIFO_ReplaceMakesDeletionsReplaced(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} + }), + nil, + ) + + f.Delete(mkFifoObj("baz", 10)) + f.Replace([]interface{}{mkFifoObj("foo", 6)}, "0") + + expectedList := []Deltas{ + {{Deleted, mkFifoObj("baz", 10)}}, + // ATTENTION: difference with delta_fifo_test, logically the deletes of known items should happen BEFORE newItems are added, so this delete happens early now + // Since "bar" didn't have a delete event and wasn't in the Replace list + // it should get a tombstone key with the right Obj. + {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 6)}}}, + {{Replaced, mkFifoObj("foo", 6)}}, + } + + for _, expected := range expectedList { + cur := Pop(f).(Deltas) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("Expected %#v, got %#v", e, a) + } + } +} + +// ATTENTION: difference with delta_fifo_test, the previous value was hardcoded as use "Replace" so I've eliminated the option to set it differently +//func TestRealFIFO_ReplaceDeltaType(t *testing.T) { + +func TestRealFIFO_UpdateResyncRace(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5)} + }), + nil, + ) + f.Update(mkFifoObj("foo", 6)) + f.Resync() + + expectedList := []Deltas{ + {{Updated, mkFifoObj("foo", 6)}}, + } + + for _, expected := range expectedList { + cur := Pop(f).(Deltas) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("Expected %#v, got %#v", e, a) + } + } +} + +func TestRealFIFO_HasSyncedCorrectOnDeletion(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} + }), + nil, + ) + f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") + + expectedList := []Deltas{ + // ATTENTION: difference with delta_fifo_test, logically the deletes of known items should happen BEFORE newItems are added, so this delete happens early now + // Since "bar" didn't have a delete event and wasn't in the Replace list + // it should get a tombstone key with the right Obj. + {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 6)}}}, + {{Deleted, DeletedFinalStateUnknown{Key: "baz", Obj: mkFifoObj("baz", 7)}}}, + {{Replaced, mkFifoObj("foo", 5)}}, + } + + for _, expected := range expectedList { + if f.HasSynced() { + t.Errorf("Expected HasSynced to be false") + } + cur, initial := pop2[Deltas](f) + if e, a := expected, cur; !reflect.DeepEqual(e, a) { + t.Errorf("Expected %#v, got %#v", e, a) + } + if initial != true { + t.Error("Expected initial list item") + } + } + if !f.HasSynced() { + t.Errorf("Expected HasSynced to be true") + } +} + +func TestRealFIFO_detectLineJumpers(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + nil, + ) + + f.Add(mkFifoObj("foo", 10)) + f.Add(mkFifoObj("bar", 1)) + f.Add(mkFifoObj("foo", 11)) + f.Add(mkFifoObj("foo", 13)) + f.Add(mkFifoObj("zab", 30)) + + // ATTENTION: difference with delta_fifo_test, every event is delivered in order + + if e, a := 10, testRealFIFOPop(f).val; a != e { + t.Fatalf("expected %d, got %d", e, a) + } + + f.Add(mkFifoObj("foo", 14)) // ensure foo doesn't jump back in line + + if e, a := 1, testRealFIFOPop(f).val; a != e { + t.Fatalf("expected %d, got %d", e, a) + } + if e, a := 11, testRealFIFOPop(f).val; a != e { + t.Fatalf("expected %d, got %d", e, a) + } + if e, a := 13, testRealFIFOPop(f).val; a != e { + t.Fatalf("expected %d, got %d", e, a) + } + if e, a := 30, testRealFIFOPop(f).val; a != e { + t.Fatalf("expected %d, got %d", e, a) + } + if e, a := 14, testRealFIFOPop(f).val; a != e { + t.Fatalf("expected %d, got %d", e, a) + } +} + +func TestRealFIFO_KeyOf(t *testing.T) { + f := RealFIFO{keyFunc: testFifoObjectKeyFunc} + + table := []struct { + obj interface{} + key string + }{ + {obj: testFifoObject{name: "A"}, key: "A"}, + {obj: DeletedFinalStateUnknown{Key: "B", Obj: nil}, key: "B"}, + {obj: Deltas{{Object: testFifoObject{name: "C"}}}, key: "C"}, + {obj: Deltas{{Object: DeletedFinalStateUnknown{Key: "D", Obj: nil}}}, key: "D"}, + } + + for _, item := range table { + got, err := f.keyOf(item.obj) + if err != nil { + t.Errorf("Unexpected error for %q: %v", item.obj, err) + continue + } + if e, a := item.key, got; e != a { + t.Errorf("Expected %v, got %v", e, a) + } + } +} + +func TestRealFIFO_HasSynced(t *testing.T) { + tests := []struct { + actions []func(f *RealFIFO) + expectedSynced bool + }{ + { + actions: []func(f *RealFIFO){}, + expectedSynced: false, + }, + { + actions: []func(f *RealFIFO){ + func(f *RealFIFO) { f.Add(mkFifoObj("a", 1)) }, + }, + expectedSynced: true, + }, + { + actions: []func(f *RealFIFO){ + func(f *RealFIFO) { f.Replace([]interface{}{}, "0") }, + }, + expectedSynced: true, + }, + { + actions: []func(f *RealFIFO){ + func(f *RealFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, + }, + expectedSynced: false, + }, + { + actions: []func(f *RealFIFO){ + func(f *RealFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, + func(f *RealFIFO) { Pop(f) }, + }, + expectedSynced: false, + }, + { + actions: []func(f *RealFIFO){ + func(f *RealFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, + func(f *RealFIFO) { Pop(f) }, + func(f *RealFIFO) { Pop(f) }, + }, + expectedSynced: true, + }, + { + // This test case won't happen in practice since a Reflector, the only producer for delta_fifo today, always passes a complete snapshot consistent in time; + // there cannot be duplicate keys in the list or apiserver is broken. + actions: []func(f *RealFIFO){ + func(f *RealFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("a", 2)}, "0") }, + func(f *RealFIFO) { Pop(f) }, + // ATTENTION: difference with delta_fifo_test, every event is delivered, so a is listed twice and must be popped twice to remove both + func(f *RealFIFO) { Pop(f) }, + }, + expectedSynced: true, + }, + } + + for i, test := range tests { + f := NewRealFIFO( + testFifoObjectKeyFunc, + emptyKnownObjects(), + nil, + ) + + for _, action := range test.actions { + action(f) + } + if e, a := test.expectedSynced, f.HasSynced(); a != e { + t.Errorf("test case %v failed, expected: %v , got %v", i, e, a) + } + } +} + +// TestRealFIFO_PopShouldUnblockWhenClosed checks that any blocking Pop on an empty queue +// should unblock and return after Close is called. +func TestRealFIFO_PopShouldUnblockWhenClosed(t *testing.T) { + f := NewRealFIFO( + testFifoObjectKeyFunc, + literalListerGetter(func() []testFifoObject { + return []testFifoObject{mkFifoObj("foo", 5)} + }), + nil, + ) + + c := make(chan struct{}) + const jobs = 10 + for i := 0; i < jobs; i++ { + go func() { + f.Pop(func(obj interface{}, isInInitialList bool) error { + return nil + }) + c <- struct{}{} + }() + } + + runtime.Gosched() + f.Close() + + for i := 0; i < jobs; i++ { + select { + case <-c: + case <-time.After(500 * time.Millisecond): + t.Fatalf("timed out waiting for Pop to return after Close") + } + } +} diff --git a/tools/cache/util_test.go b/tools/cache/util_test.go new file mode 100644 index 0000000000..ed19e3ebad --- /dev/null +++ b/tools/cache/util_test.go @@ -0,0 +1,49 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cache + +import ( + "bytes" + "sync" + "testing" + + fcache "k8s.io/client-go/tools/cache/testing" +) + +func newFakeControllerSource(tb testing.TB) *fcache.FakeControllerSource { + source := fcache.NewFakeControllerSource() + tb.Cleanup(source.Shutdown) + return source +} + +// threadSafeBuffer is a thread-safe wrapper around bytes.Buffer. +type threadSafeBuffer struct { + buffer bytes.Buffer + mu sync.Mutex +} + +func (b *threadSafeBuffer) Write(p []byte) (n int, err error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buffer.Write(p) +} + +func (b *threadSafeBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buffer.String() +} diff --git a/tools/clientcmd/api/doc.go b/tools/clientcmd/api/doc.go index fd913a3083..5871575a66 100644 --- a/tools/clientcmd/api/doc.go +++ b/tools/clientcmd/api/doc.go @@ -16,4 +16,4 @@ limitations under the License. // +k8s:deepcopy-gen=package -package api // import "k8s.io/client-go/tools/clientcmd/api" +package api diff --git a/tools/clientcmd/api/v1/doc.go b/tools/clientcmd/api/v1/doc.go index 9e483e9d75..3ccdebc1c3 100644 --- a/tools/clientcmd/api/v1/doc.go +++ b/tools/clientcmd/api/v1/doc.go @@ -18,4 +18,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // +k8s:defaulter-gen=Kind -package v1 // import "k8s.io/client-go/tools/clientcmd/api/v1" +package v1 diff --git a/tools/clientcmd/doc.go b/tools/clientcmd/doc.go index 424311ee12..c07ace6a58 100644 --- a/tools/clientcmd/doc.go +++ b/tools/clientcmd/doc.go @@ -34,4 +34,4 @@ Sample usage from merged .kubeconfig files (local directory, home directory) client, err := metav1.New(config) // ... */ -package clientcmd // import "k8s.io/client-go/tools/clientcmd" +package clientcmd diff --git a/tools/events/doc.go b/tools/events/doc.go index 8c48f607e1..08c0ba70bd 100644 --- a/tools/events/doc.go +++ b/tools/events/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package events has all client logic for recording and reporting // "k8s.io/api/events/v1".Event events. -package events // import "k8s.io/client-go/tools/events" +package events diff --git a/tools/events/event_recorder.go b/tools/events/event_recorder.go index 654317884f..ba2ec7be4e 100644 --- a/tools/events/event_recorder.go +++ b/tools/events/event_recorder.go @@ -96,7 +96,7 @@ func (recorder *recorderImpl) makeEvent(refRegarding *v1.ObjectReference, refRel } return &eventsv1.Event{ ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("%v.%x", refRegarding.Name, t.UnixNano()), + Name: util.GenerateEventName(refRegarding.Name, t.UnixNano()), Namespace: namespace, }, EventTime: timestamp, diff --git a/tools/events/event_recorder_test.go b/tools/events/event_recorder_test.go new file mode 100644 index 0000000000..0e9aed9cd8 --- /dev/null +++ b/tools/events/event_recorder_test.go @@ -0,0 +1,240 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package events + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + + v1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" + + eventsv1 "k8s.io/api/events/v1" + apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + utilvalidation "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/watch" + testclocks "k8s.io/utils/clock/testing" +) + +func TestEventf(t *testing.T) { + // use a fixed time for generated names that depend on the unix timestamp + fakeClock := testclocks.NewFakeClock(time.Date(2023, time.January, 1, 12, 0, 0, 0, time.UTC)) + + testCases := []struct { + desc string + regarding runtime.Object + related runtime.Object + eventtype string + reason string + action string + note string + args []interface{} + expectedEvent *eventsv1.Event + }{ + { + desc: "normal event", + regarding: &v1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "pod1", + Namespace: "ns1", + UID: "12345", + }, + }, + eventtype: "Normal", + reason: "Started", + action: "starting", + note: "Pod started", + expectedEvent: &eventsv1.Event{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("pod1.%x", fakeClock.Now().UnixNano()), + Namespace: "ns1", + }, + Regarding: v1.ObjectReference{ + Kind: "Pod", + Name: "pod1", + Namespace: "ns1", + UID: "12345", + APIVersion: "v1", + }, + Type: "Normal", + Reason: "Started", + Action: "starting", + Note: "Pod started", + ReportingController: "c1", + ReportingInstance: "i1", + }, + }, + { + desc: "event with related object and format args", + regarding: &v1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "pod1", + Namespace: "ns1", + UID: "12345", + }, + }, + related: &v1.Node{ + ObjectMeta: metav1.ObjectMeta{ + Name: "node1", + UID: "67890", + }, + }, + eventtype: "Warning", + reason: "FailedScheduling", + action: "scheduling", + + note: "Pod failed to schedule on %s: %s", + args: []interface{}{"node1", "not enough resources"}, + expectedEvent: &eventsv1.Event{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("pod1.%x", fakeClock.Now().UnixNano()), + Namespace: "ns1", + }, + Regarding: v1.ObjectReference{ + Kind: "Pod", + Name: "pod1", + Namespace: "ns1", + UID: "12345", + APIVersion: "v1", + }, + Related: &v1.ObjectReference{ + Kind: "Node", + Name: "node1", + UID: "67890", + APIVersion: "v1", + }, + Type: "Warning", + Reason: "FailedScheduling", + Action: "scheduling", + Note: "Pod failed to schedule on node1: not enough resources", + ReportingController: "c1", + ReportingInstance: "i1", + }, + }, { + desc: "event with invalid Event name", + regarding: &networkingv1.IPAddress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "2001:db8::123", + UID: "12345", + }, + }, + eventtype: "Warning", + reason: "IPAddressNotAllocated", + action: "IPAddressAllocation", + note: "Service default/test appears to have leaked", + + expectedEvent: &eventsv1.Event{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + }, + Regarding: v1.ObjectReference{ + Kind: "IPAddress", + Name: "2001:db8::123", + UID: "12345", + APIVersion: "networking.k8s.io/v1", + }, + Type: "Warning", + Reason: "IPAddressNotAllocated", + Action: "IPAddressAllocation", + Note: "Service default/test appears to have leaked", + ReportingController: "c1", + ReportingInstance: "i1", + }, + }, { + desc: "large event name", + regarding: &v1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: strings.Repeat("x", utilvalidation.DNS1123SubdomainMaxLength*4), + Namespace: "ns1", + UID: "12345", + }, + }, + eventtype: "Normal", + reason: "Started", + action: "starting", + note: "Pod started", + expectedEvent: &eventsv1.Event{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "ns1", + }, + Regarding: v1.ObjectReference{ + Kind: "Pod", + Name: strings.Repeat("x", utilvalidation.DNS1123SubdomainMaxLength*4), + Namespace: "ns1", + UID: "12345", + APIVersion: "v1", + }, + Type: "Normal", + Reason: "Started", + Action: "starting", + Note: "Pod started", + ReportingController: "c1", + ReportingInstance: "i1", + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + broadcaster := watch.NewBroadcaster(1, watch.WaitIfChannelFull) + recorder := &recorderImpl{ + scheme: runtime.NewScheme(), + reportingController: "c1", + reportingInstance: "i1", + Broadcaster: broadcaster, + clock: fakeClock, + } + + if err := v1.AddToScheme(recorder.scheme); err != nil { + t.Fatal(err) + } + if err := networkingv1.AddToScheme(recorder.scheme); err != nil { + t.Fatal(err) + } + ch, err := broadcaster.Watch() + if err != nil { + t.Fatal(err) + } + recorder.Eventf(tc.regarding, tc.related, tc.eventtype, tc.reason, tc.action, tc.note, tc.args...) + + select { + case event := <-ch.ResultChan(): + actualEvent := event.Object.(*eventsv1.Event) + if errs := apimachineryvalidation.NameIsDNSSubdomain(actualEvent.Name, false); len(errs) > 0 { + t.Errorf("Event Name = %s; not a valid name: %v", actualEvent.Name, errs) + } // Overwrite fields that are not relevant for comparison + tc.expectedEvent.EventTime = actualEvent.EventTime + // invalid event names generate random names + if tc.expectedEvent.Name == "" { + actualEvent.Name = "" + } + if diff := cmp.Diff(tc.expectedEvent, actualEvent); diff != "" { + t.Errorf("Unexpected event diff (-want, +got):\n%s", diff) + } + case <-time.After(time.Second): + t.Errorf("Timeout waiting for event") + } + + }) + } +} diff --git a/tools/leaderelection/leasecandidate.go b/tools/leaderelection/leasecandidate.go index 6ccd4cfbee..9aaf779eaa 100644 --- a/tools/leaderelection/leasecandidate.go +++ b/tools/leaderelection/leasecandidate.go @@ -22,14 +22,14 @@ import ( "time" v1 "k8s.io/api/coordination/v1" - v1alpha2 "k8s.io/api/coordination/v1alpha2" + v1beta1 "k8s.io/api/coordination/v1beta1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" - coordinationv1alpha2client "k8s.io/client-go/kubernetes/typed/coordination/v1alpha2" + coordinationv1beta1client "k8s.io/client-go/kubernetes/typed/coordination/v1beta1" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "k8s.io/klog/v2" @@ -43,7 +43,7 @@ type CacheSyncWaiter interface { } type LeaseCandidate struct { - leaseClient coordinationv1alpha2client.LeaseCandidateInterface + leaseClient coordinationv1beta1client.LeaseCandidateInterface leaseCandidateInformer cache.SharedIndexInformer informerFactory informers.SharedInformerFactory hasSynced cache.InformerSynced @@ -84,10 +84,10 @@ func NewCandidate(clientset kubernetes.Interface, options.FieldSelector = fieldSelector }), ) - leaseCandidateInformer := informerFactory.Coordination().V1alpha2().LeaseCandidates().Informer() + leaseCandidateInformer := informerFactory.Coordination().V1beta1().LeaseCandidates().Informer() lc := &LeaseCandidate{ - leaseClient: clientset.CoordinationV1alpha2().LeaseCandidates(candidateNamespace), + leaseClient: clientset.CoordinationV1beta1().LeaseCandidates(candidateNamespace), leaseCandidateInformer: leaseCandidateInformer, informerFactory: informerFactory, name: candidateName, @@ -102,7 +102,7 @@ func NewCandidate(clientset kubernetes.Interface, h, err := leaseCandidateInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ UpdateFunc: func(oldObj, newObj interface{}) { - if leasecandidate, ok := newObj.(*v1alpha2.LeaseCandidate); ok { + if leasecandidate, ok := newObj.(*v1beta1.LeaseCandidate); ok { if leasecandidate.Spec.PingTime != nil && leasecandidate.Spec.PingTime.After(leasecandidate.Spec.RenewTime.Time) { lc.enqueueLease() } @@ -184,13 +184,13 @@ func (c *LeaseCandidate) ensureLease(ctx context.Context) error { return nil } -func (c *LeaseCandidate) newLeaseCandidate() *v1alpha2.LeaseCandidate { - lc := &v1alpha2.LeaseCandidate{ +func (c *LeaseCandidate) newLeaseCandidate() *v1beta1.LeaseCandidate { + lc := &v1beta1.LeaseCandidate{ ObjectMeta: metav1.ObjectMeta{ Name: c.name, Namespace: c.namespace, }, - Spec: v1alpha2.LeaseCandidateSpec{ + Spec: v1beta1.LeaseCandidateSpec{ LeaseName: c.leaseName, BinaryVersion: c.binaryVersion, EmulationVersion: c.emulationVersion, diff --git a/tools/leaderelection/leasecandidate_test.go b/tools/leaderelection/leasecandidate_test.go index 661643a1e8..3099a4ea3c 100644 --- a/tools/leaderelection/leasecandidate_test.go +++ b/tools/leaderelection/leasecandidate_test.go @@ -101,12 +101,12 @@ func TestLeaseCandidateAck(t *testing.T) { // Update PingTime and verify that the client renews ensureAfter := &metav1.MicroTime{Time: time.Now()} - lc, err := client.CoordinationV1alpha2().LeaseCandidates(tc.candidateNamespace).Get(ctx, tc.candidateName, metav1.GetOptions{}) + lc, err := client.CoordinationV1beta1().LeaseCandidates(tc.candidateNamespace).Get(ctx, tc.candidateName, metav1.GetOptions{}) if err == nil { if lc.Spec.PingTime == nil { c := lc.DeepCopy() c.Spec.PingTime = &metav1.MicroTime{Time: time.Now()} - _, err = client.CoordinationV1alpha2().LeaseCandidates(tc.candidateNamespace).Update(ctx, c, metav1.UpdateOptions{}) + _, err = client.CoordinationV1beta1().LeaseCandidates(tc.candidateNamespace).Update(ctx, c, metav1.UpdateOptions{}) if err != nil { t.Error(err) } @@ -120,7 +120,7 @@ func TestLeaseCandidateAck(t *testing.T) { func pollForLease(ctx context.Context, tc testcase, client *fake.Clientset, t *metav1.MicroTime) error { return wait.PollUntilContextTimeout(ctx, 100*time.Millisecond, 10*time.Second, true, func(ctx context.Context) (done bool, err error) { - lc, err := client.CoordinationV1alpha2().LeaseCandidates(tc.candidateNamespace).Get(ctx, tc.candidateName, metav1.GetOptions{}) + lc, err := client.CoordinationV1beta1().LeaseCandidates(tc.candidateNamespace).Get(ctx, tc.candidateName, metav1.GetOptions{}) if err != nil { if errors.IsNotFound(err) { return false, nil diff --git a/tools/portforward/doc.go b/tools/portforward/doc.go index 2f53406344..e0f6cfbf2b 100644 --- a/tools/portforward/doc.go +++ b/tools/portforward/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package portforward adds support for SSH-like port forwarding from the client's // local host to remote containers. -package portforward // import "k8s.io/client-go/tools/portforward" +package portforward diff --git a/tools/portforward/tunneling_connection_test.go b/tools/portforward/tunneling_connection_test.go index 4127f49d43..afbdb6b0ce 100644 --- a/tools/portforward/tunneling_connection_test.go +++ b/tools/portforward/tunneling_connection_test.go @@ -51,12 +51,21 @@ func TestTunnelingConnection_ReadWriteClose(t *testing.T) { Subprotocols: []string{constants.WebsocketsSPDYTunnelingPortForwardV1}, } conn, err := upgrader.Upgrade(w, req, nil) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } defer conn.Close() //nolint:errcheck - require.Equal(t, constants.WebsocketsSPDYTunnelingPortForwardV1, conn.Subprotocol()) + if conn.Subprotocol() != constants.WebsocketsSPDYTunnelingPortForwardV1 { + t.Errorf("Not acceptable agreement Subprotocol: %v", conn.Subprotocol()) + return + } tunnelingConn := NewTunnelingConnection("server", conn) spdyConn, err := spdy.NewServerConnection(tunnelingConn, justQueueStream(streamChan)) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } defer spdyConn.Close() //nolint:errcheck <-stopServerChan })) @@ -77,9 +86,15 @@ func TestTunnelingConnection_ReadWriteClose(t *testing.T) { var actual []byte go func() { clientStream, err := spdyClient.CreateStream(http.Header{}) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } _, err = io.Copy(clientStream, strings.NewReader(expected)) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } clientStream.Close() //nolint:errcheck }() select { @@ -102,9 +117,14 @@ func TestTunnelingConnection_LocalRemoteAddress(t *testing.T) { Subprotocols: []string{constants.WebsocketsSPDYTunnelingPortForwardV1}, } conn, err := upgrader.Upgrade(w, req, nil) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } defer conn.Close() //nolint:errcheck - require.Equal(t, constants.WebsocketsSPDYTunnelingPortForwardV1, conn.Subprotocol()) + if conn.Subprotocol() != constants.WebsocketsSPDYTunnelingPortForwardV1 { + t.Errorf("Not acceptable agreement Subprotocol: %v", conn.Subprotocol()) + } <-stopServerChan })) defer tunnelingServer.Close() @@ -134,9 +154,15 @@ func TestTunnelingConnection_ReadWriteDeadlines(t *testing.T) { Subprotocols: []string{constants.WebsocketsSPDYTunnelingPortForwardV1}, } conn, err := upgrader.Upgrade(w, req, nil) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } defer conn.Close() //nolint:errcheck - require.Equal(t, constants.WebsocketsSPDYTunnelingPortForwardV1, conn.Subprotocol()) + if conn.Subprotocol() != constants.WebsocketsSPDYTunnelingPortForwardV1 { + t.Errorf("Not acceptable agreement Subprotocol: %v", conn.Subprotocol()) + return + } <-stopServerChan })) defer tunnelingServer.Close() diff --git a/tools/record/doc.go b/tools/record/doc.go index 33d5fe78ee..23a35758c1 100644 --- a/tools/record/doc.go +++ b/tools/record/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package record has all client logic for recording and reporting // "k8s.io/api/core/v1".Event events. -package record // import "k8s.io/client-go/tools/record" +package record diff --git a/tools/record/event.go b/tools/record/event.go index 55947d2094..f97c5d612e 100644 --- a/tools/record/event.go +++ b/tools/record/event.go @@ -489,7 +489,7 @@ func (recorder *recorderImpl) makeEvent(ref *v1.ObjectReference, annotations map } return &v1.Event{ ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("%v.%x", ref.Name, t.UnixNano()), + Name: util.GenerateEventName(ref.Name, t.UnixNano()), Namespace: namespace, Annotations: annotations, }, diff --git a/tools/record/util/util.go b/tools/record/util/util.go index afcc6a6a07..7a82db0cd2 100644 --- a/tools/record/util/util.go +++ b/tools/record/util/util.go @@ -17,10 +17,14 @@ limitations under the License. package util import ( + "fmt" "net/http" + "github.com/google/uuid" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" + apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" ) // ValidateEventType checks that eventtype is an expected type of event @@ -38,3 +42,16 @@ func IsKeyNotFoundError(err error) bool { return statusErr != nil && statusErr.Status().Code == http.StatusNotFound } + +// GenerateEventName generates a valid Event name from the referenced name and the passed UNIX timestamp. +// The referenced Object name may not be a valid name for Events and cause the Event to fail +// to be created, so we need to generate a new one in that case. +// Ref: https://issues.k8s.io/127594 +func GenerateEventName(refName string, unixNano int64) string { + name := fmt.Sprintf("%s.%x", refName, unixNano) + if errs := apimachineryvalidation.NameIsDNSSubdomain(name, false); len(errs) > 0 { + // Using an uuid guarantees uniqueness and correctness + name = uuid.New().String() + } + return name +} diff --git a/tools/record/util/util_test.go b/tools/record/util/util_test.go new file mode 100644 index 0000000000..d6be791eb5 --- /dev/null +++ b/tools/record/util/util_test.go @@ -0,0 +1,72 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package util + +import ( + "strings" + "testing" + + apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" +) + +func TestGenerateEventName(t *testing.T) { + timestamp := int64(105999103295324396) + testCases := []struct { + name string + refName string + expected string + }{ + { + name: "valid name", + refName: "test-pod", + expected: "test-pod.178959f726d80ec", + }, + { + name: "invalid name - too long", + refName: strings.Repeat("x", 300), + }, + { + name: "invalid name - upper case", + refName: "test.POD", + }, + { + name: "invalid name - special chars", + refName: "test.pod/invalid!chars?", + }, + { + name: "invalid name - special chars and non alphanumeric starting character", + refName: "--test.pod/invalid!chars?", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + actual := GenerateEventName(tc.refName, timestamp) + + if errs := apimachineryvalidation.NameIsDNSSubdomain(actual, false); len(errs) > 0 { + t.Errorf("generateEventName(%s) = %s; not a valid name: %v", tc.refName, actual, errs) + + } + + if tc.expected != "" && (actual != tc.expected) { + t.Errorf("generateEventName(%s) returned %s expected %s", tc.refName, actual, tc.expected) + } + + }) + + } +} diff --git a/tools/remotecommand/doc.go b/tools/remotecommand/doc.go index ac06a9cd37..b9f0db2d9a 100644 --- a/tools/remotecommand/doc.go +++ b/tools/remotecommand/doc.go @@ -17,4 +17,4 @@ limitations under the License. // Package remotecommand adds support for executing commands in containers, // with support for separate stdin, stdout, and stderr streams, as well as // TTY. -package remotecommand // import "k8s.io/client-go/tools/remotecommand" +package remotecommand diff --git a/tools/remotecommand/errorstream.go b/tools/remotecommand/errorstream.go index e60dd7cdc7..90bb39b4a4 100644 --- a/tools/remotecommand/errorstream.go +++ b/tools/remotecommand/errorstream.go @@ -41,7 +41,7 @@ func watchErrorStream(errorStream io.Reader, d errorStreamDecoder) chan error { message, err := io.ReadAll(errorStream) switch { case err != nil && err != io.EOF: - errorChan <- fmt.Errorf("error reading from error stream: %s", err) + errorChan <- fmt.Errorf("error reading from error stream: %w", err) case len(message) > 0: errorChan <- d.decode(message) default: diff --git a/tools/remotecommand/fallback_test.go b/tools/remotecommand/fallback_test.go index b82c7bedf7..0cd775144d 100644 --- a/tools/remotecommand/fallback_test.go +++ b/tools/remotecommand/fallback_test.go @@ -49,7 +49,9 @@ func TestFallbackClient_WebSocketPrimarySucceeds(t *testing.T) { defer conns.conn.Close() // Loopback the STDIN stream onto the STDOUT stream. _, err = io.Copy(conns.stdoutStream, conns.stdinStream) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer websocketServer.Close() @@ -180,7 +182,9 @@ func TestFallbackClient_PrimaryAndSecondaryFail(t *testing.T) { defer conns.conn.Close() // Loopback the STDIN stream onto the STDOUT stream. _, err = io.Copy(conns.stdoutStream, conns.stdinStream) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + } })) defer websocketServer.Close() @@ -284,7 +288,7 @@ KR8NJEkK99Vh/tew6jAMll70xFrE7aF8VLXJVE7w4sQzuvHxl9Q= `) // See (https://github.com/kubernetes/kubernetes/issues/126134). -func TestFallbackClient_WebSocketHTTPSProxyCausesSPDYFallback(t *testing.T) { +func TestFallbackClient_WebSocketHTTPSProxyNoFallback(t *testing.T) { cert, err := tls.X509KeyPair(localhostCert, localhostKey) if err != nil { t.Errorf("https (valid hostname): proxy_test: %v", err) @@ -305,42 +309,40 @@ func TestFallbackClient_WebSocketHTTPSProxyCausesSPDYFallback(t *testing.T) { proxyLocation, err := url.Parse(proxyServer.URL) require.NoError(t, err) - // Create fake SPDY server. Copy received STDIN data back onto STDOUT stream. - spdyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var stdin, stdout bytes.Buffer - ctx, err := createHTTPStreams(w, req, &StreamOptions{ - Stdin: &stdin, - Stdout: &stdout, - }) + // Create fake WebSocket server. Copy received STDIN data back onto STDOUT stream. + websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + conns, err := webSocketServerStreams(req, w, streamOptionsFromRequest(req)) if err != nil { w.WriteHeader(http.StatusForbidden) return } - defer ctx.conn.Close() //nolint:errcheck - _, err = io.Copy(ctx.stdoutStream, ctx.stdinStream) + defer conns.conn.Close() //nolint:errcheck + // Loopback the STDIN stream onto the STDOUT stream. + _, err = io.Copy(conns.stdoutStream, conns.stdinStream) if err != nil { - t.Fatalf("error copying STDIN to STDOUT: %v", err) + t.Fatalf("websocket copy error: %v", err) } })) - defer spdyServer.Close() //nolint:errcheck + defer websocketServer.Close() //nolint:errcheck - backendLocation, err := url.Parse(spdyServer.URL) + // Now create the WebSocket client (executor), and point it to the TLS proxy server. + // The proxy server should open a websocket connection to the fake websocket server. + websocketServer.URL = websocketServer.URL + "?" + "stdin=true" + "&" + "stdout=true" + websocketLocation, err := url.Parse(websocketServer.URL) require.NoError(t, err) - clientConfig := &rest.Config{ - Host: spdyServer.URL, + Host: websocketLocation.Host, TLSClientConfig: rest.TLSClientConfig{CAData: localhostCert}, Proxy: func(req *http.Request) (*url.URL, error) { return proxyLocation, nil }, } - - // Websocket with https proxy will fail in dialing (falling back to SPDY). - websocketExecutor, err := NewWebSocketExecutor(clientConfig, "GET", backendLocation.String()) + websocketExecutor, err := NewWebSocketExecutor(clientConfig, "GET", websocketServer.URL) require.NoError(t, err) - spdyExecutor, err := NewSPDYExecutor(clientConfig, "POST", backendLocation) + emptyURL, _ := url.Parse("") + spdyExecutor, err := NewSPDYExecutor(clientConfig, "POST", emptyURL) require.NoError(t, err) - // Fallback to spdyExecutor with websocket https proxy error; spdyExecutor succeeds against fake spdy server. + // No fallback to spdyExecutor with websocket. sawHTTPSProxyError := false exec, err := NewFallbackExecutor(websocketExecutor, spdyExecutor, func(err error) bool { if httpstream.IsUpgradeFailure(err) { @@ -392,9 +394,9 @@ func TestFallbackClient_WebSocketHTTPSProxyCausesSPDYFallback(t *testing.T) { t.Errorf("unexpected data received: %d sent: %d", len(data), len(randomData)) } - // Ensure the https proxy error was observed - if !sawHTTPSProxyError { - t.Errorf("expected to see https proxy error") + // Ensure the https proxy error was *not* observed + if sawHTTPSProxyError { + t.Errorf("expected to *not* see https proxy error") } // Ensure the proxy was called once if e, a := int64(1), proxyCalled.Load(); e != a { diff --git a/tools/remotecommand/v2_test.go b/tools/remotecommand/v2_test.go index e303f57a9e..412cee8d2f 100644 --- a/tools/remotecommand/v2_test.go +++ b/tools/remotecommand/v2_test.go @@ -19,12 +19,13 @@ package remotecommand import ( "errors" "io" + "net" "net/http" "strings" "testing" "time" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/wait" ) @@ -181,17 +182,34 @@ func TestV2ErrorStreamReading(t *testing.T) { tests := []struct { name string stream io.Reader - expectedError error + expectedError func(*testing.T, error) }{ { - name: "error reading from stream", - stream: &fakeReader{errors.New("foo")}, - expectedError: errors.New("error reading from error stream: foo"), + name: "error reading from stream", + stream: &fakeReader{errors.New("foo")}, + expectedError: func(t *testing.T, err error) { + if e, a := "error reading from error stream: foo", err.Error(); e != a { + t.Errorf("expected '%s', got '%s'", e, a) + } + }, }, { - name: "stream returns an error", - stream: strings.NewReader("some error"), - expectedError: errors.New("error executing remote command: some error"), + name: "stream returns an error", + stream: strings.NewReader("some error"), + expectedError: func(t *testing.T, err error) { + if e, a := "error executing remote command: some error", err.Error(); e != a { + t.Errorf("expected '%s', got '%s'", e, a) + } + }, + }, + { + name: "typed error", + stream: &fakeReader{net.ErrClosed}, + expectedError: func(t *testing.T, err error) { + if !errors.Is(err, net.ErrClosed) { + t.Errorf("expected errors.Is(err, net.ErrClosed), failed on %#v", err) + } + }, }, } @@ -214,8 +232,8 @@ func TestV2ErrorStreamReading(t *testing.T) { if test.expectedError != nil { if err == nil { t.Errorf("%s: expected an error", test.name) - } else if e, a := test.expectedError, err; e.Error() != a.Error() { - t.Errorf("%s: expected %q, got %q", test.name, e, a) + } else { + test.expectedError(t, err) } continue } diff --git a/tools/remotecommand/websocket.go b/tools/remotecommand/websocket.go index 1dc679cb1f..cea26a0b55 100644 --- a/tools/remotecommand/websocket.go +++ b/tools/remotecommand/websocket.go @@ -248,6 +248,7 @@ func (c *wsStreamCreator) readDemuxLoop(bufferSize int, period time.Duration, de // Initialize and start the ping/pong heartbeat. h := newHeartbeat(c.conn, period, deadline) // Set initial timeout for websocket connection reading. + klog.V(5).Infof("Websocket initial read deadline: %s", deadline) if err := c.conn.SetReadDeadline(time.Now().Add(deadline)); err != nil { klog.Errorf("Websocket initial setting read deadline failed %v", err) return @@ -311,7 +312,7 @@ func (c *wsStreamCreator) readDemuxLoop(bufferSize int, period time.Duration, de if errRead == io.EOF { break } - c.closeAllStreamReaders(fmt.Errorf("read message: %w", err)) + c.closeAllStreamReaders(fmt.Errorf("read message: %w", errRead)) return } } @@ -354,8 +355,8 @@ func (s *stream) Read(p []byte) (n int, err error) { // Write writes directly to the underlying WebSocket connection. func (s *stream) Write(p []byte) (n int, err error) { - klog.V(4).Infof("Write() on stream %d", s.id) - defer klog.V(4).Infof("Write() done on stream %d", s.id) + klog.V(8).Infof("Write() on stream %d", s.id) + defer klog.V(8).Infof("Write() done on stream %d", s.id) s.connWriteLock.Lock() defer s.connWriteLock.Unlock() if s.conn == nil { @@ -363,7 +364,7 @@ func (s *stream) Write(p []byte) (n int, err error) { } err = s.conn.SetWriteDeadline(time.Now().Add(writeDeadline)) if err != nil { - klog.V(7).Infof("Websocket setting write deadline failed %v", err) + klog.V(4).Infof("Websocket setting write deadline failed %v", err) return 0, err } // Message writer buffers the message data, so we don't need to do that ourselves. @@ -392,8 +393,8 @@ func (s *stream) Write(p []byte) (n int, err error) { // Close half-closes the stream, indicating this side is finished with the stream. func (s *stream) Close() error { - klog.V(4).Infof("Close() on stream %d", s.id) - defer klog.V(4).Infof("Close() done on stream %d", s.id) + klog.V(6).Infof("Close() on stream %d", s.id) + defer klog.V(6).Infof("Close() done on stream %d", s.id) s.connWriteLock.Lock() defer s.connWriteLock.Unlock() if s.conn == nil { @@ -452,7 +453,7 @@ func newHeartbeat(conn *gwebsocket.Conn, period time.Duration, deadline time.Dur // be empty. h.conn.SetPongHandler(func(msg string) error { // Push the read deadline into the future. - klog.V(8).Infof("Pong message received (%s)--resetting read deadline", msg) + klog.V(6).Infof("Pong message received (%s)--resetting read deadline", msg) err := h.conn.SetReadDeadline(time.Now().Add(deadline)) if err != nil { klog.Errorf("Websocket setting read deadline failed %v", err) @@ -487,14 +488,14 @@ func (h *heartbeat) start() { for { select { case <-h.closer: - klog.V(8).Infof("closed channel--returning") + klog.V(5).Infof("closed channel--returning") return case <-t.C: // "WriteControl" does not need to be protected by a mutex. According to // gorilla/websockets library docs: "The Close and WriteControl methods can // be called concurrently with all other methods." if err := h.conn.WriteControl(gwebsocket.PingMessage, h.message, time.Now().Add(pingReadDeadline)); err == nil { - klog.V(8).Infof("Websocket Ping succeeeded") + klog.V(6).Infof("Websocket Ping succeeeded") } else { klog.Errorf("Websocket Ping failed: %v", err) if errors.Is(err, gwebsocket.ErrCloseSent) { diff --git a/tools/remotecommand/websocket_test.go b/tools/remotecommand/websocket_test.go index b70afcacbe..9f064d935f 100644 --- a/tools/remotecommand/websocket_test.go +++ b/tools/remotecommand/websocket_test.go @@ -20,6 +20,7 @@ import ( "bytes" "context" "crypto/rand" + "crypto/tls" "encoding/json" "fmt" "io" @@ -31,16 +32,18 @@ import ( "reflect" "strings" "sync" + "sync/atomic" "testing" "time" gwebsocket "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/httpstream/wsstream" + utilnettesting "k8s.io/apimachinery/pkg/util/net/testing" "k8s.io/apimachinery/pkg/util/remotecommand" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/rest" @@ -1342,38 +1345,110 @@ func createWebSocketStreams(req *http.Request, w http.ResponseWriter, opts *opti return wsStreams, nil } -// See (https://github.com/kubernetes/kubernetes/issues/126134). -func TestWebSocketClient_HTTPSProxyErrorExpected(t *testing.T) { - urlStr := "http://127.0.0.1/never-used" + "?" + "stdin=true" + "&" + "stdout=true" - websocketLocation, err := url.Parse(urlStr) - if err != nil { - t.Fatalf("Unable to parse WebSocket server URL: %s", urlStr) - } - // proxy url with https scheme will trigger websocket dialing error. - httpsProxyFunc := func(req *http.Request) (*url.URL, error) { return url.Parse("https://127.0.0.1") } - exec, err := NewWebSocketExecutor(&rest.Config{Host: websocketLocation.Host, Proxy: httpsProxyFunc}, "GET", urlStr) - if err != nil { - t.Errorf("unexpected error creating websocket executor: %v", err) - } - var stdout bytes.Buffer - options := &StreamOptions{ - Stdout: &stdout, - } - errorChan := make(chan error) - go func() { - // Start the streaming on the WebSocket "exec" client. - errorChan <- exec.StreamWithContext(context.Background(), *options) - }() +func TestWebSocketClient_ProxySucceeds(t *testing.T) { + // Validate websocket proxy succeeds for each of the enumerated schemes. + proxySchemes := []string{"http", "https"} + for _, proxyScheme := range proxySchemes { + // Create the proxy handler, keeping track of how many times it was called. + var proxyCalled atomic.Int64 + proxyHandler := utilnettesting.NewHTTPProxyHandler(t, func(req *http.Request) bool { + proxyCalled.Add(1) + return true + }) + defer proxyHandler.Wait() + // Create/Start the proxy server, adding TLS functionality depending on scheme. + proxyServer := httptest.NewUnstartedServer(proxyHandler) + if proxyScheme == "https" { + cert, err := tls.X509KeyPair(localhostCert, localhostKey) + if err != nil { + t.Errorf("https (valid hostname): proxy_test: %v", err) + } + proxyServer.TLS = &tls.Config{Certificates: []tls.Certificate{cert}} + proxyServer.StartTLS() + } else { + proxyServer.Start() + } + defer proxyServer.Close() //nolint:errcheck + proxyLocation, err := url.Parse(proxyServer.URL) + require.NoError(t, err) + t.Logf("Proxy URL: %s", proxyLocation.String()) - select { - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("expect stream to be closed after connection is closed.") - case err := <-errorChan: - if err == nil { - t.Errorf("expected error but received none") + // Create fake WebSocket server. Copy received STDIN data back onto STDOUT stream. + websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + conns, err := webSocketServerStreams(req, w, streamOptionsFromRequest(req)) + if err != nil { + t.Fatalf("error on webSocketServerStreams: %v", err) + } + defer conns.conn.Close() //nolint:errcheck + // Loopback the STDIN stream onto the STDOUT stream. + _, err = io.Copy(conns.stdoutStream, conns.stdinStream) + if err != nil { + t.Fatalf("error copying STDIN to STDOUT: %v", err) + } + })) + defer websocketServer.Close() //nolint:errcheck + + // Now create the WebSocket client (executor), and point it to the TLS proxy server. + // The proxy server should open a websocket connection to the fake websocket server. + websocketServer.URL = websocketServer.URL + "?" + "stdin=true" + "&" + "stdout=true" + websocketLocation, err := url.Parse(websocketServer.URL) + require.NoError(t, err) + clientConfig := &rest.Config{ + Host: websocketLocation.Host, + // Unused if "http" scheme. + TLSClientConfig: rest.TLSClientConfig{CAData: localhostCert}, + Proxy: func(req *http.Request) (*url.URL, error) { + return proxyLocation, nil + }, + } + exec, err := NewWebSocketExecutor(clientConfig, "GET", websocketServer.URL) + require.NoError(t, err) + + // Generate random data, and set it up to stream on STDIN. The data will be + // returned on the STDOUT buffer. + randomSize := 1024 * 1024 + randomData := make([]byte, randomSize) + if _, err := rand.Read(randomData); err != nil { + t.Errorf("unexpected error reading random data: %v", err) + } + var stdout bytes.Buffer + options := &StreamOptions{ + Stdin: bytes.NewReader(randomData), + Stdout: &stdout, + } + errorChan := make(chan error) + go func() { + // Start the streaming on the WebSocket "exec" client. + errorChan <- exec.StreamWithContext(context.Background(), *options) + }() + + select { + case <-time.After(wait.ForeverTestTimeout): + t.Fatalf("expect stream to be closed after connection is closed.") + case err := <-errorChan: + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + // Validate remote command v5 protocol was negotiated. + streamExec := exec.(*wsStreamExecutor) + if remotecommand.StreamProtocolV5Name != streamExec.negotiated { + t.Fatalf("expected remote command v5 protocol, got (%s)", streamExec.negotiated) + } + } + data, err := io.ReadAll(bytes.NewReader(stdout.Bytes())) + if err != nil { + t.Fatalf("error reading the stream: %v", err) + } + // Check the random data sent on STDIN was the same returned on STDOUT. + t.Logf("comparing %d random bytes sent data versus received", len(randomData)) + if !bytes.Equal(randomData, data) { + t.Errorf("unexpected data received: %d sent: %d", len(data), len(randomData)) + } else { + t.Log("success--random bytes are the same") } - if !httpstream.IsHTTPSProxyError(err) { - t.Errorf("expected https proxy error, got (%s)", err) + // Ensure the proxy was called once + if e, a := int64(1), proxyCalled.Load(); e != a { + t.Errorf("expected %d proxy call, got %d", e, a) } } } diff --git a/tools/watch/informerwatcher.go b/tools/watch/informerwatcher.go index 5e6aad5cf1..114abfcc9b 100644 --- a/tools/watch/informerwatcher.go +++ b/tools/watch/informerwatcher.go @@ -20,8 +20,10 @@ import ( "sync" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" + "k8s.io/klog/v2" ) func newEventProcessor(out chan<- watch.Event) *eventProcessor { @@ -103,7 +105,16 @@ func (e *eventProcessor) stop() { // NewIndexerInformerWatcher will create an IndexerInformer and wrap it into watch.Interface // so you can use it anywhere where you'd have used a regular Watcher returned from Watch method. // it also returns a channel you can use to wait for the informers to fully shutdown. +// +// Contextual logging: NewIndexerInformerWatcherWithLogger should be used instead of NewIndexerInformerWatcher in code which supports contextual logging. func NewIndexerInformerWatcher(lw cache.ListerWatcher, objType runtime.Object) (cache.Indexer, cache.Controller, watch.Interface, <-chan struct{}) { + return NewIndexerInformerWatcherWithLogger(klog.Background(), lw, objType) +} + +// NewIndexerInformerWatcherWithLogger will create an IndexerInformer and wrap it into watch.Interface +// so you can use it anywhere where you'd have used a regular Watcher returned from Watch method. +// it also returns a channel you can use to wait for the informers to fully shutdown. +func NewIndexerInformerWatcherWithLogger(logger klog.Logger, lw cache.ListerWatcher, objType runtime.Object) (cache.Indexer, cache.Controller, watch.Interface, <-chan struct{}) { ch := make(chan watch.Event) w := watch.NewProxyWatcher(ch) e := newEventProcessor(ch) @@ -137,13 +148,18 @@ func NewIndexerInformerWatcher(lw cache.ListerWatcher, objType runtime.Object) ( }, }, cache.Indexers{}) + // This will get stopped, but without waiting for it. go e.run() doneCh := make(chan struct{}) go func() { defer close(doneCh) defer e.stop() - informer.Run(w.StopChan()) + // Waiting for w.StopChan() is the traditional behavior which gets + // preserved here, with the logger added to support contextual logging. + ctx := wait.ContextForChannel(w.StopChan()) + ctx = klog.NewContext(ctx, logger) + informer.RunWithContext(ctx) }() return indexer, informer, w, doneCh diff --git a/tools/watch/informerwatcher_test.go b/tools/watch/informerwatcher_test.go index 1f8e16c2ec..e03f9612db 100644 --- a/tools/watch/informerwatcher_test.go +++ b/tools/watch/informerwatcher_test.go @@ -320,6 +320,7 @@ func TestNewInformerWatcher(t *testing.T) { return fake.CoreV1().Secrets("").Watch(context.TODO(), options) }, } + //nolint:logcheck // Intentionally uses the older API. _, _, outputWatcher, informerDoneCh := NewIndexerInformerWatcher(lw, &corev1.Secret{}) outputCh := outputWatcher.ResultChan() timeoutCh := time.After(wait.ForeverTestTimeout) @@ -413,6 +414,7 @@ func TestInformerWatcherDeletedFinalStateUnknown(t *testing.T) { return w, nil }, } + //nolint:logcheck // Intentionally uses the older API. _, _, w, done := NewIndexerInformerWatcher(lw, &corev1.Secret{}) defer w.Stop() diff --git a/tools/watch/retrywatcher.go b/tools/watch/retrywatcher.go index d36d7455d5..45249d8e47 100644 --- a/tools/watch/retrywatcher.go +++ b/tools/watch/retrywatcher.go @@ -22,7 +22,6 @@ import ( "fmt" "io" "net/http" - "sync" "time" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -48,23 +47,31 @@ type resourceVersionGetter interface { // Please note that this is not resilient to etcd cache not having the resource version anymore - you would need to // use Informers for that. type RetryWatcher struct { + cancel func(error) lastResourceVersion string - watcherClient cache.Watcher + watcherClient cache.WatcherWithContext resultChan chan watch.Event - stopChan chan struct{} doneChan chan struct{} minRestartDelay time.Duration - stopChanLock sync.Mutex } // NewRetryWatcher creates a new RetryWatcher. // It will make sure that watches gets restarted in case of recoverable errors. // The initialResourceVersion will be given to watch method when first called. +// +// Deprecated: use NewRetryWatcherWithContext instead. func NewRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher) (*RetryWatcher, error) { - return newRetryWatcher(initialResourceVersion, watcherClient, 1*time.Second) + return NewRetryWatcherWithContext(context.Background(), initialResourceVersion, cache.ToWatcherWithContext(watcherClient)) } -func newRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher, minRestartDelay time.Duration) (*RetryWatcher, error) { +// NewRetryWatcherWithContext creates a new RetryWatcher. +// It will make sure that watches gets restarted in case of recoverable errors. +// The initialResourceVersion will be given to watch method when first called. +func NewRetryWatcherWithContext(ctx context.Context, initialResourceVersion string, watcherClient cache.WatcherWithContext) (*RetryWatcher, error) { + return newRetryWatcher(ctx, initialResourceVersion, watcherClient, 1*time.Second) +} + +func newRetryWatcher(ctx context.Context, initialResourceVersion string, watcherClient cache.WatcherWithContext, minRestartDelay time.Duration) (*RetryWatcher, error) { switch initialResourceVersion { case "", "0": // TODO: revisit this if we ever get WATCH v2 where it means start "now" @@ -74,34 +81,36 @@ func newRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher, break } + ctx, cancel := context.WithCancelCause(ctx) + rw := &RetryWatcher{ + cancel: cancel, lastResourceVersion: initialResourceVersion, watcherClient: watcherClient, - stopChan: make(chan struct{}), doneChan: make(chan struct{}), resultChan: make(chan watch.Event, 0), minRestartDelay: minRestartDelay, } - go rw.receive() + go rw.receive(ctx) return rw, nil } -func (rw *RetryWatcher) send(event watch.Event) bool { +func (rw *RetryWatcher) send(ctx context.Context, event watch.Event) bool { // Writing to an unbuffered channel is blocking operation // and we need to check if stop wasn't requested while doing so. select { case rw.resultChan <- event: return true - case <-rw.stopChan: + case <-ctx.Done(): return false } } // doReceive returns true when it is done, false otherwise. // If it is not done the second return value holds the time to wait before calling it again. -func (rw *RetryWatcher) doReceive() (bool, time.Duration) { - watcher, err := rw.watcherClient.Watch(metav1.ListOptions{ +func (rw *RetryWatcher) doReceive(ctx context.Context) (bool, time.Duration) { + watcher, err := rw.watcherClient.WatchWithContext(ctx, metav1.ListOptions{ ResourceVersion: rw.lastResourceVersion, AllowWatchBookmarks: true, }) @@ -117,13 +126,13 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { return false, 0 case io.ErrUnexpectedEOF: - klog.V(1).InfoS("Watch closed with unexpected EOF", "err", err) + klog.FromContext(ctx).V(1).Info("Watch closed with unexpected EOF", "err", err) return false, 0 default: msg := "Watch failed" if net.IsProbableEOF(err) || net.IsTimeout(err) { - klog.V(5).InfoS(msg, "err", err) + klog.FromContext(ctx).V(5).Info(msg, "err", err) // Retry return false, 0 } @@ -132,38 +141,38 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { // being invalid (e.g. expired token). if apierrors.IsForbidden(err) || apierrors.IsUnauthorized(err) { // Add more detail since the forbidden message returned by the Kubernetes API is just "unknown". - klog.ErrorS(err, msg+": ensure the client has valid credentials and watch permissions on the resource") + klog.FromContext(ctx).Error(err, msg+": ensure the client has valid credentials and watch permissions on the resource") if apiStatus, ok := err.(apierrors.APIStatus); ok { statusErr := apiStatus.Status() - sent := rw.send(watch.Event{ + sent := rw.send(ctx, watch.Event{ Type: watch.Error, Object: &statusErr, }) if !sent { // This likely means the RetryWatcher is stopping but return false so the caller to doReceive can // verify this and potentially retry. - klog.Error("Failed to send the Unauthorized or Forbidden watch event") + klog.FromContext(ctx).Error(nil, "Failed to send the Unauthorized or Forbidden watch event") return false, 0 } } else { // This should never happen since apierrors only handles apierrors.APIStatus. Still, this is an // unrecoverable error, so still allow it to return true below. - klog.ErrorS(err, msg+": encountered an unexpected Unauthorized or Forbidden error type") + klog.FromContext(ctx).Error(err, msg+": encountered an unexpected Unauthorized or Forbidden error type") } return true, 0 } - klog.ErrorS(err, msg) + klog.FromContext(ctx).Error(err, msg) // Retry return false, 0 } if watcher == nil { - klog.ErrorS(nil, "Watch returned nil watcher") + klog.FromContext(ctx).Error(nil, "Watch returned nil watcher") // Retry return false, 0 } @@ -173,12 +182,12 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { for { select { - case <-rw.stopChan: - klog.V(4).InfoS("Stopping RetryWatcher.") + case <-ctx.Done(): + klog.FromContext(ctx).V(4).Info("Stopping RetryWatcher") return true, 0 case event, ok := <-ch: if !ok { - klog.V(4).InfoS("Failed to get event! Re-creating the watcher.", "resourceVersion", rw.lastResourceVersion) + klog.FromContext(ctx).V(4).Info("Failed to get event - re-creating the watcher", "resourceVersion", rw.lastResourceVersion) return false, 0 } @@ -187,7 +196,7 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { case watch.Added, watch.Modified, watch.Deleted, watch.Bookmark: metaObject, ok := event.Object.(resourceVersionGetter) if !ok { - _ = rw.send(watch.Event{ + _ = rw.send(ctx, watch.Event{ Type: watch.Error, Object: &apierrors.NewInternalError(errors.New("retryWatcher: doesn't support resourceVersion")).ErrStatus, }) @@ -197,7 +206,7 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { resourceVersion := metaObject.GetResourceVersion() if resourceVersion == "" { - _ = rw.send(watch.Event{ + _ = rw.send(ctx, watch.Event{ Type: watch.Error, Object: &apierrors.NewInternalError(fmt.Errorf("retryWatcher: object %#v doesn't support resourceVersion", event.Object)).ErrStatus, }) @@ -207,7 +216,7 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { // All is fine; send the non-bookmark events and update resource version. if event.Type != watch.Bookmark { - ok = rw.send(event) + ok = rw.send(ctx, event) if !ok { return true, 0 } @@ -221,7 +230,7 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { errObject := apierrors.FromObject(event.Object) statusErr, ok := errObject.(*apierrors.StatusError) if !ok { - klog.Error(fmt.Sprintf("Received an error which is not *metav1.Status but %s", dump.Pretty(event.Object))) + klog.FromContext(ctx).Error(nil, "Received an error which is not *metav1.Status", "errorObject", dump.Pretty(event.Object)) // Retry unknown errors return false, 0 } @@ -236,7 +245,7 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { switch status.Code { case http.StatusGone: // Never retry RV too old errors - _ = rw.send(event) + _ = rw.send(ctx, event) return true, 0 case http.StatusGatewayTimeout, http.StatusInternalServerError: @@ -250,15 +259,15 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { // Log here so we have a record of hitting the unexpected error // and we can whitelist some error codes if we missed any that are expected. - klog.V(5).Info(fmt.Sprintf("Retrying after unexpected error: %s", dump.Pretty(event.Object))) + klog.FromContext(ctx).V(5).Info("Retrying after unexpected error", "errorObject", dump.Pretty(event.Object)) // Retry return false, statusDelay } default: - klog.Errorf("Failed to recognize Event type %q", event.Type) - _ = rw.send(watch.Event{ + klog.FromContext(ctx).Error(nil, "Failed to recognize event", "type", event.Type) + _ = rw.send(ctx, watch.Event{ Type: watch.Error, Object: &apierrors.NewInternalError(fmt.Errorf("retryWatcher failed to recognize Event type %q", event.Type)).ErrStatus, }) @@ -270,29 +279,21 @@ func (rw *RetryWatcher) doReceive() (bool, time.Duration) { } // receive reads the result from a watcher, restarting it if necessary. -func (rw *RetryWatcher) receive() { +func (rw *RetryWatcher) receive(ctx context.Context) { defer close(rw.doneChan) defer close(rw.resultChan) - klog.V(4).Info("Starting RetryWatcher.") - defer klog.V(4).Info("Stopping RetryWatcher.") + logger := klog.FromContext(ctx) + logger.V(4).Info("Starting RetryWatcher") + defer logger.V(4).Info("Stopping RetryWatcher") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(ctx) defer cancel() - go func() { - select { - case <-rw.stopChan: - cancel() - return - case <-ctx.Done(): - return - } - }() // We use non sliding until so we don't introduce delays on happy path when WATCH call // timeouts or gets closed and we need to reestablish it while also avoiding hot loops. wait.NonSlidingUntilWithContext(ctx, func(ctx context.Context) { - done, retryAfter := rw.doReceive() + done, retryAfter := rw.doReceive(ctx) if done { cancel() return @@ -306,7 +307,7 @@ func (rw *RetryWatcher) receive() { case <-timer.C: } - klog.V(4).Infof("Restarting RetryWatcher at RV=%q", rw.lastResourceVersion) + logger.V(4).Info("Restarting RetryWatcher", "resourceVersion", rw.lastResourceVersion) }, rw.minRestartDelay) } @@ -317,15 +318,7 @@ func (rw *RetryWatcher) ResultChan() <-chan watch.Event { // Stop implements Interface. func (rw *RetryWatcher) Stop() { - rw.stopChanLock.Lock() - defer rw.stopChanLock.Unlock() - - // Prevent closing an already closed channel to prevent a panic - select { - case <-rw.stopChan: - default: - close(rw.stopChan) - } + rw.cancel(errors.New("asked to stop")) } // Done allows the caller to be notified when Retry watcher stops. diff --git a/tools/watch/retrywatcher_test.go b/tools/watch/retrywatcher_test.go index 873ce37e6b..307b8da333 100644 --- a/tools/watch/retrywatcher_test.go +++ b/tools/watch/retrywatcher_test.go @@ -37,6 +37,7 @@ import ( "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" "k8s.io/klog/v2" + "k8s.io/klog/v2/ktesting" ) func init() { @@ -54,7 +55,7 @@ func (o testObject) GetObjectKind() schema.ObjectKind { return schema.EmptyObjec func (o testObject) DeepCopyObject() runtime.Object { return o } func (o testObject) GetResourceVersion() string { return o.resourceVersion } -func withCounter(w cache.Watcher) (*uint32, cache.Watcher) { +func withCounter(w cache.Watcher) (*uint32, cache.WatcherWithContext) { var counter uint32 return &counter, &cache.ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { @@ -549,10 +550,11 @@ func TestRetryWatcher(t *testing.T) { for _, tc := range tt { tc := tc t.Run(tc.name, func(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) t.Parallel() atomicCounter, watchFunc := withCounter(tc.watchClient) - watcher, err := newRetryWatcher(tc.initialRV, watchFunc, time.Duration(0)) + watcher, err := newRetryWatcher(ctx, tc.initialRV, watchFunc, time.Duration(0)) if err != nil { t.Fatalf("failed to create a RetryWatcher: %v", err) } diff --git a/tools/watch/until.go b/tools/watch/until.go index a2474556b0..03ceaf002d 100644 --- a/tools/watch/until.go +++ b/tools/watch/until.go @@ -105,7 +105,7 @@ func UntilWithoutRetry(ctx context.Context, watcher watch.Interface, conditions // // The most frequent usage for Until would be a test where you want to verify exact order of events ("edges"). func Until(ctx context.Context, initialResourceVersion string, watcherClient cache.Watcher, conditions ...ConditionFunc) (*watch.Event, error) { - w, err := NewRetryWatcher(initialResourceVersion, watcherClient) + w, err := NewRetryWatcherWithContext(ctx, initialResourceVersion, cache.ToWatcherWithContext(watcherClient)) if err != nil { return nil, err } @@ -126,7 +126,7 @@ func Until(ctx context.Context, initialResourceVersion string, watcherClient cac // The most frequent usage would be a command that needs to watch the "state of the world" and should't fail, like: // waiting for object reaching a state, "small" controllers, ... func UntilWithSync(ctx context.Context, lw cache.ListerWatcher, objType runtime.Object, precondition PreconditionFunc, conditions ...ConditionFunc) (*watch.Event, error) { - indexer, informer, watcher, done := NewIndexerInformerWatcher(lw, objType) + indexer, informer, watcher, done := NewIndexerInformerWatcherWithLogger(klog.FromContext(ctx), lw, objType) // We need to wait for the internal informers to fully stop so it's easier to reason about // and it works with non-thread safe clients. defer func() { <-done }() @@ -156,7 +156,7 @@ func UntilWithSync(ctx context.Context, lw cache.ListerWatcher, objType runtime. func ContextWithOptionalTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) { if timeout < 0 { // This should be handled in validation - klog.Errorf("Timeout for context shall not be negative!") + klog.FromContext(parent).Error(nil, "Timeout for context shall not be negative") timeout = 0 } diff --git a/transport/cache.go b/transport/cache.go index 7c7f1b330f..b8dd866119 100644 --- a/transport/cache.go +++ b/transport/cache.go @@ -28,6 +28,7 @@ import ( utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/tools/metrics" + "k8s.io/klog/v2" ) // TlsTransportCache caches TLS http.RoundTrippers different configurations. The @@ -116,10 +117,13 @@ func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error) { // If we use are reloading files, we need to handle certificate rotation properly // TODO(jackkleeman): We can also add rotation here when config.HasCertCallback() is true if config.TLS.ReloadTLSFiles && tlsConfig != nil && tlsConfig.GetClientCertificate != nil { - dynamicCertDialer := certRotatingDialer(tlsConfig.GetClientCertificate, dial) + // The TLS cache is a singleton, so sharing the same name for all of its + // background activity seems okay. + logger := klog.Background().WithName("tls-transport-cache") + dynamicCertDialer := certRotatingDialer(logger, tlsConfig.GetClientCertificate, dial) tlsConfig.GetClientCertificate = dynamicCertDialer.GetClientCertificate dial = dynamicCertDialer.connDialer.DialContext - go dynamicCertDialer.Run(DialerStopCh) + go dynamicCertDialer.run(DialerStopCh) } proxy := http.ProxyFromEnvironment diff --git a/transport/cert_rotation.go b/transport/cert_rotation.go index e76f65812d..e343f42be4 100644 --- a/transport/cert_rotation.go +++ b/transport/cert_rotation.go @@ -19,7 +19,6 @@ package transport import ( "bytes" "crypto/tls" - "fmt" "reflect" "sync" "time" @@ -40,6 +39,7 @@ var CertCallbackRefreshDuration = 5 * time.Minute type reloadFunc func(*tls.CertificateRequestInfo) (*tls.Certificate, error) type dynamicClientCert struct { + logger klog.Logger clientCert *tls.Certificate certMtx sync.RWMutex @@ -50,8 +50,9 @@ type dynamicClientCert struct { queue workqueue.TypedRateLimitingInterface[string] } -func certRotatingDialer(reload reloadFunc, dial utilnet.DialFunc) *dynamicClientCert { +func certRotatingDialer(logger klog.Logger, reload reloadFunc, dial utilnet.DialFunc) *dynamicClientCert { d := &dynamicClientCert{ + logger: logger, reload: reload, connDialer: connrotation.NewDialer(connrotation.DialFunc(dial)), queue: workqueue.NewTypedRateLimitingQueueWithConfig( @@ -88,7 +89,7 @@ func (c *dynamicClientCert) loadClientCert() (*tls.Certificate, error) { return cert, nil } - klog.V(1).Infof("certificate rotation detected, shutting down client connections to start using new credentials") + c.logger.V(1).Info("Certificate rotation detected, shutting down client connections to start using new credentials") c.connDialer.CloseAll() return cert, nil @@ -133,12 +134,12 @@ func byteMatrixEqual(left, right [][]byte) bool { } // run starts the controller and blocks until stopCh is closed. -func (c *dynamicClientCert) Run(stopCh <-chan struct{}) { - defer utilruntime.HandleCrash() +func (c *dynamicClientCert) run(stopCh <-chan struct{}) { + defer utilruntime.HandleCrashWithLogger(c.logger) defer c.queue.ShutDown() - klog.V(3).Infof("Starting client certificate rotation controller") - defer klog.V(3).Infof("Shutting down client certificate rotation controller") + c.logger.V(3).Info("Starting client certificate rotation controller") + defer c.logger.V(3).Info("Shutting down client certificate rotation controller") go wait.Until(c.runWorker, time.Second, stopCh) @@ -168,7 +169,7 @@ func (c *dynamicClientCert) processNextWorkItem() bool { return true } - utilruntime.HandleError(fmt.Errorf("%v failed with : %v", dsKey, err)) + utilruntime.HandleErrorWithLogger(c.logger, err, "Loading client cert failed", "key", dsKey) c.queue.AddRateLimited(dsKey) return true diff --git a/transport/round_trippers.go b/transport/round_trippers.go index 52fefb5316..39fcebd941 100644 --- a/transport/round_trippers.go +++ b/transport/round_trippers.go @@ -21,10 +21,12 @@ import ( "fmt" "net/http" "net/http/httptrace" + "sort" "strings" "sync" "time" + "github.com/go-logr/logr" "golang.org/x/oauth2" utilnet "k8s.io/apimachinery/pkg/util/net" @@ -68,19 +70,16 @@ func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTrip return rt, nil } -// DebugWrappers wraps a round tripper and logs based on the current log level. +// DebugWrappers potentially wraps a round tripper with a wrapper that logs +// based on the log level in the context of each individual request. +// +// At the moment, wrapping depends on the global log verbosity and is done +// if that verbosity is >= 6. This may change in the future. func DebugWrappers(rt http.RoundTripper) http.RoundTripper { - switch { - case bool(klog.V(9).Enabled()): - rt = NewDebuggingRoundTripper(rt, DebugCurlCommand, DebugURLTiming, DebugDetailedTiming, DebugResponseHeaders) - case bool(klog.V(8).Enabled()): - rt = NewDebuggingRoundTripper(rt, DebugJustURL, DebugRequestHeaders, DebugResponseStatus, DebugResponseHeaders) - case bool(klog.V(7).Enabled()): - rt = NewDebuggingRoundTripper(rt, DebugJustURL, DebugRequestHeaders, DebugResponseStatus) - case bool(klog.V(6).Enabled()): - rt = NewDebuggingRoundTripper(rt, DebugURLTiming) + //nolint:logcheck // The actual logging is done with a different logger, so only checking here is okay. + if klog.V(6).Enabled() { + rt = NewDebuggingRoundTripper(rt, DebugByContext) } - return rt } @@ -380,14 +379,17 @@ func (r *requestInfo) toCurl() string { } } - return fmt.Sprintf("curl -v -X%s %s '%s'", r.RequestVerb, headers, r.RequestURL) + // Newline at the end makes this look better in the text log output (the + // only usage of this method) because it becomes a multi-line string with + // no quoting. + return fmt.Sprintf("curl -v -X%s %s '%s'\n", r.RequestVerb, headers, r.RequestURL) } // debuggingRoundTripper will display information about the requests passing // through it based on what is configured type debuggingRoundTripper struct { delegatedRoundTripper http.RoundTripper - levels map[DebugLevel]bool + levels int } var _ utilnet.RoundTripperWrapper = &debuggingRoundTripper{} @@ -412,6 +414,26 @@ const ( DebugResponseHeaders // DebugDetailedTiming will add to the debug output the duration of the HTTP requests events. DebugDetailedTiming + // DebugByContext will add any of the above depending on the verbosity of the per-request logger obtained from the requests context. + // + // Can be combined in NewDebuggingRoundTripper with some of the other options, in which case the + // debug roundtripper will always log what is requested there plus the information that gets + // enabled by the context's log verbosity. + DebugByContext +) + +// Different log levels include different sets of information. +// +// Not exported because the exact content of log messages is not part +// of of the package API. +const ( + levelsV6 = (1 << DebugURLTiming) + // Logging *less* information for the response at level 7 compared to 6 replicates prior behavior: + // https://github.com/kubernetes/kubernetes/blob/2b472fe4690c83a2b343995f88050b2a3e9ff0fa/staging/src/k8s.io/client-go/transport/round_trippers.go#L79 + // Presumably that was done because verb and URL are already in the request log entry. + levelsV7 = (1 << DebugJustURL) | (1 << DebugRequestHeaders) | (1 << DebugResponseStatus) + levelsV8 = (1 << DebugJustURL) | (1 << DebugRequestHeaders) | (1 << DebugResponseStatus) | (1 << DebugResponseHeaders) + levelsV9 = (1 << DebugCurlCommand) | (1 << DebugURLTiming) | (1 << DebugDetailedTiming) | (1 << DebugResponseHeaders) ) // NewDebuggingRoundTripper allows to display in the logs output debug information @@ -419,10 +441,9 @@ const ( func NewDebuggingRoundTripper(rt http.RoundTripper, levels ...DebugLevel) http.RoundTripper { drt := &debuggingRoundTripper{ delegatedRoundTripper: rt, - levels: make(map[DebugLevel]bool, len(levels)), } for _, v := range levels { - drt.levels[v] = true + drt.levels |= 1 << v } return drt } @@ -464,27 +485,51 @@ func maskValue(key string, value string) string { } func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + logger := klog.FromContext(req.Context()) + levels := rt.levels + + // When logging depends on the context, it uses the verbosity of the per-context logger + // and a hard-coded mapping of verbosity to debug details. Otherwise all messages + // are logged as V(0). + if levels&(1< 0 { + logger.Info("Request", kvs...) } startTime := time.Now() - if rt.levels[DebugDetailedTiming] { + if levels&(1< 0 { + logger.Info("Response", kvs...) + } + + return response, err +} - if rt.levels[DebugResponseStatus] { - klog.Infof("Response Status: %s in %d milliseconds", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond)) +// headerMap formats headers sorted and across multiple lines with no quoting +// when using string output and as JSON when using zapr. +type headersMap http.Header + +// newHeadersMap masks all sensitive values. This has to be done before +// passing the map to a logger because while in practice all loggers +// either use String or MarshalLog, that is not guaranteed. +func newHeadersMap(header http.Header) headersMap { + h := make(headersMap, len(header)) + for key, values := range header { + maskedValues := make([]string, 0, len(values)) + for _, value := range values { + maskedValues = append(maskedValues, maskValue(key, value)) + } + h[key] = maskedValues } - if rt.levels[DebugResponseHeaders] { - klog.Info("Response Headers:") - for key, values := range reqInfo.ResponseHeaders { - for _, value := range values { - klog.Infof(" %s: %s", key, value) - } + return h +} + +var _ fmt.Stringer = headersMap{} +var _ logr.Marshaler = headersMap{} + +func (h headersMap) String() string { + // The fixed size typically avoids memory allocations when it is large enough. + keys := make([]string, 0, 20) + for key := range h { + keys = append(keys, key) + } + sort.Strings(keys) + var buffer strings.Builder + for _, key := range keys { + for _, value := range h[key] { + _, _ = buffer.WriteString(key) + _, _ = buffer.WriteString(": ") + _, _ = buffer.WriteString(value) + _, _ = buffer.WriteString("\n") } } + return buffer.String() +} - return response, err +func (h headersMap) MarshalLog() any { + return map[string][]string(h) } func (rt *debuggingRoundTripper) WrappedRoundTripper() http.RoundTripper { diff --git a/transport/round_trippers_test.go b/transport/round_trippers_test.go index 1e20f7094c..7ccfc3a635 100644 --- a/transport/round_trippers_test.go +++ b/transport/round_trippers_test.go @@ -18,13 +18,18 @@ package transport import ( "bytes" + "context" + "flag" "fmt" "net/http" "net/url" "reflect" + "regexp" "strings" "testing" + "github.com/go-logr/logr/funcr" + "k8s.io/klog/v2" ) @@ -460,101 +465,224 @@ func TestHeaderEscapeRoundTrip(t *testing.T) { } } +//nolint:logcheck // Intentionally tests with global logging. func TestDebuggingRoundTripper(t *testing.T) { - t.Parallel() - rawURL := "https://127.0.0.1:12345/api/v1/pods?limit=500" - req := &http.Request{ - Method: http.MethodGet, - Header: map[string][]string{ - "Authorization": {"bearer secretauthtoken"}, - "X-Test-Request": {"test"}, - }, + parsedURL, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q) returned error: %v", rawURL, err) + } + method := http.MethodGet + header := map[string][]string{ + "Authorization": {"bearer secretauthtoken"}, + "X-Test-Request": {"test"}, } + reqHeaderText := `headers=< + Authorization: bearer + X-Test-Request: test + >` + // Both can be written by funcr. + reqHeaderJSON := `"headers":{"Authorization":["bearer "],"X-Test-Request":["test"]}` + reqHeaderJSONReversed := `"headers":{"X-Test-Request":["test"],"Authorization":["bearer "]}` + res := &http.Response{ Status: "OK", StatusCode: http.StatusOK, Header: map[string][]string{ - "X-Test-Response": {"test"}, + "X-Test-Response": {"a", "b"}, }, } + + resHeaderText := `headers=< + X-Test-Response: a + X-Test-Response: b + >` + resHeaderJSON := `"headers":{"X-Test-Response":["a","b"]}` + tcs := []struct { - levels []DebugLevel - expectedOutputLines []string + levels []DebugLevel + v int + expectedTextLines []string + expectedJSONLines []string }{ { - levels: []DebugLevel{DebugJustURL}, - expectedOutputLines: []string{fmt.Sprintf("%s %s", req.Method, rawURL)}, + levels: []DebugLevel{DebugJustURL}, + expectedTextLines: []string{fmt.Sprintf(`"Request" verb=%q url=%q`, method, rawURL)}, + expectedJSONLines: []string{fmt.Sprintf(`"msg":"Request","verb":%q,"url":%q`, method, rawURL)}, }, { - levels: []DebugLevel{DebugRequestHeaders}, - expectedOutputLines: func() []string { - lines := []string{fmt.Sprintf("Request Headers:\n")} - for key, values := range req.Header { - for _, value := range values { - if key == "Authorization" { - value = "bearer " - } - lines = append(lines, fmt.Sprintf(" %s: %s\n", key, value)) - } - } - return lines - }(), + levels: []DebugLevel{DebugRequestHeaders}, + expectedTextLines: []string{`"Request" ` + reqHeaderText}, + expectedJSONLines: []string{`"msg":"Request",` + reqHeaderJSON}, }, { - levels: []DebugLevel{DebugResponseHeaders}, - expectedOutputLines: func() []string { - lines := []string{fmt.Sprintf("Response Headers:\n")} - for key, values := range res.Header { - for _, value := range values { - lines = append(lines, fmt.Sprintf(" %s: %s\n", key, value)) - } - } - return lines - }(), + levels: []DebugLevel{DebugResponseHeaders}, + expectedTextLines: []string{`"Response" ` + resHeaderText}, + expectedJSONLines: []string{`"msg":"Response",` + resHeaderJSON}, + }, + { + levels: []DebugLevel{DebugURLTiming}, + expectedTextLines: []string{fmt.Sprintf(`"Response" verb=%q url=%q status=%q`, method, rawURL, res.Status)}, + expectedJSONLines: []string{fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q`, method, rawURL, res.Status)}, + }, + { + levels: []DebugLevel{DebugResponseStatus}, + expectedTextLines: []string{fmt.Sprintf(`"Response" status=%q`, res.Status)}, + expectedJSONLines: []string{fmt.Sprintf(`"msg":"Response","status":%q`, res.Status)}, + }, + { + levels: []DebugLevel{DebugCurlCommand}, + expectedTextLines: []string{`curlCommand=< + curl -v -X`}, + expectedJSONLines: []string{`"curlCommand":"curl -v -X`}, + }, + { + levels: []DebugLevel{DebugURLTiming, DebugResponseStatus}, + expectedTextLines: []string{fmt.Sprintf(`"Response" verb=%q url=%q status=%q milliseconds=`, method, rawURL, res.Status)}, + expectedJSONLines: []string{fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,"milliseconds":`, method, rawURL, res.Status)}, + }, + { + levels: []DebugLevel{DebugByContext}, + v: 5, + }, + { + levels: []DebugLevel{DebugByContext, DebugURLTiming}, + v: 5, + expectedTextLines: []string{ + fmt.Sprintf(`"Response" verb=%q url=%q status=%q milliseconds=`, method, rawURL, res.Status), + }, + expectedJSONLines: []string{ + fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,"milliseconds":`, method, rawURL, res.Status), + }, + }, + { + levels: []DebugLevel{DebugByContext}, + v: 6, + expectedTextLines: []string{ + fmt.Sprintf(`"Response" verb=%q url=%q status=%q milliseconds=`, method, rawURL, res.Status), + }, + expectedJSONLines: []string{ + fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,"milliseconds":`, method, rawURL, res.Status), + }, }, { - levels: []DebugLevel{DebugURLTiming}, - expectedOutputLines: []string{fmt.Sprintf("%s %s %s", req.Method, rawURL, res.Status)}, + levels: []DebugLevel{DebugByContext}, + v: 7, + expectedTextLines: []string{ + fmt.Sprintf(`"Request" verb=%q url=%q %s +`, method, rawURL, reqHeaderText), + fmt.Sprintf(`"Response" status=%q milliseconds=`, res.Status), + }, + expectedJSONLines: []string{ + fmt.Sprintf(`"msg":"Request","verb":%q,"url":%q,%s`, method, rawURL, reqHeaderJSON), + fmt.Sprintf(`"msg":"Response","status":%q,"milliseconds":`, res.Status), + }, }, { - levels: []DebugLevel{DebugResponseStatus}, - expectedOutputLines: []string{fmt.Sprintf("Response Status: %s", res.Status)}, + levels: []DebugLevel{DebugByContext}, + v: 8, + expectedTextLines: []string{ + fmt.Sprintf(`"Request" verb=%q url=%q %s +`, method, rawURL, reqHeaderText), + fmt.Sprintf(`"Response" status=%q %s milliseconds=`, res.Status, resHeaderText), + }, + expectedJSONLines: []string{ + fmt.Sprintf(`"msg":"Request","verb":%q,"url":%q,%s`, method, rawURL, reqHeaderJSON), + fmt.Sprintf(`"msg":"Response","status":%q,%s,"milliseconds":`, res.Status, resHeaderJSON), + }, }, { - levels: []DebugLevel{DebugCurlCommand}, - expectedOutputLines: []string{fmt.Sprintf("curl -v -X")}, + levels: []DebugLevel{DebugByContext}, + v: 9, + expectedTextLines: []string{ + fmt.Sprintf(`"Request" curlCommand=< + curl -v -X%s`, method), + fmt.Sprintf(`"Response" verb=%q url=%q status=%q %s milliseconds=`, method, rawURL, res.Status, resHeaderText), + }, + expectedJSONLines: []string{ + fmt.Sprintf(`"msg":"Request","curlCommand":"curl -v -X%s`, method), + fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,%s,"milliseconds":`, method, rawURL, res.Status, resHeaderJSON), + }, }, } - for _, tc := range tcs { - // hijack the klog output - tmpWriteBuffer := bytes.NewBuffer(nil) - klog.SetOutput(tmpWriteBuffer) - klog.LogToStderr(false) - - // parse rawURL - parsedURL, err := url.Parse(rawURL) - if err != nil { - t.Fatalf("url.Parse(%q) returned error: %v", rawURL, err) - } - req.URL = parsedURL + for i, tc := range tcs { + t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { + for _, format := range []string{"text", "JSON"} { + t.Run(format, func(t *testing.T) { + // hijack the klog output + state := klog.CaptureState() + tmpWriteBuffer := bytes.NewBuffer(nil) + klog.SetOutput(tmpWriteBuffer) + klog.LogToStderr(false) + var fs flag.FlagSet + klog.InitFlags(&fs) + if err := fs.Set("one_output", "true"); err != nil { + t.Errorf("unexpected error setting -one_output: %v", err) + } + if err := fs.Set("v", fmt.Sprintf("%d", tc.v)); err != nil { + t.Errorf("unexpected error setting -v: %v", err) + } - // execute the round tripper - rt := &testRoundTripper{ - Response: res, - } - NewDebuggingRoundTripper(rt, tc.levels...).RoundTrip(req) + expectOutput := tc.expectedTextLines + var req *http.Request + if format == "JSON" { + // Logger will be picked up through the context. + logger := funcr.NewJSON(func(obj string) { + _, _ = tmpWriteBuffer.Write([]byte(obj)) + _, _ = tmpWriteBuffer.Write([]byte("\n")) + }, funcr.Options{Verbosity: tc.v}) + ctx := klog.NewContext(context.Background(), logger) + expectOutput = tc.expectedJSONLines + r, err := http.NewRequestWithContext(ctx, method, rawURL, nil) + if err != nil { + t.Fatalf("unexpected error constructing the HTTP request: %v", err) + } + req = r + } else { + // Intentionally no context, as before. + req = &http.Request{ + Method: method, + URL: parsedURL, + } + } + req.Header = header + + // execute the round tripper + rt := &testRoundTripper{ + Response: res, + } + if len(tc.levels) == 1 && tc.levels[0] == DebugByContext { + DebugWrappers(rt).RoundTrip(req) + } else { + NewDebuggingRoundTripper(rt, tc.levels...).RoundTrip(req) + } + + // call Flush to ensure the text isn't still buffered + klog.Flush() - // call Flush to ensure the text isn't still buffered - klog.Flush() + // check if klog's output contains the expected lines + actual := tmpWriteBuffer.String() - // check if klog's output contains the expected lines - actual := tmpWriteBuffer.String() - for _, expected := range tc.expectedOutputLines { - if !strings.Contains(actual, expected) { - t.Errorf("%q does not contain expected output %q", actual, expected) + // funcr writes a map in non-deterministic order. + // Fix that up before comparison. + actual = strings.ReplaceAll(actual, reqHeaderJSONReversed, reqHeaderJSON) + + for _, expected := range expectOutput { + if !strings.Contains(actual, expected) { + t.Errorf("verbosity %d: expected this substring:\n%s\n\ngot:\n%s", tc.v, expected, actual) + } + } + // These test cases describe all expected lines. Split the log output + // into log entries and compare their number. + entries := regexp.MustCompile(`(?m)^[I{]`).FindAllStringIndex(actual, -1) + if tc.v > 0 && len(entries) != len(expectOutput) { + t.Errorf("expected %d output lines, got %d:\n%s", len(expectOutput), len(entries), actual) + } + + state.Restore() + }) } - } + }) } } diff --git a/transport/token_source.go b/transport/token_source.go index 8e312800f7..469dd81765 100644 --- a/transport/token_source.go +++ b/transport/token_source.go @@ -182,7 +182,10 @@ func (ts *cachingTokenSource) Token() (*oauth2.Token, error) { if ts.tok == nil { return nil, err } - klog.Errorf("Unable to rotate token: %v", err) + // Not using a caller-provided logger isn't ideal, but impossible to fix + // without new APIs that go up all the way to HTTPWrappersForConfig. + // This is currently deemed not worth changing (too much effort, not enough benefit). + klog.TODO().Error(err, "Unable to rotate token") return ts.tok, nil } diff --git a/transport/transport.go b/transport/transport.go index 4770331a0e..8fdcc5700b 100644 --- a/transport/transport.go +++ b/transport/transport.go @@ -353,7 +353,7 @@ func tryCancelRequest(rt http.RoundTripper, req *http.Request) { case utilnet.RoundTripperWrapper: tryCancelRequest(rt.WrappedRoundTripper(), req) default: - klog.Warningf("Unable to cancel request for %T", rt) + klog.FromContext(req.Context()).Info("Warning: unable to cancel request", "roundTripperType", fmt.Sprintf("%T", rt)) } } diff --git a/transport/websocket/roundtripper_test.go b/transport/websocket/roundtripper_test.go index 6c71b97976..903dd0c0c8 100644 --- a/transport/websocket/roundtripper_test.go +++ b/transport/websocket/roundtripper_test.go @@ -113,12 +113,21 @@ func TestWebSocketRoundTripper_RoundTripperFails(t *testing.T) { } if testCase.status != nil { statusBytes, err := runtime.Encode(encoder, testCase.status) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } _, err = w.Write(statusBytes) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } } else if len(testCase.body) > 0 { _, err := w.Write([]byte(testCase.body)) - require.NoError(t, err) + if err != nil { + t.Errorf("unexpected error %v", err) + return + } } })) defer websocketServer.Close() diff --git a/util/cert/cert.go b/util/cert/cert.go index 91e171271a..1220461264 100644 --- a/util/cert/cert.go +++ b/util/cert/cert.go @@ -90,11 +90,37 @@ func NewSelfSignedCACert(cfg Config, key crypto.Signer) (*x509.Certificate, erro return x509.ParseCertificate(certDERBytes) } +// SelfSignedCertKeyOptions contains configuration parameters for generating self-signed certificates. +type SelfSignedCertKeyOptions struct { + // Host is required, and identifies the host of the serving certificate. Can be a DNS name or IP address. + Host string + // AlternateIPs is optional, and identifies additional IPs the serving certificate should be valid for. + AlternateIPs []net.IP + // AlternateDNS is optional, and identifies additional DNS names the serving certificate should be valid for. + AlternateDNS []string + + // MaxAge controls the duration of the issued certificate. + // Defaults to 1 year if unset. + // Ignored if FixtureDirectory is set. + MaxAge time.Duration + + // FixtureDirectory is intended for use in tests. + // If non-empty, it is a directory path which can contain pre-generated certs. The format is: + // _-_-.crt + // _-_-.key + // Certs/keys not existing in that directory are created with a duration of 100 years. + FixtureDirectory string +} + // GenerateSelfSignedCertKey creates a self-signed certificate and key for the given host. // Host may be an IP or a DNS name // You may also specify additional subject alt names (either ip or dns names) for the certificate. func GenerateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS []string) ([]byte, []byte, error) { - return GenerateSelfSignedCertKeyWithFixtures(host, alternateIPs, alternateDNS, "") + return GenerateSelfSignedCertKeyWithOptions(SelfSignedCertKeyOptions{ + Host: host, + AlternateIPs: alternateIPs, + AlternateDNS: alternateDNS, + }) } // GenerateSelfSignedCertKeyWithFixtures creates a self-signed certificate and key for the given host. @@ -106,8 +132,26 @@ func GenerateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS // _-_-.key // Certs/keys not existing in that directory are created. func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, alternateDNS []string, fixtureDirectory string) ([]byte, []byte, error) { + return GenerateSelfSignedCertKeyWithOptions(SelfSignedCertKeyOptions{ + Host: host, + AlternateIPs: alternateIPs, + AlternateDNS: alternateDNS, + FixtureDirectory: fixtureDirectory, + }) +} + +// GenerateSelfSignedCertKeyWithOptions generates a self-signed certificate and key based on the provided options. +func GenerateSelfSignedCertKeyWithOptions(opts SelfSignedCertKeyOptions) ([]byte, []byte, error) { + host := opts.Host + alternateIPs := opts.AlternateIPs + alternateDNS := opts.AlternateDNS + fixtureDirectory := opts.FixtureDirectory + maxAge := opts.MaxAge + if maxAge == 0 { + maxAge = 365 * 24 * time.Hour + } + validFrom := time.Now().Add(-time.Hour) // valid an hour earlier to avoid flakes due to clock skew - maxAge := time.Hour * 24 * 365 // one year self-signed certs baseName := fmt.Sprintf("%s_%s_%s", host, strings.Join(ipsToStrings(alternateIPs), "-"), strings.Join(alternateDNS, "-")) certFixturePath := filepath.Join(fixtureDirectory, baseName+".crt") diff --git a/util/certificate/certificate_manager.go b/util/certificate/certificate_manager.go index b4dcb0b849..cda9dfe47d 100644 --- a/util/certificate/certificate_manager.go +++ b/util/certificate/certificate_manager.go @@ -203,13 +203,16 @@ type Config struct { // certificate renewal failures. CertificateRenewFailure Counter // Name is an optional string that will be used when writing log output - // or returning errors from manager methods. If not set, SignerName will + // via logger.WithName or returning errors from manager methods. + // + // If not set, SignerName will // be used, if SignerName is not set, if Usages includes client auth the // name will be "client auth", otherwise the value will be "server". Name string - // Logf is an optional function that log output will be sent to from the - // certificate manager. If not set it will use klog.V(2) - Logf func(format string, args ...interface{}) + // Ctx is an optional context. Cancelling it is equivalent to + // calling Stop. A logger is extracted from it if non-nil, otherwise + // klog.Background() is used. + Ctx *context.Context } // Store is responsible for getting and updating the current certificate. @@ -278,30 +281,22 @@ type manager struct { cert *tls.Certificate serverHealth bool + // Context and cancel function for background goroutines. + ctx context.Context + cancel func(err error) + // the clientFn must only be accessed under the clientAccessLock clientAccessLock sync.Mutex clientsetFn ClientsetFunc - stopCh chan struct{} - stopped bool // Set to time.Now but can be stubbed out for testing now func() time.Time - - name string - logf func(format string, args ...interface{}) } // NewManager returns a new certificate manager. A certificate manager is // responsible for being the authoritative source of certificates in the // Kubelet and handling updates due to rotation. func NewManager(config *Config) (Manager, error) { - cert, forceRotation, err := getCurrentCertificateOrBootstrap( - config.CertificateStore, - config.BootstrapCertificatePEM, - config.BootstrapKeyPEM) - if err != nil { - return nil, err - } getTemplate := config.GetTemplate if getTemplate == nil { @@ -321,7 +316,6 @@ func NewManager(config *Config) (Manager, error) { getUsages = func(interface{}) []certificates.KeyUsage { return config.Usages } } m := manager{ - stopCh: make(chan struct{}), clientsetFn: config.ClientsetFn, getTemplate: getTemplate, dynamicTemplate: config.GetTemplate != nil, @@ -329,13 +323,12 @@ func NewManager(config *Config) (Manager, error) { requestedCertificateLifetime: config.RequestedCertificateLifetime, getUsages: getUsages, certStore: config.CertificateStore, - cert: cert, - forceRotation: forceRotation, certificateRotation: config.CertificateRotation, certificateRenewFailure: config.CertificateRenewFailure, now: time.Now, } + // Determine the name that is to be included in log output from this manager instance. name := config.Name if len(name) == 0 { name = m.signerName @@ -350,11 +343,35 @@ func NewManager(config *Config) (Manager, error) { } } - m.name = name - m.logf = config.Logf - if m.logf == nil { - m.logf = func(format string, args ...interface{}) { klog.V(2).Infof(format, args...) } + // The name gets included through contextual logging. + logger := klog.Background() + if config.Ctx != nil { + logger = klog.FromContext(*config.Ctx) } + logger = klog.LoggerWithName(logger, name) + + cert, forceRotation, err := getCurrentCertificateOrBootstrap( + logger, + config.CertificateStore, + config.BootstrapCertificatePEM, + config.BootstrapKeyPEM) + if err != nil { + return nil, err + } + m.cert, m.forceRotation = cert, forceRotation + + // cancel will be called by Stop, ctx.Done is our stop channel. + m.ctx, m.cancel = context.WithCancelCause(context.Background()) + if config.Ctx != nil && (*config.Ctx).Done() != nil { + ctx := *config.Ctx + // If we have been passed a context and it has a Done channel, then + // we need to map its cancellation to our Done method. + go func() { + <-ctx.Done() + m.Stop() + }() + } + m.ctx = klog.NewContext(m.ctx, logger) return &m, nil } @@ -367,7 +384,7 @@ func (m *manager) Current() *tls.Certificate { m.certAccessLock.RLock() defer m.certAccessLock.RUnlock() if m.cert != nil && m.cert.Leaf != nil && m.now().After(m.cert.Leaf.NotAfter) { - m.logf("%s: Current certificate is expired", m.name) + klog.FromContext(m.ctx).V(2).Info("Current certificate is expired") return nil } return m.cert @@ -383,31 +400,35 @@ func (m *manager) ServerHealthy() bool { // Stop terminates the manager. func (m *manager) Stop() { - m.clientAccessLock.Lock() - defer m.clientAccessLock.Unlock() - if m.stopped { - return - } - close(m.stopCh) - m.stopped = true + m.cancel(errors.New("asked to stop")) } // Start will start the background work of rotating the certificates. func (m *manager) Start() { + go m.run() +} + +// run, in contrast to Start, blocks while the manager is running. +// It waits for all goroutines to stop. +func (m *manager) run() { + logger := klog.FromContext(m.ctx) // Certificate rotation depends on access to the API server certificate // signing API, so don't start the certificate manager if we don't have a // client. if m.clientsetFn == nil { - m.logf("%s: Certificate rotation is not enabled, no connection to the apiserver", m.name) + logger.V(2).Info("Certificate rotation is not enabled, no connection to the apiserver") return } - m.logf("%s: Certificate rotation is enabled", m.name) + logger.V(2).Info("Certificate rotation is enabled") + + var wg sync.WaitGroup + defer wg.Wait() templateChanged := make(chan struct{}) - go wait.Until(func() { - deadline := m.nextRotationDeadline() + rotate := func(ctx context.Context) { + deadline := m.nextRotationDeadline(logger) if sleepInterval := deadline.Sub(m.now()); sleepInterval > 0 { - m.logf("%s: Waiting %v for next certificate rotation", m.name, sleepInterval) + logger.V(2).Info("Waiting for next certificate rotation", "sleep", sleepInterval) timer := time.NewTimer(sleepInterval) defer timer.Stop() @@ -421,7 +442,7 @@ func (m *manager) Start() { // if the template now matches what we last requested, restart the rotation deadline loop return } - m.logf("%s: Certificate template changed, rotating", m.name) + logger.V(2).Info("Certificate template changed, rotating") } } @@ -436,18 +457,24 @@ func (m *manager) Start() { Jitter: 0.1, Steps: 5, } - if err := wait.ExponentialBackoff(backoff, m.rotateCerts); err != nil { - utilruntime.HandleError(fmt.Errorf("%s: Reached backoff limit, still unable to rotate certs: %v", m.name, err)) - wait.PollInfinite(32*time.Second, m.rotateCerts) + if err := wait.ExponentialBackoffWithContext(ctx, backoff, m.rotateCerts); err != nil { + utilruntime.HandleErrorWithContext(ctx, err, "Reached backoff limit, still unable to rotate certs") + wait.PollInfiniteWithContext(ctx, 32*time.Second, m.rotateCerts) } - }, time.Second, m.stopCh) + } + + wg.Add(1) + go func() { + defer wg.Done() + wait.UntilWithContext(m.ctx, rotate, time.Second) + }() if m.dynamicTemplate { - go wait.Until(func() { + template := func(ctx context.Context) { // check if the current template matches what we last requested lastRequestCancel, lastRequestTemplate := m.getLastRequest() - if !m.certSatisfiesTemplate() && !reflect.DeepEqual(lastRequestTemplate, m.getTemplate()) { + if !m.certSatisfiesTemplate(logger) && !reflect.DeepEqual(lastRequestTemplate, m.getTemplate()) { // if the template is different, queue up an interrupt of the rotation deadline loop. // if we've requested a CSR that matches the new template by the time the interrupt is handled, the interrupt is disregarded. if lastRequestCancel != nil { @@ -456,14 +483,20 @@ func (m *manager) Start() { } select { case templateChanged <- struct{}{}: - case <-m.stopCh: + case <-ctx.Done(): } } - }, time.Second, m.stopCh) + } + wg.Add(1) + go func() { + defer wg.Done() + wait.UntilWithContext(m.ctx, template, time.Second) + }() } } func getCurrentCertificateOrBootstrap( + logger klog.Logger, store Store, bootstrapCertificatePEM []byte, bootstrapKeyPEM []byte) (cert *tls.Certificate, shouldRotate bool, errResult error) { @@ -494,7 +527,7 @@ func getCurrentCertificateOrBootstrap( certs, err := x509.ParseCertificates(bootstrapCert.Certificate[0]) if err != nil { - return nil, false, fmt.Errorf("unable to parse certificate data: %v", err) + return nil, false, fmt.Errorf("unable to parse certificate data: %w", err) } if len(certs) < 1 { return nil, false, fmt.Errorf("no cert data found") @@ -502,7 +535,7 @@ func getCurrentCertificateOrBootstrap( bootstrapCert.Leaf = certs[0] if _, err := store.Update(bootstrapCertificatePEM, bootstrapKeyPEM); err != nil { - utilruntime.HandleError(fmt.Errorf("unable to set the cert/key pair to the bootstrap certificate: %v", err)) + utilruntime.HandleErrorWithLogger(logger, err, "Unable to set the cert/key pair to the bootstrap certificate") } return &bootstrapCert, true, nil @@ -519,7 +552,7 @@ func (m *manager) getClientset() (clientset.Interface, error) { // Returns true if it changed the cert, false otherwise. Error is only returned in // exceptional cases. func (m *manager) RotateCerts() (bool, error) { - return m.rotateCerts() + return m.rotateCerts(m.ctx) } // rotateCerts attempts to request a client cert from the server, wait a reasonable @@ -528,12 +561,13 @@ func (m *manager) RotateCerts() (bool, error) { // This method also keeps track of "server health" by interpreting the responses it gets // from the server on the various calls it makes. // TODO: return errors, have callers handle and log them correctly -func (m *manager) rotateCerts() (bool, error) { - m.logf("%s: Rotating certificates", m.name) +func (m *manager) rotateCerts(ctx context.Context) (bool, error) { + logger := klog.FromContext(ctx) + logger.V(2).Info("Rotating certificates") template, csrPEM, keyPEM, privateKey, err := m.generateCSR() if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: Unable to generate a certificate signing request: %v", m.name, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Unable to generate a certificate signing request") if m.certificateRenewFailure != nil { m.certificateRenewFailure.Inc() } @@ -543,7 +577,7 @@ func (m *manager) rotateCerts() (bool, error) { // request the client each time clientSet, err := m.getClientset() if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: Unable to load a client to request certificates: %v", m.name, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Unable to load a client to request certificates") if m.certificateRenewFailure != nil { m.certificateRenewFailure.Inc() } @@ -557,16 +591,16 @@ func (m *manager) rotateCerts() (bool, error) { usages := getUsages(privateKey) // Call the Certificate Signing Request API to get a certificate for the // new private key - reqName, reqUID, err := csr.RequestCertificate(clientSet, csrPEM, "", m.signerName, m.requestedCertificateLifetime, usages, privateKey) + reqName, reqUID, err := csr.RequestCertificateWithContext(ctx, clientSet, csrPEM, "", m.signerName, m.requestedCertificateLifetime, usages, privateKey) if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: Failed while requesting a signed certificate from the control plane: %v", m.name, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Failed while requesting a signed certificate from the control plane") if m.certificateRenewFailure != nil { m.certificateRenewFailure.Inc() } return false, m.updateServerError(err) } - ctx, cancel := context.WithTimeout(context.Background(), certificateWaitTimeout) + ctx, cancel := context.WithTimeout(ctx, certificateWaitTimeout) defer cancel() // Once we've successfully submitted a CSR for this template, record that we did so @@ -576,7 +610,7 @@ func (m *manager) rotateCerts() (bool, error) { // is a remainder after the old design using raw watch wrapped with backoff. crtPEM, err := csr.WaitForCertificate(ctx, clientSet, reqName, reqUID) if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: certificate request was not signed: %v", m.name, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Certificate request was not signed") if m.certificateRenewFailure != nil { m.certificateRenewFailure.Inc() } @@ -585,7 +619,7 @@ func (m *manager) rotateCerts() (bool, error) { cert, err := m.certStore.Update(crtPEM, keyPEM) if err != nil { - utilruntime.HandleError(fmt.Errorf("%s: Unable to store the new cert/key pair: %v", m.name, err)) + utilruntime.HandleErrorWithContext(ctx, err, "Unable to store the new cert/key pair") if m.certificateRenewFailure != nil { m.certificateRenewFailure.Inc() } @@ -606,14 +640,14 @@ func (m *manager) rotateCerts() (bool, error) { // the template will not trigger a renewal. // // Requires certAccessLock to be locked. -func (m *manager) certSatisfiesTemplateLocked() bool { +func (m *manager) certSatisfiesTemplateLocked(logger klog.Logger) bool { if m.cert == nil { return false } if template := m.getTemplate(); template != nil { if template.Subject.CommonName != m.cert.Leaf.Subject.CommonName { - m.logf("%s: Current certificate CN (%s) does not match requested CN (%s)", m.name, m.cert.Leaf.Subject.CommonName, template.Subject.CommonName) + logger.V(2).Info("Current certificate CN does not match requested CN", "currentName", m.cert.Leaf.Subject.CommonName, "requestedName", template.Subject.CommonName) return false } @@ -621,7 +655,7 @@ func (m *manager) certSatisfiesTemplateLocked() bool { desiredDNSNames := sets.NewString(template.DNSNames...) missingDNSNames := desiredDNSNames.Difference(currentDNSNames) if len(missingDNSNames) > 0 { - m.logf("%s: Current certificate is missing requested DNS names %v", m.name, missingDNSNames.List()) + logger.V(2).Info("Current certificate is missing requested DNS names", "dnsNames", missingDNSNames.List()) return false } @@ -635,7 +669,7 @@ func (m *manager) certSatisfiesTemplateLocked() bool { } missingIPs := desiredIPs.Difference(currentIPs) if len(missingIPs) > 0 { - m.logf("%s: Current certificate is missing requested IP addresses %v", m.name, missingIPs.List()) + logger.V(2).Info("Current certificate is missing requested IP addresses", "IPs", missingIPs.List()) return false } @@ -643,7 +677,7 @@ func (m *manager) certSatisfiesTemplateLocked() bool { desiredOrgs := sets.NewString(template.Subject.Organization...) missingOrgs := desiredOrgs.Difference(currentOrgs) if len(missingOrgs) > 0 { - m.logf("%s: Current certificate is missing requested orgs %v", m.name, missingOrgs.List()) + logger.V(2).Info("Current certificate is missing requested orgs", "orgs", missingOrgs.List()) return false } } @@ -651,16 +685,16 @@ func (m *manager) certSatisfiesTemplateLocked() bool { return true } -func (m *manager) certSatisfiesTemplate() bool { +func (m *manager) certSatisfiesTemplate(logger klog.Logger) bool { m.certAccessLock.RLock() defer m.certAccessLock.RUnlock() - return m.certSatisfiesTemplateLocked() + return m.certSatisfiesTemplateLocked(logger) } // nextRotationDeadline returns a value for the threshold at which the // current certificate should be rotated, 80%+/-10% of the expiration of the // certificate. -func (m *manager) nextRotationDeadline() time.Time { +func (m *manager) nextRotationDeadline(logger klog.Logger) time.Time { // forceRotation is not protected by locks if m.forceRotation { m.forceRotation = false @@ -670,7 +704,7 @@ func (m *manager) nextRotationDeadline() time.Time { m.certAccessLock.RLock() defer m.certAccessLock.RUnlock() - if !m.certSatisfiesTemplateLocked() { + if !m.certSatisfiesTemplateLocked(logger) { return m.now() } @@ -678,7 +712,7 @@ func (m *manager) nextRotationDeadline() time.Time { totalDuration := float64(notAfter.Sub(m.cert.Leaf.NotBefore)) deadline := m.cert.Leaf.NotBefore.Add(jitteryDuration(totalDuration)) - m.logf("%s: Certificate expiration is %v, rotation deadline is %v", m.name, notAfter, deadline) + logger.V(2).Info("Certificate rotation deadline determined", "expiration", notAfter, "deadline", deadline) return deadline } @@ -732,22 +766,22 @@ func (m *manager) generateCSR() (template *x509.CertificateRequest, csrPEM []byt // Generate a new private key. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader) if err != nil { - return nil, nil, nil, nil, fmt.Errorf("%s: unable to generate a new private key: %v", m.name, err) + return nil, nil, nil, nil, fmt.Errorf("unable to generate a new private key: %w", err) } der, err := x509.MarshalECPrivateKey(privateKey) if err != nil { - return nil, nil, nil, nil, fmt.Errorf("%s: unable to marshal the new key to DER: %v", m.name, err) + return nil, nil, nil, nil, fmt.Errorf("unable to marshal the new key to DER: %w", err) } keyPEM = pem.EncodeToMemory(&pem.Block{Type: keyutil.ECPrivateKeyBlockType, Bytes: der}) template = m.getTemplate() if template == nil { - return nil, nil, nil, nil, fmt.Errorf("%s: unable to create a csr, no template available", m.name) + return nil, nil, nil, nil, errors.New("unable to create a csr, no template available") } csrPEM, err = cert.MakeCSRFromTemplate(privateKey, template) if err != nil { - return nil, nil, nil, nil, fmt.Errorf("%s: unable to create a csr from the private key: %v", m.name, err) + return nil, nil, nil, nil, fmt.Errorf("unable to create a csr from the private key: %w", err) } return template, csrPEM, keyPEM, privateKey, nil } diff --git a/util/certificate/certificate_manager_test.go b/util/certificate/certificate_manager_test.go index df1fd1d5b8..867ea0b926 100644 --- a/util/certificate/certificate_manager_test.go +++ b/util/certificate/certificate_manager_test.go @@ -18,15 +18,20 @@ package certificate import ( "bytes" + "context" "crypto/tls" "crypto/x509" "crypto/x509/pkix" + "errors" "fmt" "net" "strings" + "sync" "testing" "time" + "github.com/stretchr/testify/require" + certificatesv1 "k8s.io/api/certificates/v1" certificatesv1beta1 "k8s.io/api/certificates/v1beta1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -38,6 +43,8 @@ import ( "k8s.io/client-go/kubernetes/fake" certificatesclient "k8s.io/client-go/kubernetes/typed/certificates/v1beta1" clienttesting "k8s.io/client-go/testing" + "k8s.io/klog/v2" + "k8s.io/klog/v2/ktesting" netutils "k8s.io/utils/net" ) @@ -268,6 +275,7 @@ func TestSetRotationDeadline(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { + logger, ctx := ktesting.NewTestContext(t) m := manager{ cert: &tls.Certificate{ Leaf: &x509.Certificate{ @@ -277,12 +285,12 @@ func TestSetRotationDeadline(t *testing.T) { }, getTemplate: func() *x509.CertificateRequest { return &x509.CertificateRequest{} }, now: func() time.Time { return now }, - logf: t.Logf, + ctx: ctx, } jitteryDuration = func(float64) time.Duration { return time.Duration(float64(tc.notAfter.Sub(tc.notBefore)) * 0.7) } lowerBound := tc.notBefore.Add(time.Duration(float64(tc.notAfter.Sub(tc.notBefore)) * 0.7)) - deadline := m.nextRotationDeadline() + deadline := m.nextRotationDeadline(logger) if !deadline.Equal(lowerBound) { t.Errorf("For notBefore %v, notAfter %v, the rotationDeadline %v should be %v.", @@ -438,6 +446,7 @@ func TestCertSatisfiesTemplate(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { + logger, ctx := ktesting.NewTestContext(t) var tlsCert *tls.Certificate if tc.cert != nil { @@ -450,10 +459,10 @@ func TestCertSatisfiesTemplate(t *testing.T) { cert: tlsCert, getTemplate: func() *x509.CertificateRequest { return tc.template }, now: time.Now, - logf: t.Logf, + ctx: ctx, } - result := m.certSatisfiesTemplate() + result := m.certSatisfiesTemplate(logger) if result != tc.shouldSatisfy { t.Errorf("cert: %+v, template: %+v, certSatisfiesTemplate returned %v, want %v", m.cert, tc.template, result, tc.shouldSatisfy) } @@ -462,6 +471,7 @@ func TestCertSatisfiesTemplate(t *testing.T) { } func TestRotateCertCreateCSRError(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) now := time.Now() m := manager{ cert: &tls.Certificate{ @@ -474,11 +484,11 @@ func TestRotateCertCreateCSRError(t *testing.T) { clientsetFn: func(_ *tls.Certificate) (clientset.Interface, error) { return newClientset(fakeClient{failureType: createError}), nil }, - now: func() time.Time { return now }, - logf: t.Logf, + now: func() time.Time { return now }, + ctx: ctx, } - if success, err := m.rotateCerts(); success { + if success, err := m.rotateCerts(ctx); success { t.Errorf("Got success from 'rotateCerts', wanted failure") } else if err != nil { t.Errorf("Got error %v from 'rotateCerts', wanted no error.", err) @@ -486,6 +496,7 @@ func TestRotateCertCreateCSRError(t *testing.T) { } func TestRotateCertWaitingForResultError(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) now := time.Now() m := manager{ cert: &tls.Certificate{ @@ -498,13 +509,13 @@ func TestRotateCertWaitingForResultError(t *testing.T) { clientsetFn: func(_ *tls.Certificate) (clientset.Interface, error) { return newClientset(fakeClient{failureType: watchError}), nil }, - now: func() time.Time { return now }, - logf: t.Logf, + now: func() time.Time { return now }, + ctx: ctx, } defer func(t time.Duration) { certificateWaitTimeout = t }(certificateWaitTimeout) certificateWaitTimeout = 1 * time.Millisecond - if success, err := m.rotateCerts(); success { + if success, err := m.rotateCerts(ctx); success { t.Errorf("Got success from 'rotateCerts', wanted failure.") } else if err != nil { t.Errorf("Got error %v from 'rotateCerts', wanted no error.", err) @@ -610,11 +621,13 @@ func TestGetCurrentCertificateOrBootstrap(t *testing.T) { for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { + logger, _ := ktesting.NewTestContext(t) store := &fakeStore{ cert: tc.storeCert, } certResult, shouldRotate, err := getCurrentCertificateOrBootstrap( + logger, store, tc.bootstrapCertData, tc.bootstrapKeyData) @@ -717,6 +730,7 @@ func TestInitializeCertificateSigningRequestClient(t *testing.T) { for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) certificateStore := &fakeStore{ cert: tc.storeCert.certificate, } @@ -744,6 +758,7 @@ func TestInitializeCertificateSigningRequestClient(t *testing.T) { certificatePEM: tc.apiCert.certificatePEM, }), nil }, + Ctx: &ctx, }) if err != nil { t.Errorf("Got %v, wanted no error.", err) @@ -764,7 +779,7 @@ func TestInitializeCertificateSigningRequestClient(t *testing.T) { t.Errorf("Expected a '*manager' from 'NewManager'") } else { if m.forceRotation { - if success, err := m.rotateCerts(); !success { + if success, err := m.rotateCerts(ctx); !success { t.Errorf("Got failure from 'rotateCerts', wanted success.") } else if err != nil { t.Errorf("Got error %v, expected none.", err) @@ -832,6 +847,7 @@ func TestInitializeOtherRESTClients(t *testing.T) { for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) certificateStore := &fakeStore{ cert: tc.storeCert.certificate, } @@ -870,7 +886,7 @@ func TestInitializeOtherRESTClients(t *testing.T) { t.Errorf("Expected a '*manager' from 'NewManager'") } else { if m.forceRotation { - success, err := certificateManager.(*manager).rotateCerts() + success, err := certificateManager.(*manager).rotateCerts(ctx) if err != nil { t.Errorf("Got error %v, expected none.", err) return @@ -977,6 +993,7 @@ func TestServerHealth(t *testing.T) { for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) certificateStore := &fakeStore{ cert: tc.storeCert.certificate, } @@ -1016,7 +1033,7 @@ func TestServerHealth(t *testing.T) { if _, ok := certificateManager.(*manager); !ok { t.Errorf("Expected a '*manager' from 'NewManager'") } else { - success, err := certificateManager.(*manager).rotateCerts() + success, err := certificateManager.(*manager).rotateCerts(ctx) if err != nil { t.Errorf("Got error %v, expected none.", err) return @@ -1039,6 +1056,7 @@ func TestServerHealth(t *testing.T) { } func TestRotationLogsDuration(t *testing.T) { + _, ctx := ktesting.NewTestContext(t) h := metricMock{} now := time.Now() certIss := now.Add(-2 * time.Hour) @@ -1058,9 +1076,9 @@ func TestRotationLogsDuration(t *testing.T) { }, certificateRotation: &h, now: func() time.Time { return now }, - logf: t.Logf, + ctx: ctx, } - ok, err := m.rotateCerts() + ok, err := m.rotateCerts(ctx) if err != nil || !ok { t.Errorf("failed to rotate certs: %v", err) } @@ -1073,6 +1091,101 @@ func TestRotationLogsDuration(t *testing.T) { } +func TestStop(t *testing.T) { + // No certificate yet, will be added while manager runs. + store := &fakeStore{} + m, err := NewManager(&Config{ + GetTemplate: func() *x509.CertificateRequest { + return &x509.CertificateRequest{ + Subject: pkix.Name{ + Organization: []string{"system:nodes"}, + CommonName: "system:node:fake-node-name", + }, + } + }, + Usages: []certificatesv1.KeyUsage{}, + CertificateStore: store, + ClientsetFn: func(_ *tls.Certificate) (clientset.Interface, error) { + return newClientset(fakeClient{ + certificatePEM: apiServerCertData.certificatePEM, + }), nil + }, + }) + require.NoError(t, err, "initialize the certificate manager") + require.Nil(t, m.Current(), "no certificate yet") + + // Run the manager and stop it when the test cleans up. + var wg sync.WaitGroup + defer func() { + t.Log("Waiting for manager to stop...") + wg.Wait() + }() + wg.Add(1) + go func() { + defer wg.Done() + m.(*manager).run() + }() + defer m.Stop() + + require.Eventually(t, func() bool { + return m.Current() != nil + }, 10*time.Second, time.Microsecond, "current certificate") +} + +func TestContext(t *testing.T) { + logger := ktesting.NewLogger(t, ktesting.NewConfig( + ktesting.BufferLogs(true), + ktesting.Verbosity(2), + )) + ctx := klog.NewContext(context.Background(), logger) + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(errors.New("test is done")) + + // No certificate yet, will be added while manager runs. + store := &fakeStore{} + m, err := NewManager(&Config{ + Ctx: &ctx, + GetTemplate: func() *x509.CertificateRequest { + return &x509.CertificateRequest{ + Subject: pkix.Name{ + Organization: []string{"system:nodes"}, + CommonName: "system:node:fake-node-name", + }, + } + }, + Usages: []certificatesv1.KeyUsage{}, + CertificateStore: store, + ClientsetFn: func(_ *tls.Certificate) (clientset.Interface, error) { + return newClientset(fakeClient{ + certificatePEM: apiServerCertData.certificatePEM, + }), nil + }, + }) + require.NoError(t, err, "initialize the certificate manager") + require.Nil(t, m.Current(), "no certificate yet") + + // Run the manager and stop it when the test cleans up. + var wg sync.WaitGroup + defer func() { + t.Log("Waiting for manager to stop...") + wg.Wait() + + // Must be a no-op. + m.Stop() + }() + wg.Add(1) + go func() { + defer wg.Done() + m.(*manager).run() + }() + defer cancel(errors.New("testing context cancellation")) + + require.Eventually(t, func() bool { + return m.Current() != nil + }, 10*time.Second, time.Microsecond, "current certificate") + require.Contains(t, logger.GetSink().(ktesting.Underlier).GetBuffer().String(), "certificate: Rotating certificates", "contextual log output from manager.rotateCerts") +} + type fakeClientFailureType int const ( @@ -1243,10 +1356,14 @@ func (w *fakeWatch) ResultChan() <-chan watch.Event { } type fakeStore struct { - cert *tls.Certificate + mutex sync.Mutex + cert *tls.Certificate } func (s *fakeStore) Current() (*tls.Certificate, error) { + s.mutex.Lock() + defer s.mutex.Unlock() + if s.cert == nil { noKeyErr := NoCertKeyError("") return nil, &noKeyErr @@ -1258,6 +1375,9 @@ func (s *fakeStore) Current() (*tls.Certificate, error) { // pair the 'current' pair, that will be returned by future calls to // Current(). func (s *fakeStore) Update(certPEM, keyPEM []byte) (*tls.Certificate, error) { + s.mutex.Lock() + defer s.mutex.Unlock() + // In order to make the mocking work, whenever a cert/key pair is passed in // to be updated in the mock store, assume that the certificate manager // generated the key, and then asked the mock CertificateSigningRequest API diff --git a/util/certificate/certificate_store.go b/util/certificate/certificate_store.go index e7ed58ee8a..4f9d5db06a 100644 --- a/util/certificate/certificate_store.go +++ b/util/certificate/certificate_store.go @@ -38,6 +38,7 @@ const ( ) type fileStore struct { + logger klog.Logger pairNamePrefix string certDirectory string keyDirectory string @@ -67,14 +68,30 @@ type FileStore interface { // updates will be written to the ${certDirectory} directory and // ${certDirectory}/${pairNamePrefix}-current.pem will be created as a soft // link to the currently selected cert/key pair. +// +// Contextual logging: NewFileStoreWithLogger should be used instead of NewFileStore in code which supports contextual logging. func NewFileStore( pairNamePrefix string, certDirectory string, keyDirectory string, certFile string, keyFile string) (FileStore, error) { + return NewFileStoreWithLogger(klog.Background(), pairNamePrefix, certDirectory, keyDirectory, certFile, keyFile) +} + +// NewFileStoreWithLogger is a variant of NewFileStore where the caller is in +// control of logging. All log messages get emitted with logger.Info, so +// pass e.g. logger.V(3) to make logging less verbose. +func NewFileStoreWithLogger( + logger klog.Logger, + pairNamePrefix string, + certDirectory string, + keyDirectory string, + certFile string, + keyFile string) (FileStore, error) { s := fileStore{ + logger: logger, pairNamePrefix: pairNamePrefix, certDirectory: certDirectory, keyDirectory: keyDirectory, @@ -127,7 +144,7 @@ func (s *fileStore) Current() (*tls.Certificate, error) { if pairFileExists, err := fileExists(pairFile); err != nil { return nil, err } else if pairFileExists { - klog.Infof("Loading cert/key pair from %q.", pairFile) + s.logger.Info("Loading cert/key pair from a file", "filePath", pairFile) return loadFile(pairFile) } @@ -140,7 +157,7 @@ func (s *fileStore) Current() (*tls.Certificate, error) { return nil, err } if certFileExists && keyFileExists { - klog.Infof("Loading cert/key pair from (%q, %q).", s.certFile, s.keyFile) + s.logger.Info("Loading cert/key pair", "certFile", s.certFile, "keyFile", s.keyFile) return loadX509KeyPair(s.certFile, s.keyFile) } @@ -155,7 +172,7 @@ func (s *fileStore) Current() (*tls.Certificate, error) { return nil, err } if certFileExists && keyFileExists { - klog.Infof("Loading cert/key pair from (%q, %q).", c, k) + s.logger.Info("Loading cert/key pair", "certFile", c, "keyFile", k) return loadX509KeyPair(c, k) } diff --git a/util/certificate/certificate_store_test.go b/util/certificate/certificate_store_test.go index 3d6abaa4c8..11591520b7 100644 --- a/util/certificate/certificate_store_test.go +++ b/util/certificate/certificate_store_test.go @@ -235,6 +235,7 @@ func TestUpdateNoRotation(t *testing.T) { t.Fatalf("Unable to create the file %q: %v", certFile, err) } + //nolint:logcheck // Intentionally uses the old API. s, err := NewFileStore(prefix, dir, dir, certFile, keyFile) if err != nil { t.Fatalf("Got %v while creating a new store.", err) @@ -269,6 +270,7 @@ func TestUpdateRotation(t *testing.T) { t.Fatalf("Unable to create the file %q: %v", certFile, err) } + //nolint:logcheck // Intentionally uses the old API. s, err := NewFileStore(prefix, dir, dir, certFile, keyFile) if err != nil { t.Fatalf("Got %v while creating a new store.", err) @@ -303,6 +305,7 @@ func TestUpdateTwoCerts(t *testing.T) { t.Fatalf("Unable to create the file %q: %v", certFile, err) } + //nolint:logcheck // Intentionally uses the old API. s, err := NewFileStore(prefix, dir, dir, certFile, keyFile) if err != nil { t.Fatalf("Got %v while creating a new store.", err) @@ -340,6 +343,7 @@ func TestUpdateWithBadCertKeyData(t *testing.T) { t.Fatalf("Unable to create the file %q: %v", certFile, err) } + //nolint:logcheck // Intentionally uses the old API. s, err := NewFileStore(prefix, dir, dir, certFile, keyFile) if err != nil { t.Fatalf("Got %v while creating a new store.", err) @@ -376,6 +380,7 @@ func TestCurrentPairFile(t *testing.T) { t.Fatalf("unable to create a symlink from %q to %q: %v", currentFile, pairFile, err) } + //nolint:logcheck // Intentionally uses the old API. store, err := NewFileStore("kubelet-server", dir, dir, "", "") if err != nil { t.Fatalf("Failed to initialize certificate store: %v", err) @@ -413,6 +418,7 @@ func TestCurrentCertKeyFiles(t *testing.T) { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } + //nolint:logcheck // Intentionally uses the old API. store, err := NewFileStore(prefix, dir, dir, certFile, keyFile) if err != nil { t.Fatalf("Failed to initialize certificate store: %v", err) @@ -450,6 +456,7 @@ func TestCurrentTwoCerts(t *testing.T) { t.Fatalf("Unable to create the file %q: %v", keyFile, err) } + //nolint:logcheck // Intentionally uses the old API. store, err := NewFileStore(prefix, dir, dir, certFile, keyFile) if err != nil { t.Fatalf("Failed to initialize certificate store: %v", err) @@ -481,6 +488,7 @@ func TestCurrentNoFiles(t *testing.T) { } }() + //nolint:logcheck // Intentionally uses the old API. store, err := NewFileStore("kubelet-server", dir, dir, "", "") if err != nil { t.Fatalf("Failed to initialize certificate store: %v", err) diff --git a/util/certificate/csr/csr.go b/util/certificate/csr/csr.go index 0390d1c02f..a2921ecd4f 100644 --- a/util/certificate/csr/csr.go +++ b/util/certificate/csr/csr.go @@ -47,7 +47,18 @@ import ( // PEM encoded CSR and send it to API server. An optional requestedDuration may be passed // to set the spec.expirationSeconds field on the CSR to control the lifetime of the issued // certificate. This is not guaranteed as the signer may choose to ignore the request. +// +// Deprecated: use RequestCertificateWithContext instead. func RequestCertificate(client clientset.Interface, csrData []byte, name, signerName string, requestedDuration *time.Duration, usages []certificatesv1.KeyUsage, privateKey interface{}) (reqName string, reqUID types.UID, err error) { + return RequestCertificateWithContext(context.Background(), client, csrData, name, signerName, requestedDuration, usages, privateKey) +} + +// RequestCertificateWithContext will either use an existing (if this process has run +// before but not to completion) or create a certificate signing request using the +// PEM encoded CSR and send it to API server. An optional requestedDuration may be passed +// to set the spec.expirationSeconds field on the CSR to control the lifetime of the issued +// certificate. This is not guaranteed as the signer may choose to ignore the request. +func RequestCertificateWithContext(ctx context.Context, client clientset.Interface, csrData []byte, name, signerName string, requestedDuration *time.Duration, usages []certificatesv1.KeyUsage, privateKey interface{}) (reqName string, reqUID types.UID, err error) { csr := &certificatesv1.CertificateSigningRequest{ // Username, UID, Groups will be injected by API server. TypeMeta: metav1.TypeMeta{Kind: "CertificateSigningRequest"}, @@ -67,21 +78,22 @@ func RequestCertificate(client clientset.Interface, csrData []byte, name, signer csr.Spec.ExpirationSeconds = DurationToExpirationSeconds(*requestedDuration) } - reqName, reqUID, err = create(client, csr) + reqName, reqUID, err = create(ctx, client, csr) switch { case err == nil: return reqName, reqUID, err case apierrors.IsAlreadyExists(err) && len(name) > 0: - klog.Infof("csr for this node already exists, reusing") - req, err := get(client, name) + logger := klog.FromContext(ctx) + logger.Info("csr for this node already exists, reusing") + req, err := get(ctx, client, name) if err != nil { return "", "", formatError("cannot retrieve certificate signing request: %v", err) } if err := ensureCompatible(req, csr, privateKey); err != nil { return "", "", fmt.Errorf("retrieved csr is not compatible: %v", err) } - klog.Infof("csr for this node is still valid") + logger.Info("csr for this node is still valid") return req.Name, req.UID, nil default: @@ -97,13 +109,13 @@ func ExpirationSecondsToDuration(expirationSeconds int32) time.Duration { return time.Duration(expirationSeconds) * time.Second } -func get(client clientset.Interface, name string) (*certificatesv1.CertificateSigningRequest, error) { - v1req, v1err := client.CertificatesV1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{}) +func get(ctx context.Context, client clientset.Interface, name string) (*certificatesv1.CertificateSigningRequest, error) { + v1req, v1err := client.CertificatesV1().CertificateSigningRequests().Get(ctx, name, metav1.GetOptions{}) if v1err == nil || !apierrors.IsNotFound(v1err) { return v1req, v1err } - v1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{}) + v1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Get(ctx, name, metav1.GetOptions{}) if v1beta1err != nil { return nil, v1beta1err } @@ -123,10 +135,10 @@ func get(client clientset.Interface, name string) (*certificatesv1.CertificateSi return v1req, nil } -func create(client clientset.Interface, csr *certificatesv1.CertificateSigningRequest) (reqName string, reqUID types.UID, err error) { +func create(ctx context.Context, client clientset.Interface, csr *certificatesv1.CertificateSigningRequest) (reqName string, reqUID types.UID, err error) { // only attempt a create via v1 if we specified signerName and usages and are not using the legacy unknown signerName if len(csr.Spec.Usages) > 0 && len(csr.Spec.SignerName) > 0 && csr.Spec.SignerName != "kubernetes.io/legacy-unknown" { - v1req, v1err := client.CertificatesV1().CertificateSigningRequests().Create(context.TODO(), csr, metav1.CreateOptions{}) + v1req, v1err := client.CertificatesV1().CertificateSigningRequests().Create(ctx, csr, metav1.CreateOptions{}) switch { case v1err != nil && apierrors.IsNotFound(v1err): // v1 CSR API was not found, continue to try v1beta1 @@ -154,7 +166,7 @@ func create(client clientset.Interface, csr *certificatesv1.CertificateSigningRe } // create v1beta1 - v1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Create(context.TODO(), v1beta1csr, metav1.CreateOptions{}) + v1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Create(ctx, v1beta1csr, metav1.CreateOptions{}) if v1beta1err != nil { return "", "", v1beta1err } @@ -164,6 +176,7 @@ func create(client clientset.Interface, csr *certificatesv1.CertificateSigningRe // WaitForCertificate waits for a certificate to be issued until timeout, or returns an error. func WaitForCertificate(ctx context.Context, client clientset.Interface, reqName string, reqUID types.UID) (certData []byte, err error) { fieldSelector := fields.OneTermEqualSelector("metadata.name", reqName).String() + logger := klog.FromContext(ctx) var lw *cache.ListWatch var obj runtime.Object @@ -184,7 +197,7 @@ func WaitForCertificate(ctx context.Context, client clientset.Interface, reqName } break } else { - klog.V(2).Infof("error fetching v1 certificate signing request: %v", err) + logger.V(2).Info("Error fetching v1 certificate signing request", "err", err) } // return if we've timed out @@ -208,7 +221,7 @@ func WaitForCertificate(ctx context.Context, client clientset.Interface, reqName } break } else { - klog.V(2).Infof("error fetching v1beta1 certificate signing request: %v", err) + logger.V(2).Info("Error fetching v1beta1 certificate signing request", "err", err) } // return if we've timed out @@ -254,11 +267,11 @@ func WaitForCertificate(ctx context.Context, client clientset.Interface, reqName } if approved { if len(csr.Status.Certificate) > 0 { - klog.V(2).Infof("certificate signing request %s is issued", csr.Name) + logger.V(2).Info("Certificate signing request is issued", "csr", klog.KObj(csr)) issuedCertificate = csr.Status.Certificate return true, nil } - klog.V(2).Infof("certificate signing request %s is approved, waiting to be issued", csr.Name) + logger.V(2).Info("Certificate signing request is approved, waiting to be issued", "csr", klog.KObj(csr)) } case *certificatesv1beta1.CertificateSigningRequest: @@ -279,11 +292,11 @@ func WaitForCertificate(ctx context.Context, client clientset.Interface, reqName } if approved { if len(csr.Status.Certificate) > 0 { - klog.V(2).Infof("certificate signing request %s is issued", csr.Name) + logger.V(2).Info("Certificate signing request is issued", "csr", klog.KObj(csr)) issuedCertificate = csr.Status.Certificate return true, nil } - klog.V(2).Infof("certificate signing request %s is approved, waiting to be issued", csr.Name) + logger.V(2).Info("Certificate signing request is approved, waiting to be issued", "csr", klog.KObj(csr)) } default: diff --git a/util/consistencydetector/data_consistency_detector.go b/util/consistencydetector/data_consistency_detector.go index b33d08032f..72a871d434 100644 --- a/util/consistencydetector/data_consistency_detector.go +++ b/util/consistencydetector/data_consistency_detector.go @@ -22,7 +22,7 @@ import ( "sort" "time" - "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp" //nolint:depguard "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/util/flowcontrol/backoff.go b/util/flowcontrol/backoff.go index 899b8e34ef..7cb46717c2 100644 --- a/util/flowcontrol/backoff.go +++ b/util/flowcontrol/backoff.go @@ -22,7 +22,6 @@ import ( "time" "k8s.io/utils/clock" - testingclock "k8s.io/utils/clock/testing" ) type backoffEntry struct { @@ -49,7 +48,7 @@ type Backoff struct { maxJitterFactor float64 } -func NewFakeBackOff(initial, max time.Duration, tc *testingclock.FakeClock) *Backoff { +func NewFakeBackOff(initial, max time.Duration, tc clock.Clock) *Backoff { return newBackoff(tc, initial, max, 0.0) } @@ -57,7 +56,7 @@ func NewBackOff(initial, max time.Duration) *Backoff { return NewBackOffWithJitter(initial, max, 0.0) } -func NewFakeBackOffWithJitter(initial, max time.Duration, tc *testingclock.FakeClock, maxJitterFactor float64) *Backoff { +func NewFakeBackOffWithJitter(initial, max time.Duration, tc clock.Clock, maxJitterFactor float64) *Backoff { return newBackoff(tc, initial, max, maxJitterFactor) } diff --git a/util/jsonpath/doc.go b/util/jsonpath/doc.go index 0effb15c41..2a6e170617 100644 --- a/util/jsonpath/doc.go +++ b/util/jsonpath/doc.go @@ -17,4 +17,4 @@ limitations under the License. // package jsonpath is a template engine using jsonpath syntax, // which can be seen at http://goessner.net/articles/JsonPath/. // In addition, it has {range} {end} function to iterate list and slice. -package jsonpath // import "k8s.io/client-go/util/jsonpath" +package jsonpath diff --git a/util/workqueue/delaying_queue.go b/util/workqueue/delaying_queue.go index e33a6c6929..da444f4fb3 100644 --- a/util/workqueue/delaying_queue.go +++ b/util/workqueue/delaying_queue.go @@ -22,6 +22,7 @@ import ( "time" utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/klog/v2" "k8s.io/utils/clock" ) @@ -46,6 +47,10 @@ type DelayingQueueConfig = TypedDelayingQueueConfig[any] // TypedDelayingQueueConfig specifies optional configurations to customize a DelayingInterface. type TypedDelayingQueueConfig[T comparable] struct { + // An optional logger. The name of the queue does *not* get added to it, this should + // be done by the caller if desired. + Logger *klog.Logger + // Name for the queue. If unnamed, the metrics will not be registered. Name string @@ -94,6 +99,10 @@ func TypedNewDelayingQueue[T comparable]() TypedDelayingInterface[T] { // NewTypedDelayingQueueWithConfig constructs a new workqueue with options to // customize different properties. func NewTypedDelayingQueueWithConfig[T comparable](config TypedDelayingQueueConfig[T]) TypedDelayingInterface[T] { + logger := klog.Background() + if config.Logger != nil { + logger = *config.Logger + } if config.Clock == nil { config.Clock = clock.RealClock{} } @@ -106,7 +115,7 @@ func NewTypedDelayingQueueWithConfig[T comparable](config TypedDelayingQueueConf }) } - return newDelayingQueue(config.Clock, config.Queue, config.Name, config.MetricsProvider) + return newDelayingQueue(logger, config.Clock, config.Queue, config.Name, config.MetricsProvider) } // NewDelayingQueueWithCustomQueue constructs a new workqueue with ability to @@ -135,7 +144,7 @@ func NewDelayingQueueWithCustomClock(clock clock.WithTicker, name string) Delayi }) } -func newDelayingQueue[T comparable](clock clock.WithTicker, q TypedInterface[T], name string, provider MetricsProvider) *delayingType[T] { +func newDelayingQueue[T comparable](logger klog.Logger, clock clock.WithTicker, q TypedInterface[T], name string, provider MetricsProvider) *delayingType[T] { ret := &delayingType[T]{ TypedInterface: q, clock: clock, @@ -145,7 +154,7 @@ func newDelayingQueue[T comparable](clock clock.WithTicker, q TypedInterface[T], metrics: newRetryMetrics(name, provider), } - go ret.waitingLoop() + go ret.waitingLoop(logger) return ret } @@ -264,8 +273,8 @@ func (q *delayingType[T]) AddAfter(item T, duration time.Duration) { const maxWait = 10 * time.Second // waitingLoop runs until the workqueue is shutdown and keeps a check on the list of items to be added. -func (q *delayingType[T]) waitingLoop() { - defer utilruntime.HandleCrash() +func (q *delayingType[T]) waitingLoop(logger klog.Logger) { + defer utilruntime.HandleCrashWithLogger(logger) // Make a placeholder channel to use when there are no items in our list never := make(<-chan time.Time) diff --git a/util/workqueue/doc.go b/util/workqueue/doc.go index 8555aa95fe..a76d830ede 100644 --- a/util/workqueue/doc.go +++ b/util/workqueue/doc.go @@ -23,4 +23,4 @@ limitations under the License. // - Multiple consumers and producers. In particular, it is allowed for an // item to be reenqueued while it is being processed. // - Shutdown notifications. -package workqueue // import "k8s.io/client-go/util/workqueue" +package workqueue diff --git a/util/workqueue/parallelizer.go b/util/workqueue/parallelizer.go index 366bf20a31..9f986a25a4 100644 --- a/util/workqueue/parallelizer.go +++ b/util/workqueue/parallelizer.go @@ -74,7 +74,7 @@ func ParallelizeUntil(ctx context.Context, workers, pieces int, doWorkPiece DoWo wg.Add(workers) for i := 0; i < workers; i++ { go func() { - defer utilruntime.HandleCrash() + defer utilruntime.HandleCrashWithContext(ctx) defer wg.Done() for chunk := range toProcess { start := chunk * chunkSize