rebase: update replaced k8s.io modules to v0.33.0

Signed-off-by: Niels de Vos <ndevos@ibm.com>
This commit is contained in:
Niels de Vos
2025-05-07 13:13:33 +02:00
committed by mergify[bot]
parent dd77e72800
commit 107407b44b
1723 changed files with 65035 additions and 175239 deletions

37
e2e/vendor/k8s.io/apimachinery/pkg/api/safe/safe.go generated vendored Normal file
View File

@ -0,0 +1,37 @@
/*
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 safe
// Field takes a pointer to any value (which may or may not be nil) and
// a function that traverses to a target type R (a typical use case is to dereference a field),
// and returns the result of the traversal, or the zero value of the target type.
// This is roughly equivalent to "value != nil ? fn(value) : zero-value" in languages that support the ternary operator.
func Field[V any, R any](value *V, fn func(*V) R) R {
if value == nil {
var zero R
return zero
}
o := fn(value)
return o
}
// Cast takes any value, attempts to cast it to T, and returns the T value if
// the cast is successful, or else the zero value of T.
func Cast[T any](value any) T {
result, _ := value.(T)
return result
}

View File

@ -0,0 +1,64 @@
# API validation
This package holds functions which validate fields and types in the Kubernetes
API. It may be useful beyond API validation, but this is the primary goal.
Most of the public functions here have signatures which adhere to the following
pattern, which is assumed by automation and code-generation:
```
import (
"context"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
func <Name>(ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue <ValueType>, <OtherArgs...>) field.ErrorList
```
The name of validator functions should consider that callers will generally be
spelling out the package name and the function name, and so should aim for
legibility. E.g. `validate.Concept()`.
The `ctx` argument is Go's usual Context.
The `opCtx` argument provides information about the API operation in question.
The `fldPath` argument indicates the path to the field in question, to be used
in errors.
The `value` and `oldValue` arguments are the thing(s) being validated. For
CREATE operations (`opCtx.Operation == operation.Create`), the `oldValue`
argument will be nil. Many validators functions only look at the current value
(`value`) and disregard `oldValue`.
The `value` and `oldValue` arguments are always nilable - pointers to primitive
types, slices of any type, or maps of any type. Validator functions should
avoid dereferencing nil. Callers are expected to not pass a nil `value` unless the
API field itself was nilable. `oldValue` is always nil for CREATE operations and
is also nil for UPDATE operations if the `value` is not correlated with an `oldValue`.
Simple content-validators may have no `<OtherArgs>`, but validator functions
may take additional arguments. Some validator functions will be built as
generics, e.g. to allow any integer type or to handle arbitrary slices.
Examples:
```
// NonEmpty validates that a string is not empty.
func NonEmpty(ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList
// Even validates that a slice has an even number of items.
func Even[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList
// KeysMaxLen validates that all of the string keys in a map are under the
// specified length.
func KeysMaxLen[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ map[string]T, maxLen int) field.ErrorList
```
Validator functions always return an `ErrorList` where each item is a distinct
validation failure and a zero-length return value (not just nil) indicates
success.
Good validation failure messages follow the Kubernetes API conventions, for
example using "must" instead of "should".

View File

@ -0,0 +1,28 @@
/*
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 validate
import (
"context"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// ValidateFunc is a function that validates a value, possibly considering the
// old value (if any).
type ValidateFunc[T any] func(ctx context.Context, op operation.Operation, fldPath *field.Path, newValue, oldValue T) field.ErrorList

View File

@ -0,0 +1,32 @@
/*
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 constraints
// Signed is a constraint that permits any signed integer type.
type Signed interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
// Unsigned is a constraint that permits any unsigned integer type.
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
// Integer is a constraint that permits any integer type.
type Integer interface {
Signed | Unsigned
}

View File

@ -1,5 +1,5 @@
/*
Copyright 2017 The Kubernetes Authors.
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.
@ -14,6 +14,16 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Package waitgroup implements SafeWaitGroup wrap of sync.WaitGroup.
// Add with positive delta when waiting will fail, to prevent sync.WaitGroup race issue.
package waitgroup
package content
import (
"fmt"
"k8s.io/apimachinery/pkg/api/validate/constraints"
)
// MinError returns a string explanation of a "must be greater than or equal"
// validation failure.
func MinError[T constraints.Integer](min T) string {
return fmt.Sprintf("must be greater than or equal to %d", min)
}

50
e2e/vendor/k8s.io/apimachinery/pkg/api/validate/doc.go generated vendored Normal file
View File

@ -0,0 +1,50 @@
/*
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 validate holds API validation functions which are designed for use
// with the k8s.io/code-generator/cmd/validation-gen tool. Each validation
// function has a similar fingerprint:
//
// func <Name>(ctx context.Context,
// op operation.Operation,
// fldPath *field.Path,
// value, oldValue <nilable type>,
// <other args...>) field.ErrorList
//
// The value and oldValue arguments will always be a nilable type. If the
// original value was a string, these will be a *string. If the original value
// was a slice or map, these will be the same slice or map type.
//
// For a CREATE operation, the oldValue will always be nil. For an UPDATE
// operation, either value or oldValue may be nil, e.g. when adding or removing
// a value in a list-map. Validators which care about UPDATE operations should
// look at the opCtx argument to know which operation is being executed.
//
// Tightened validation (also known as ratcheting validation) is supported by
// defining a new validation function. For example:
//
// func TightenedMaxLength(ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *string) field.ErrorList {
// if oldValue != nil && len(MaxLength(ctx, op, fldPath, oldValue, nil)) > 0 {
// // old value is not valid, so this value skips the tightened validation
// return nil
// }
// return MaxLength(ctx, op, fldPath, value, nil)
// }
//
// In general, we cannot distinguish a non-specified slice or map from one that
// is specified but empty. Validators should not rely on nil values, but use
// len() instead.
package validate

View File

@ -0,0 +1,83 @@
/*
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 validate
import (
"context"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// CompareFunc is a function that compares two values of the same type.
type CompareFunc[T any] func(T, T) bool
// EachSliceVal validates each element of newSlice with the specified
// validation function. The comparison function is used to find the
// corresponding value in oldSlice. The value-type of the slices is assumed to
// not be nilable.
func EachSliceVal[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newSlice, oldSlice []T,
cmp CompareFunc[T], validator ValidateFunc[*T]) field.ErrorList {
var errs field.ErrorList
for i, val := range newSlice {
var old *T
if cmp != nil && len(oldSlice) > 0 {
old = lookup(oldSlice, val, cmp)
}
errs = append(errs, validator(ctx, op, fldPath.Index(i), &val, old)...)
}
return errs
}
// lookup returns a pointer to the first element in the list that matches the
// target, according to the provided comparison function, or else nil.
func lookup[T any](list []T, target T, cmp func(T, T) bool) *T {
for i := range list {
if cmp(list[i], target) {
return &list[i]
}
}
return nil
}
// EachMapVal validates each element of newMap with the specified validation
// function and, if the corresponding key is found in oldMap, the old value.
// The value-type of the slices is assumed to not be nilable.
func EachMapVal[K ~string, V any](ctx context.Context, op operation.Operation, fldPath *field.Path, newMap, oldMap map[K]V,
validator ValidateFunc[*V]) field.ErrorList {
var errs field.ErrorList
for key, val := range newMap {
var old *V
if o, found := oldMap[key]; found {
old = &o
}
errs = append(errs, validator(ctx, op, fldPath.Key(string(key)), &val, old)...)
}
return errs
}
// EachMapKey validates each element of newMap with the specified
// validation function. The oldMap argument is not used.
func EachMapKey[K ~string, T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newMap, oldMap map[K]T,
validator ValidateFunc[*K]) field.ErrorList {
var errs field.ErrorList
for key := range newMap {
// Note: the field path is the field, not the key.
errs = append(errs, validator(ctx, op, fldPath, &key, nil)...)
}
return errs
}

View File

@ -0,0 +1,60 @@
/*
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 validate
import (
"context"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// Immutable verifies that the specified value has not changed in the course of
// an update operation. It does nothing if the old value is not provided. If
// the caller needs to compare types that are not trivially comparable, they
// should use ImmutableNonComparable instead.
func Immutable[T comparable](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T) field.ErrorList {
if op.Type != operation.Update {
return nil
}
if value == nil && oldValue == nil {
return nil
}
if value == nil || oldValue == nil || *value != *oldValue {
return field.ErrorList{
field.Forbidden(fldPath, "field is immutable"),
}
}
return nil
}
// ImmutableNonComparable verifies that the specified value has not changed in
// the course of an update operation. It does nothing if the old value is not
// provided. Unlike Immutable, this function can be used with types that are
// not directly comparable, at the cost of performance.
func ImmutableNonComparable[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue T) field.ErrorList {
if op.Type != operation.Update {
return nil
}
if !equality.Semantic.DeepEqual(value, oldValue) {
return field.ErrorList{
field.Forbidden(fldPath, "field is immutable"),
}
}
return nil
}

View File

@ -0,0 +1,37 @@
/*
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 validate
import (
"context"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/api/validate/constraints"
"k8s.io/apimachinery/pkg/api/validate/content"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// Minimum verifies that the specified value is greater than or equal to min.
func Minimum[T constraints.Integer](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, min T) field.ErrorList {
if value == nil {
return nil
}
if *value < min {
return field.ErrorList{field.Invalid(fldPath, *value, content.MinError(min)).WithOrigin("minimum")}
}
return nil
}

View File

@ -0,0 +1,133 @@
/*
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 validate
import (
"context"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// RequiredValue verifies that the specified value is not the zero-value for
// its type.
func RequiredValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList {
var zero T
if *value != zero {
return nil
}
return field.ErrorList{field.Required(fldPath, "")}
}
// RequiredPointer verifies that the specified pointer is not nil.
func RequiredPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList {
if value != nil {
return nil
}
return field.ErrorList{field.Required(fldPath, "")}
}
// RequiredSlice verifies that the specified slice is not empty.
func RequiredSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList {
if len(value) > 0 {
return nil
}
return field.ErrorList{field.Required(fldPath, "")}
}
// RequiredMap verifies that the specified map is not empty.
func RequiredMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList {
if len(value) > 0 {
return nil
}
return field.ErrorList{field.Required(fldPath, "")}
}
// ForbiddenValue verifies that the specified value is the zero-value for its
// type.
func ForbiddenValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList {
var zero T
if *value == zero {
return nil
}
return field.ErrorList{field.Forbidden(fldPath, "")}
}
// ForbiddenPointer verifies that the specified pointer is nil.
func ForbiddenPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList {
if value == nil {
return nil
}
return field.ErrorList{field.Forbidden(fldPath, "")}
}
// ForbiddenSlice verifies that the specified slice is empty.
func ForbiddenSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList {
if len(value) == 0 {
return nil
}
return field.ErrorList{field.Forbidden(fldPath, "")}
}
// RequiredMap verifies that the specified map is empty.
func ForbiddenMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList {
if len(value) == 0 {
return nil
}
return field.ErrorList{field.Forbidden(fldPath, "")}
}
// OptionalValue verifies that the specified value is not the zero-value for
// its type. This is identical to RequiredValue, but the caller should treat an
// error here as an indication that the optional value was not specified.
func OptionalValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList {
var zero T
if *value != zero {
return nil
}
return field.ErrorList{field.Required(fldPath, "optional value was not specified")}
}
// OptionalPointer verifies that the specified pointer is not nil. This is
// identical to RequiredPointer, but the caller should treat an error here as an
// indication that the optional value was not specified.
func OptionalPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList {
if value != nil {
return nil
}
return field.ErrorList{field.Required(fldPath, "optional value was not specified")}
}
// OptionalSlice verifies that the specified slice is not empty. This is
// identical to RequiredSlice, but the caller should treat an error here as an
// indication that the optional value was not specified.
func OptionalSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList {
if len(value) > 0 {
return nil
}
return field.ErrorList{field.Required(fldPath, "optional value was not specified")}
}
// OptionalMap verifies that the specified map is not empty. This is identical
// to RequiredMap, but the caller should treat an error here as an indication that
// the optional value was not specified.
func OptionalMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList {
if len(value) > 0 {
return nil
}
return field.ErrorList{field.Required(fldPath, "optional value was not specified")}
}

View File

@ -0,0 +1,41 @@
/*
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 validate
import (
"context"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// GetFieldFunc is a function that extracts a field from a type and returns a
// nilable value.
type GetFieldFunc[Tstruct any, Tfield any] func(*Tstruct) Tfield
// Subfield validates a subfield of a struct against a validator function.
func Subfield[Tstruct any, Tfield any](ctx context.Context, op operation.Operation, fldPath *field.Path, newStruct, oldStruct *Tstruct,
fldName string, getField GetFieldFunc[Tstruct, Tfield], validator ValidateFunc[Tfield]) field.ErrorList {
var errs field.ErrorList
newVal := getField(newStruct)
var oldVal Tfield
if oldStruct != nil {
oldVal = getField(oldStruct)
}
errs = append(errs, validator(ctx, op, fldPath.Child(fldName), newVal, oldVal)...)
return errs
}

View File

@ -1,5 +1,5 @@
/*
Copyright 2018 The Kubernetes Authors.
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.
@ -14,20 +14,22 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
package validation
package validate
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"context"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// ValidateTableOptions returns any invalid flags on TableOptions.
func ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList {
var allErrs field.ErrorList
switch opts.IncludeObject {
case metav1.IncludeMetadata, metav1.IncludeNone, metav1.IncludeObject, "":
default:
allErrs = append(allErrs, field.Invalid(field.NewPath("includeObject"), opts.IncludeObject, "must be 'Metadata', 'Object', 'None', or empty"))
// FixedResult asserts a fixed boolean result. This is mostly useful for
// testing.
func FixedResult[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ T, result bool, arg string) field.ErrorList {
if result {
return nil
}
return field.ErrorList{
field.Invalid(fldPath, value, "forced failure: "+arg).WithOrigin("validateFalse"),
}
return allErrs
}

View File

@ -1,43 +0,0 @@
/*
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 asn1
import "encoding/asn1"
// These constants store suffixes for use with the CNCF Private Enterprise Number allocated to Kubernetes:
// https://www.iana.org/assignments/enterprise-numbers.txt
//
// Root: 1.3.6.1.4.1.57683
//
// Cloud Native Computing Foundation
const (
// single-value, string value
x509UIDSuffix = 2
)
func makeOID(suffix int) asn1.ObjectIdentifier {
return asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57683, suffix}
}
// X509UID returns an OID (1.3.6.1.4.1.57683.2) for an element of an x509 distinguished name representing a user UID.
// The UID is a unique value for a particular user that will change if the user is removed from the system
// and another user is added with the same username.
//
// This element must not appear more than once in a distinguished name, and the value must be a string
func X509UID() asn1.ObjectIdentifier {
return makeOID(x509UIDSuffix)
}

View File

@ -1,134 +0,0 @@
/*
Copyright 2023 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 waitgroup
import (
"context"
"fmt"
"sync"
)
// RateLimiter abstracts the rate limiter used by RateLimitedSafeWaitGroup.
// The implementation must be thread-safe.
type RateLimiter interface {
Wait(ctx context.Context) error
}
// RateLimiterFactoryFunc is used by the RateLimitedSafeWaitGroup to create a new
// instance of a RateLimiter that will be used to rate limit the return rate
// of the active number of request(s). 'count' is the number of requests in
// flight that are expected to invoke 'Done' on this wait group.
type RateLimiterFactoryFunc func(count int) (RateLimiter, context.Context, context.CancelFunc)
// RateLimitedSafeWaitGroup must not be copied after first use.
type RateLimitedSafeWaitGroup struct {
wg sync.WaitGroup
// Once Wait is initiated, all consecutive Done invocation will be
// rate limited using this rate limiter.
limiter RateLimiter
stopCtx context.Context
mu sync.Mutex
// wait indicate whether Wait is called, if true,
// then any Add with positive delta will return error.
wait bool
// number of request(s) currently using the wait group
count int
}
// Add adds delta, which may be negative, similar to sync.WaitGroup.
// If Add with a positive delta happens after Wait, it will return error,
// which prevent unsafe Add.
func (wg *RateLimitedSafeWaitGroup) Add(delta int) error {
wg.mu.Lock()
defer wg.mu.Unlock()
if wg.wait && delta > 0 {
return fmt.Errorf("add with positive delta after Wait is forbidden")
}
wg.wg.Add(delta)
wg.count += delta
return nil
}
// Done decrements the WaitGroup counter, rate limiting is applied only
// when the wait group is in waiting mode.
func (wg *RateLimitedSafeWaitGroup) Done() {
var limiter RateLimiter
func() {
wg.mu.Lock()
defer wg.mu.Unlock()
wg.count -= 1
if wg.wait {
// we are using the limiter outside the scope of the lock
limiter = wg.limiter
}
}()
defer wg.wg.Done()
if limiter != nil {
limiter.Wait(wg.stopCtx)
}
}
// Wait blocks until the WaitGroup counter is zero or a hard limit has elapsed.
// It returns the number of active request(s) accounted for at the time Wait
// has been invoked, number of request(s) that have drianed (done using the
// wait group immediately before Wait returns).
// Ideally, the both numbers returned should be equal, to indicate that all
// request(s) using the wait group have released their lock.
func (wg *RateLimitedSafeWaitGroup) Wait(limiterFactory RateLimiterFactoryFunc) (int, int, error) {
if limiterFactory == nil {
return 0, 0, fmt.Errorf("rate limiter factory must be specified")
}
var cancel context.CancelFunc
var countNow, countAfter int
func() {
wg.mu.Lock()
defer wg.mu.Unlock()
wg.limiter, wg.stopCtx, cancel = limiterFactory(wg.count)
countNow = wg.count
wg.wait = true
}()
defer cancel()
// there should be a hard stop, in case request(s) are not responsive
// enough to invoke Done before the grace period is over.
waitDoneCh := make(chan struct{})
go func() {
defer close(waitDoneCh)
wg.wg.Wait()
}()
var err error
select {
case <-wg.stopCtx.Done():
err = wg.stopCtx.Err()
case <-waitDoneCh:
}
func() {
wg.mu.Lock()
defer wg.mu.Unlock()
countAfter = wg.count
}()
return countNow, countAfter, err
}

View File

@ -1,57 +0,0 @@
/*
Copyright 2017 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 waitgroup
import (
"fmt"
"sync"
)
// SafeWaitGroup must not be copied after first use.
type SafeWaitGroup struct {
wg sync.WaitGroup
mu sync.RWMutex
// wait indicate whether Wait is called, if true,
// then any Add with positive delta will return error.
wait bool
}
// Add adds delta, which may be negative, similar to sync.WaitGroup.
// If Add with a positive delta happens after Wait, it will return error,
// which prevent unsafe Add.
func (wg *SafeWaitGroup) Add(delta int) error {
wg.mu.RLock()
defer wg.mu.RUnlock()
if wg.wait && delta > 0 {
return fmt.Errorf("add with positive delta after Wait is forbidden")
}
wg.wg.Add(delta)
return nil
}
// Done decrements the WaitGroup counter.
func (wg *SafeWaitGroup) Done() {
wg.wg.Done()
}
// Wait blocks until the WaitGroup counter is zero.
func (wg *SafeWaitGroup) Wait() {
wg.mu.Lock()
wg.wait = true
wg.mu.Unlock()
wg.wg.Wait()
}