code
stringlengths 12
335k
| docstring
stringlengths 20
20.8k
| func_name
stringlengths 1
105
| language
stringclasses 1
value | repo
stringclasses 498
values | path
stringlengths 5
172
| url
stringlengths 43
235
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func (b *backoffManager) Step() time.Duration {
b.lock.Lock()
defer b.lock.Unlock()
switch {
case b.resetInterval == 0:
b.backoff = b.initialBackoff
case b.clock.Now().Sub(b.lastStart) > b.resetInterval:
b.backoff = b.initialBackoff
b.lastStart = b.clock.Now()
}
return b.backoff.Step()
} | Step returns the expected next duration to wait. | Step | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func (b *backoffManager) Backoff() clock.Timer {
b.lock.Lock()
defer b.lock.Unlock()
if b.timer == nil {
b.timer = b.clock.NewTimer(b.Step())
} else {
b.timer.Reset(b.Step())
}
return b.timer
} | Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer
for exponential backoff. The returned timer must be drained before calling Backoff() the second
time. | Backoff | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func (b *backoffManager) Timer() Timer {
return DelayFunc(b.Step).Timer(b.clock)
} | Timer returns a new Timer instance that shares the clock and the reset behavior with all other
timers. | Timer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func NewExponentialBackoffManager(initBackoff, maxBackoff, resetDuration time.Duration, backoffFactor, jitter float64, c clock.Clock) BackoffManager {
return &exponentialBackoffManagerImpl{
backoff: &Backoff{
Duration: initBackoff,
Factor: backoffFactor,
Jitter: jitter,
// the current impl of wait.Backoff returns Backoff.Duration once steps are used up, which is not
// what we ideally need here, we set it to max int and assume we will never use up the steps
Steps: math.MaxInt32,
Cap: maxBackoff,
},
backoffTimer: nil,
initialBackoff: initBackoff,
lastBackoffStart: c.Now(),
backoffResetDuration: resetDuration,
clock: c,
}
} | NewExponentialBackoffManager returns a manager for managing exponential backoff. Each backoff is jittered and
backoff will not exceed the given max. If the backoff is not called within resetDuration, the backoff is reset.
This backoff manager is used to reduce load during upstream unhealthiness.
Deprecated: Will be removed when the legacy Poll methods are removed. Callers should construct a
Backoff struct, use DelayWithReset() to get a DelayFunc that periodically resets itself, and then
invoke Timer() when calling wait.BackoffUntil.
Instead of:
bm := wait.NewExponentialBackoffManager(init, max, reset, factor, jitter, clock)
...
wait.BackoffUntil(..., bm.Backoff, ...)
Use:
delayFn := wait.Backoff{
Duration: init,
Cap: max,
Steps: int(math.Ceil(float64(max) / float64(init))), // now a required argument
Factor: factor,
Jitter: jitter,
}.DelayWithReset(reset, clock)
wait.BackoffUntil(..., delayFn.Timer(), ...) | NewExponentialBackoffManager | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func (b *exponentialBackoffManagerImpl) Backoff() clock.Timer {
if b.backoffTimer == nil {
b.backoffTimer = b.clock.NewTimer(b.getNextBackoff())
} else {
b.backoffTimer.Reset(b.getNextBackoff())
}
return b.backoffTimer
} | Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for exponential backoff.
The returned timer must be drained before calling Backoff() the second time | Backoff | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func NewJitteredBackoffManager(duration time.Duration, jitter float64, c clock.Clock) BackoffManager {
return &jitteredBackoffManagerImpl{
clock: c,
duration: duration,
jitter: jitter,
backoffTimer: nil,
}
} | NewJitteredBackoffManager returns a BackoffManager that backoffs with given duration plus given jitter. If the jitter
is negative, backoff will not be jittered.
Deprecated: Will be removed when the legacy Poll methods are removed. Callers should construct a
Backoff struct and invoke Timer() when calling wait.BackoffUntil.
Instead of:
bm := wait.NewJitteredBackoffManager(duration, jitter, clock)
...
wait.BackoffUntil(..., bm.Backoff, ...)
Use:
wait.BackoffUntil(..., wait.Backoff{Duration: duration, Jitter: jitter}.Timer(), ...) | NewJitteredBackoffManager | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func (j *jitteredBackoffManagerImpl) Backoff() clock.Timer {
backoff := j.getNextBackoff()
if j.backoffTimer == nil {
j.backoffTimer = j.clock.NewTimer(backoff)
} else {
j.backoffTimer.Reset(backoff)
}
return j.backoffTimer
} | Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for jittered backoff.
The returned timer must be drained before calling Backoff() the second time | Backoff | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {
for backoff.Steps > 0 {
if ok, err := runConditionWithCrashProtection(condition); err != nil || ok {
return err
}
if backoff.Steps == 1 {
break
}
time.Sleep(backoff.Step())
}
return ErrWaitTimeout
} | ExponentialBackoff repeats a condition check with exponential backoff.
It repeatedly checks the condition and then sleeps, using `backoff.Step()`
to determine the length of the sleep and adjust Duration and Steps.
Stops and returns as soon as:
1. the condition check returns true or an error,
2. `backoff.Steps` checks of the condition have been done, or
3. a sleep truncated by the cap on duration has been completed.
In case (1) the returned error is what the condition function returned.
In all other cases, ErrWaitTimeout is returned.
Since backoffs are often subject to cancellation, we recommend using
ExponentialBackoffWithContext and passing a context to the method. | ExponentialBackoff | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func ExponentialBackoffWithContext(ctx context.Context, backoff Backoff, condition ConditionWithContextFunc) error {
for backoff.Steps > 0 {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if ok, err := runConditionWithCrashProtectionWithContext(ctx, condition); err != nil || ok {
return err
}
if backoff.Steps == 1 {
break
}
waitBeforeRetry := backoff.Step()
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(waitBeforeRetry):
}
}
return ErrWaitTimeout
} | ExponentialBackoffWithContext repeats a condition check with exponential backoff.
It immediately returns an error if the condition returns an error, the context is cancelled
or hits the deadline, or if the maximum attempts defined in backoff is exceeded (ErrWaitTimeout).
If an error is returned by the condition the backoff stops immediately. The condition will
never be invoked more than backoff.Steps times. | ExponentialBackoffWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go | Apache-2.0 |
func (g *Group) StartWithChannel(stopCh <-chan struct{}, f func(stopCh <-chan struct{})) {
g.Start(func() {
f(stopCh)
})
} | StartWithChannel starts f in a new goroutine in the group.
stopCh is passed to f as an argument. f should stop when stopCh is available. | StartWithChannel | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func (g *Group) StartWithContext(ctx context.Context, f func(context.Context)) {
g.Start(func() {
f(ctx)
})
} | StartWithContext starts f in a new goroutine in the group.
ctx is passed to f as an argument. f should stop when ctx.Done() is available. | StartWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func (g *Group) Start(f func()) {
g.wg.Add(1)
go func() {
defer g.wg.Done()
f()
}()
} | Start starts f in a new goroutine in the group. | Start | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func Forever(f func(), period time.Duration) {
Until(f, period, NeverStop)
} | Forever calls f every period for ever.
Forever is syntactic sugar on top of Until. | Forever | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func Jitter(duration time.Duration, maxFactor float64) time.Duration {
if maxFactor <= 0.0 {
maxFactor = 1.0
}
wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))
return wait
} | Jitter returns a time.Duration between duration and duration + maxFactor *
duration.
This allows clients to avoid converging on periodic behavior. If maxFactor
is 0.0, a suggested default value will be chosen. | Jitter | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func (cf ConditionFunc) WithContext() ConditionWithContextFunc {
return func(context.Context) (done bool, err error) {
return cf()
}
} | WithContext converts a ConditionFunc into a ConditionWithContextFunc | WithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func ContextForChannel(parentCh <-chan struct{}) context.Context {
return channelContext{stopCh: parentCh}
} | ContextForChannel provides a context that will be treated as cancelled
when the provided parentCh is closed. The implementation returns
context.Canceled for Err() if and only if the parentCh is closed. | ContextForChannel | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func runConditionWithCrashProtection(condition ConditionFunc) (bool, error) {
defer runtime.HandleCrash()
return condition()
} | runConditionWithCrashProtection runs a ConditionFunc with crash protection.
Deprecated: Will be removed when the legacy polling methods are removed. | runConditionWithCrashProtection | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func runConditionWithCrashProtectionWithContext(ctx context.Context, condition ConditionWithContextFunc) (bool, error) {
defer runtime.HandleCrash()
return condition(ctx)
} | runConditionWithCrashProtectionWithContext runs a ConditionWithContextFunc
with crash protection.
Deprecated: Will be removed when the legacy polling methods are removed. | runConditionWithCrashProtectionWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func (w waitFunc) WithContext() waitWithContextFunc {
return func(ctx context.Context) <-chan struct{} {
return w(ctx.Done())
}
} | WithContext converts the WaitFunc to an equivalent WaitWithContextFunc | WithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func waitForWithContext(ctx context.Context, wait waitWithContextFunc, fn ConditionWithContextFunc) error {
waitCtx, cancel := context.WithCancel(context.Background())
defer cancel()
c := wait(waitCtx)
for {
select {
case _, open := <-c:
ok, err := runConditionWithCrashProtectionWithContext(ctx, fn)
if err != nil {
return err
}
if ok {
return nil
}
if !open {
return ErrWaitTimeout
}
case <-ctx.Done():
// returning ctx.Err() will break backward compatibility, use new PollUntilContext*
// methods instead
return ErrWaitTimeout
}
}
} | waitForWithContext continually checks 'fn' as driven by 'wait'.
waitForWithContext gets a channel from 'wait()”, and then invokes 'fn'
once for every value placed on the channel and once more when the
channel is closed. If the channel is closed and 'fn'
returns false without error, waitForWithContext returns ErrWaitTimeout.
If 'fn' returns an error the loop ends and that error is returned. If
'fn' returns true the loop ends and nil is returned.
context.Canceled will be returned if the ctx.Done() channel is closed
without fn ever returning true.
When the ctx.Done() channel is closed, because the golang `select` statement is
"uniform pseudo-random", the `fn` might still run one or multiple times,
though eventually `waitForWithContext` will return.
Deprecated: Will be removed in a future release in favor of
loopConditionUntilContext. | waitForWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go | Apache-2.0 |
func loopConditionUntilContext(ctx context.Context, t Timer, immediate, sliding bool, condition ConditionWithContextFunc) error {
defer t.Stop()
var timeCh <-chan time.Time
doneCh := ctx.Done()
if !sliding {
timeCh = t.C()
}
// if immediate is true the condition is
// guaranteed to be executed at least once,
// if we haven't requested immediate execution, delay once
if immediate {
if ok, err := func() (bool, error) {
defer runtime.HandleCrash()
return condition(ctx)
}(); err != nil || ok {
return err
}
}
if sliding {
timeCh = t.C()
}
for {
// Wait for either the context to be cancelled or the next invocation be called
select {
case <-doneCh:
return ctx.Err()
case <-timeCh:
}
// IMPORTANT: Because there is no channel priority selection in golang
// it is possible for very short timers to "win" the race in the previous select
// repeatedly even when the context has been canceled. We therefore must
// explicitly check for context cancellation on every loop and exit if true to
// guarantee that we don't invoke condition more than once after context has
// been cancelled.
if err := ctx.Err(); err != nil {
return err
}
if !sliding {
t.Next()
}
if ok, err := func() (bool, error) {
defer runtime.HandleCrash()
return condition(ctx)
}(); err != nil || ok {
return err
}
if sliding {
t.Next()
}
}
} | loopConditionUntilContext executes the provided condition at intervals defined by
the provided timer until the provided context is cancelled, the condition returns
true, or the condition returns an error. If sliding is true, the period is computed
after condition runs. If it is false then period includes the runtime for condition.
If immediate is false the first delay happens before any call to condition, if
immediate is true the condition will be invoked before waiting and guarantees that
the condition is invoked at least once, regardless of whether the context has been
cancelled. The returned error is the error returned by the last condition or the
context error if the context was terminated.
This is the common loop construct for all polling in the wait package. | loopConditionUntilContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/loop.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/loop.go | Apache-2.0 |
func PollUntilContextCancel(ctx context.Context, interval time.Duration, immediate bool, condition ConditionWithContextFunc) error {
return loopConditionUntilContext(ctx, Backoff{Duration: interval}.Timer(), immediate, false, condition)
} | PollUntilContextCancel tries a condition func until it returns true, an error, or the context
is cancelled or hits a deadline. condition will be invoked after the first interval if the
context is not cancelled first. The returned error will be from ctx.Err(), the condition's
err return value, or nil. If invoking condition takes longer than interval the next condition
will be invoked immediately. When using very short intervals, condition may be invoked multiple
times before a context cancellation is detected. If immediate is true, condition will be
invoked before waiting and guarantees that condition is invoked at least once, regardless of
whether the context has been cancelled. | PollUntilContextCancel | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollUntilContextTimeout(ctx context.Context, interval, timeout time.Duration, immediate bool, condition ConditionWithContextFunc) error {
deadlineCtx, deadlineCancel := context.WithTimeout(ctx, timeout)
defer deadlineCancel()
return loopConditionUntilContext(deadlineCtx, Backoff{Duration: interval}.Timer(), immediate, false, condition)
} | PollUntilContextTimeout will terminate polling after timeout duration by setting a context
timeout. This is provided as a convenience function for callers not currently executing under
a deadline and is equivalent to:
deadlineCtx, deadlineCancel := context.WithTimeout(ctx, timeout)
err := PollUntilContextCancel(deadlineCtx, interval, immediate, condition)
The deadline context will be cancelled if the Poll succeeds before the timeout, simplifying
inline usage. All other behavior is identical to PollUntilContextCancel. | PollUntilContextTimeout | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func Poll(interval, timeout time.Duration, condition ConditionFunc) error {
return PollWithContext(context.Background(), interval, timeout, condition.WithContext())
} | Poll tries a condition func until it returns true, an error, or the timeout
is reached.
Poll always waits the interval before the run of 'condition'.
'condition' will always be invoked at least once.
Some intervals may be missed if the condition takes too long or the time
window is too short.
If you want to Poll something forever, see PollInfinite.
Deprecated: This method does not return errors from context, use PollUntilContextTimeout.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | Poll | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error {
return poll(ctx, false, poller(interval, timeout), condition)
} | PollWithContext tries a condition func until it returns true, an error,
or when the context expires or the timeout is reached, whichever
happens first.
PollWithContext always waits the interval before the run of 'condition'.
'condition' will always be invoked at least once.
Some intervals may be missed if the condition takes too long or the time
window is too short.
If you want to Poll something forever, see PollInfinite.
Deprecated: This method does not return errors from context, use PollUntilContextTimeout.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
return PollUntilWithContext(ContextForChannel(stopCh), interval, condition.WithContext())
} | PollUntil tries a condition func until it returns true, an error or stopCh is
closed.
PollUntil always waits interval before the first run of 'condition'.
'condition' will always be invoked at least once.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollUntil | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
return poll(ctx, false, poller(interval, 0), condition)
} | PollUntilWithContext tries a condition func until it returns true,
an error or the specified context is cancelled or expired.
PollUntilWithContext always waits interval before the first run of 'condition'.
'condition' will always be invoked at least once.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollUntilWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollInfinite(interval time.Duration, condition ConditionFunc) error {
return PollInfiniteWithContext(context.Background(), interval, condition.WithContext())
} | PollInfinite tries a condition func until it returns true or an error
PollInfinite always waits the interval before the run of 'condition'.
Some intervals may be missed if the condition takes too long or the time
window is too short.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollInfinite | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
return poll(ctx, false, poller(interval, 0), condition)
} | PollInfiniteWithContext tries a condition func until it returns true or an error
PollInfiniteWithContext always waits the interval before the run of 'condition'.
Some intervals may be missed if the condition takes too long or the time
window is too short.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollInfiniteWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error {
return PollImmediateWithContext(context.Background(), interval, timeout, condition.WithContext())
} | PollImmediate tries a condition func until it returns true, an error, or the timeout
is reached.
PollImmediate always checks 'condition' before waiting for the interval. 'condition'
will always be invoked at least once.
Some intervals may be missed if the condition takes too long or the time
window is too short.
If you want to immediately Poll something forever, see PollImmediateInfinite.
Deprecated: This method does not return errors from context, use PollUntilContextTimeout.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollImmediate | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollImmediateWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error {
return poll(ctx, true, poller(interval, timeout), condition)
} | PollImmediateWithContext tries a condition func until it returns true, an error,
or the timeout is reached or the specified context expires, whichever happens first.
PollImmediateWithContext always checks 'condition' before waiting for the interval.
'condition' will always be invoked at least once.
Some intervals may be missed if the condition takes too long or the time
window is too short.
If you want to immediately Poll something forever, see PollImmediateInfinite.
Deprecated: This method does not return errors from context, use PollUntilContextTimeout.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollImmediateWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollImmediateUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
return PollImmediateUntilWithContext(ContextForChannel(stopCh), interval, condition.WithContext())
} | PollImmediateUntil tries a condition func until it returns true, an error or stopCh is closed.
PollImmediateUntil runs the 'condition' before waiting for the interval.
'condition' will always be invoked at least once.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollImmediateUntil | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollImmediateUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
return poll(ctx, true, poller(interval, 0), condition)
} | PollImmediateUntilWithContext tries a condition func until it returns true,
an error or the specified context is cancelled or expired.
PollImmediateUntilWithContext runs the 'condition' before waiting for the interval.
'condition' will always be invoked at least once.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollImmediateUntilWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error {
return PollImmediateInfiniteWithContext(context.Background(), interval, condition.WithContext())
} | PollImmediateInfinite tries a condition func until it returns true or an error
PollImmediateInfinite runs the 'condition' before waiting for the interval.
Some intervals may be missed if the condition takes too long or the time
window is too short.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollImmediateInfinite | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func PollImmediateInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
return poll(ctx, true, poller(interval, 0), condition)
} | PollImmediateInfiniteWithContext tries a condition func until it returns true
or an error or the specified context gets cancelled or expired.
PollImmediateInfiniteWithContext runs the 'condition' before waiting for the interval.
Some intervals may be missed if the condition takes too long or the time
window is too short.
Deprecated: This method does not return errors from context, use PollUntilContextCancel.
Note that the new method will no longer return ErrWaitTimeout and instead return errors
defined by the context package. Will be removed in a future release. | PollImmediateInfiniteWithContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func poll(ctx context.Context, immediate bool, wait waitWithContextFunc, condition ConditionWithContextFunc) error {
if immediate {
done, err := runConditionWithCrashProtectionWithContext(ctx, condition)
if err != nil {
return err
}
if done {
return nil
}
}
select {
case <-ctx.Done():
// returning ctx.Err() will break backward compatibility, use new PollUntilContext*
// methods instead
return ErrWaitTimeout
default:
return waitForWithContext(ctx, wait, condition)
}
} | Internally used, each of the public 'Poll*' function defined in this
package should invoke this internal function with appropriate parameters.
ctx: the context specified by the caller, for infinite polling pass
a context that never gets cancelled or expired.
immediate: if true, the 'condition' will be invoked before waiting for the interval,
in this case 'condition' will always be invoked at least once.
wait: user specified WaitFunc function that controls at what interval the condition
function should be invoked periodically and whether it is bound by a timeout.
condition: user specified ConditionWithContextFunc function.
Deprecated: will be removed in favor of loopConditionUntilContext. | poll | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func poller(interval, timeout time.Duration) waitWithContextFunc {
return waitWithContextFunc(func(ctx context.Context) <-chan struct{} {
ch := make(chan struct{})
go func() {
defer close(ch)
tick := time.NewTicker(interval)
defer tick.Stop()
var after <-chan time.Time
if timeout != 0 {
// time.After is more convenient, but it
// potentially leaves timers around much longer
// than necessary if we exit early.
timer := time.NewTimer(timeout)
after = timer.C
defer timer.Stop()
}
for {
select {
case <-tick.C:
// If the consumer isn't ready for this signal drop it and
// check the other channels.
select {
case ch <- struct{}{}:
default:
}
case <-after:
return
case <-ctx.Done():
return
}
}
}()
return ch
})
} | poller returns a WaitFunc that will send to the channel every interval until
timeout has elapsed and then closes the channel.
Over very short intervals you may receive no ticks before the channel is
closed. A timeout of 0 is interpreted as an infinity, and in such a case
it would be the caller's responsibility to close the done channel.
Failure to do so would result in a leaked goroutine.
Output ticks are not buffered. If the channel is not ready to receive an
item, the tick is skipped.
Deprecated: Will be removed in a future release. | poller | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go | Apache-2.0 |
func Interrupted(err error) bool {
switch {
case errors.Is(err, errWaitTimeout),
errors.Is(err, context.Canceled),
errors.Is(err, context.DeadlineExceeded):
return true
default:
return false
}
} | Interrupted returns true if the error indicates a Poll, ExponentialBackoff, or
Until loop exited for any reason besides the condition returning true or an
error. A loop is considered interrupted if the calling context is cancelled,
the context reaches its deadline, or a backoff reaches its maximum allowed
steps.
Callers should use this method instead of comparing the error value directly to
ErrWaitTimeout, as methods that cancel a context may not return that error.
Instead of:
err := wait.Poll(...)
if err == wait.ErrWaitTimeout {
log.Infof("Wait for operation exceeded")
} else ...
Use:
err := wait.Poll(...)
if wait.Interrupted(err) {
log.Infof("Wait for operation exceeded")
} else ... | Interrupted | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/error.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/error.go | Apache-2.0 |
func ErrorInterrupted(cause error) error {
switch cause.(type) {
case errInterrupted:
// no need to wrap twice since errInterrupted is only needed
// once in a chain
return cause
default:
return errInterrupted{cause}
} | ErrorInterrupted returns an error that indicates the wait was ended
early for a given reason. If no cause is provided a generic error
will be used but callers are encouraged to provide a real cause for
clarity in debugging. | ErrorInterrupted | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/error.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/error.go | Apache-2.0 |
func (fn DelayFunc) Timer(c clock.Clock) Timer {
return &variableTimer{fn: fn, new: c.NewTimer}
} | Timer takes an arbitrary delay function and returns a timer that can handle arbitrary interval changes.
Use Backoff{...}.Timer() for simple delays and more efficient timers. | Timer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/delay.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/delay.go | Apache-2.0 |
func (fn DelayFunc) Until(ctx context.Context, immediate, sliding bool, condition ConditionWithContextFunc) error {
return loopConditionUntilContext(ctx, &variableTimer{fn: fn, new: internalClock.NewTimer}, immediate, sliding, condition)
} | Until takes an arbitrary delay function and runs until cancelled or the condition indicates exit. This
offers all of the functionality of the methods in this package. | Until | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/delay.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/delay.go | Apache-2.0 |
func (fn DelayFunc) Concurrent() DelayFunc {
var lock sync.Mutex
return func() time.Duration {
lock.Lock()
defer lock.Unlock()
return fn()
}
} | Concurrent returns a version of this DelayFunc that is safe for use by multiple goroutines that
wish to share a single delay timer. | Concurrent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/delay.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/delay.go | Apache-2.0 |
func newNoopTimer() noopTimer {
ch := make(chan time.Time)
close(ch)
return noopTimer{closedCh: ch}
} | newNoopTimer creates a timer with a unique channel to avoid contention
for the channel's lock across multiple unrelated timers. | newNoopTimer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/wait/timer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/wait/timer.go | Apache-2.0 |
func NewAggregate(errlist []error) Aggregate {
if len(errlist) == 0 {
return nil
}
// In case of input error list contains nil
var errs []error
for _, e := range errlist {
if e != nil {
errs = append(errs, e)
}
}
if len(errs) == 0 {
return nil
}
return aggregate(errs)
} | NewAggregate converts a slice of errors into an Aggregate interface, which
is itself an implementation of the error interface. If the slice is empty,
this returns nil.
It will check if any of the element of input error list is nil, to avoid
nil pointer panic when call Error(). | NewAggregate | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func (agg aggregate) Error() string {
if len(agg) == 0 {
// This should never happen, really.
return ""
}
if len(agg) == 1 {
return agg[0].Error()
}
seenerrs := sets.NewString()
result := ""
agg.visit(func(err error) bool {
msg := err.Error()
if seenerrs.Has(msg) {
return false
}
seenerrs.Insert(msg)
if len(seenerrs) > 1 {
result += ", "
}
result += msg
return false
})
if len(seenerrs) == 1 {
return result
}
return "[" + result + "]"
} | Error is part of the error interface. | Error | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func FilterOut(err error, fns ...Matcher) error {
if err == nil {
return nil
}
if agg, ok := err.(Aggregate); ok {
return NewAggregate(filterErrors(agg.Errors(), fns...))
}
if !matchesError(err, fns...) {
return err
}
return nil
} | FilterOut removes all errors that match any of the matchers from the input
error. If the input is a singular error, only that error is tested. If the
input implements the Aggregate interface, the list of errors will be
processed recursively.
This can be used, for example, to remove known-OK errors (such as io.EOF or
os.PathNotFound) from a list of errors. | FilterOut | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func matchesError(err error, fns ...Matcher) bool {
for _, fn := range fns {
if fn(err) {
return true
}
}
return false
} | matchesError returns true if any Matcher returns true | matchesError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func filterErrors(list []error, fns ...Matcher) []error {
result := []error{}
for _, err := range list {
r := FilterOut(err, fns...)
if r != nil {
result = append(result, r)
}
}
return result
} | filterErrors returns any errors (or nested errors, if the list contains
nested Errors) for which all fns return false. If no errors
remain a nil list is returned. The resulting slice will have all
nested slices flattened as a side effect. | filterErrors | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func Flatten(agg Aggregate) Aggregate {
result := []error{}
if agg == nil {
return nil
}
for _, err := range agg.Errors() {
if a, ok := err.(Aggregate); ok {
r := Flatten(a)
if r != nil {
result = append(result, r.Errors()...)
}
} else {
if err != nil {
result = append(result, err)
}
}
}
return NewAggregate(result)
} | Flatten takes an Aggregate, which may hold other Aggregates in arbitrary
nesting, and flattens them all into a single Aggregate, recursively. | Flatten | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate {
if m == nil {
return nil
}
result := make([]error, 0, len(m))
for errStr, count := range m {
var countStr string
if count > 1 {
countStr = fmt.Sprintf(" (repeated %v times)", count)
}
result = append(result, fmt.Errorf("%v%v", errStr, countStr))
}
return NewAggregate(result)
} | CreateAggregateFromMessageCountMap converts MessageCountMap Aggregate | CreateAggregateFromMessageCountMap | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func Reduce(err error) error {
if agg, ok := err.(Aggregate); ok && err != nil {
switch len(agg.Errors()) {
case 1:
return agg.Errors()[0]
case 0:
return nil
}
}
return err
} | Reduce will return err or nil, if err is an Aggregate and only has one item,
the first item in the aggregate. | Reduce | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func AggregateGoroutines(funcs ...func() error) Aggregate {
errChan := make(chan error, len(funcs))
for _, f := range funcs {
go func(f func() error) { errChan <- f() }(f)
}
errs := make([]error, 0)
for i := 0; i < cap(errChan); i++ {
if err := <-errChan; err != nil {
errs = append(errs, err)
}
}
return NewAggregate(errs)
} | AggregateGoroutines runs the provided functions in parallel, stuffing all
non-nil errors into the returned Aggregate.
Returns nil if all the functions complete successfully. | AggregateGoroutines | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go | Apache-2.0 |
func GetNameFromCallsite(ignoredPackages ...string) string {
name := "????"
const maxStack = 10
for i := 1; i < maxStack; i++ {
_, file, line, ok := goruntime.Caller(i)
if !ok {
file, line, ok = extractStackCreator()
if !ok {
break
}
i += maxStack
}
if hasPackage(file, append(ignoredPackages, "/runtime/asm_")) {
continue
}
file = trimPackagePrefix(file)
name = fmt.Sprintf("%s:%d", file, line)
break
}
return name
} | GetNameFromCallsite walks back through the call stack until we find a caller from outside of the ignoredPackages
it returns back a shortpath/filename:line to aid in identification of this reflector when it starts logging | GetNameFromCallsite | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | Apache-2.0 |
func hasPackage(file string, ignoredPackages []string) bool {
for _, ignoredPackage := range ignoredPackages {
if strings.Contains(file, ignoredPackage) {
return true
}
}
return false
} | hasPackage returns true if the file is in one of the ignored packages. | hasPackage | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | Apache-2.0 |
func trimPackagePrefix(file string) string {
if l := strings.LastIndex(file, "/vendor/"); l >= 0 {
return file[l+len("/vendor/"):]
}
if l := strings.LastIndex(file, "/src/"); l >= 0 {
return file[l+5:]
}
if l := strings.LastIndex(file, "/pkg/"); l >= 0 {
return file[l+1:]
}
return file
} | trimPackagePrefix reduces duplicate values off the front of a package name. | trimPackagePrefix | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | Apache-2.0 |
func extractStackCreator() (string, int, bool) {
stack := debug.Stack()
matches := stackCreator.FindStringSubmatch(string(stack))
if len(matches) != 4 {
return "", 0, false
}
line, err := strconv.Atoi(matches[3])
if err != nil {
return "", 0, false
}
return matches[2], line, true
} | extractStackCreator retrieves the goroutine file and line that launched this stack. Returns false
if the creator cannot be located.
TODO: Go does not expose this via runtime https://github.com/golang/go/issues/11440 | extractStackCreator | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go | Apache-2.0 |
func NewEncoder(w io.Writer) *json.Encoder {
return json.NewEncoder(w)
} | NewEncoder delegates to json.NewEncoder
It is only here so this package can be a drop-in for common encoding/json uses | NewEncoder | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/json/json.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/json/json.go | Apache-2.0 |
func Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
} | Marshal delegates to json.Marshal
It is only here so this package can be a drop-in for common encoding/json uses | Marshal | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/json/json.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/json/json.go | Apache-2.0 |
func Unmarshal(data []byte, v interface{}) error {
return kjson.UnmarshalCaseSensitivePreserveInts(data, v)
} | Unmarshal unmarshals the given data.
Object keys are case-sensitive.
Numbers decoded into interface{} fields are converted to int64 or float64. | Unmarshal | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/json/json.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/json/json.go | Apache-2.0 |
func ConvertInterfaceNumbers(v *interface{}, depth int) error {
var err error
switch v2 := (*v).(type) {
case json.Number:
*v, err = convertNumber(v2)
case map[string]interface{}:
err = ConvertMapNumbers(v2, depth+1)
case []interface{}:
err = ConvertSliceNumbers(v2, depth+1)
} | ConvertInterfaceNumbers converts any json.Number values to int64 or float64.
Values which are map[string]interface{} or []interface{} are recursively visited | ConvertInterfaceNumbers | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/json/json.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/json/json.go | Apache-2.0 |
func ConvertMapNumbers(m map[string]interface{}, depth int) error {
if depth > maxDepth {
return fmt.Errorf("exceeded max depth of %d", maxDepth)
}
var err error
for k, v := range m {
switch v := v.(type) {
case json.Number:
m[k], err = convertNumber(v)
case map[string]interface{}:
err = ConvertMapNumbers(v, depth+1)
case []interface{}:
err = ConvertSliceNumbers(v, depth+1)
}
if err != nil {
return err
}
} | ConvertMapNumbers traverses the map, converting any json.Number values to int64 or float64.
values which are map[string]interface{} or []interface{} are recursively visited | ConvertMapNumbers | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/json/json.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/json/json.go | Apache-2.0 |
func ConvertSliceNumbers(s []interface{}, depth int) error {
if depth > maxDepth {
return fmt.Errorf("exceeded max depth of %d", maxDepth)
}
var err error
for i, v := range s {
switch v := v.(type) {
case json.Number:
s[i], err = convertNumber(v)
case map[string]interface{}:
err = ConvertMapNumbers(v, depth+1)
case []interface{}:
err = ConvertSliceNumbers(v, depth+1)
}
if err != nil {
return err
}
} | ConvertSliceNumbers traverses the slice, converting any json.Number values to int64 or float64.
values which are map[string]interface{} or []interface{} are recursively visited | ConvertSliceNumbers | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/json/json.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/json/json.go | Apache-2.0 |
func convertNumber(n json.Number) (interface{}, error) {
// Attempt to convert to an int64 first
if i, err := n.Int64(); err == nil {
return i, nil
}
// Return a float64 (default json.Decode() behavior)
// An overflow will return an error
return n.Float64()
} | convertNumber converts a json.Number to an int64 or float64, or returns an error | convertNumber | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/json/json.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/json/json.go | Apache-2.0 |
func FromInt(val int) IntOrString {
if val > math.MaxInt32 || val < math.MinInt32 {
klog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack())
}
return IntOrString{Type: Int, IntVal: int32(val)}
} | FromInt creates an IntOrString object with an int32 value. It is
your responsibility not to call this method with a value greater
than int32.
Deprecated: use FromInt32 instead. | FromInt | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func FromInt32(val int32) IntOrString {
return IntOrString{Type: Int, IntVal: val}
} | FromInt32 creates an IntOrString object with an int32 value. | FromInt32 | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func FromString(val string) IntOrString {
return IntOrString{Type: String, StrVal: val}
} | FromString creates an IntOrString object with a string value. | FromString | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func Parse(val string) IntOrString {
i, err := strconv.ParseInt(val, 10, 32)
if err != nil {
return FromString(val)
}
return FromInt32(int32(i))
} | Parse the given string and try to convert it to an int32 integer before
setting it as a string value. | Parse | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (intstr *IntOrString) UnmarshalJSON(value []byte) error {
if value[0] == '"' {
intstr.Type = String
return json.Unmarshal(value, &intstr.StrVal)
}
intstr.Type = Int
return json.Unmarshal(value, &intstr.IntVal)
} | UnmarshalJSON implements the json.Unmarshaller interface. | UnmarshalJSON | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (intstr *IntOrString) String() string {
if intstr == nil {
return "<nil>"
}
if intstr.Type == String {
return intstr.StrVal
}
return strconv.Itoa(intstr.IntValue())
} | String returns the string value, or the Itoa of the int value. | String | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (intstr *IntOrString) IntValue() int {
if intstr.Type == String {
i, _ := strconv.Atoi(intstr.StrVal)
return i
}
return int(intstr.IntVal)
} | IntValue returns the IntVal if type Int, or if
it is a String, will attempt a conversion to int,
returning 0 if a parsing error occurs. | IntValue | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (intstr IntOrString) MarshalJSON() ([]byte, error) {
switch intstr.Type {
case Int:
return json.Marshal(intstr.IntVal)
case String:
return json.Marshal(intstr.StrVal)
default:
return []byte{}, fmt.Errorf("impossible IntOrString.Type")
}
} | MarshalJSON implements the json.Marshaller interface. | MarshalJSON | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (IntOrString) OpenAPISchemaType() []string { return []string{"string"} } | OpenAPISchemaType is used by the kube-openapi generator when constructing
the OpenAPI spec of this type.
See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators | OpenAPISchemaType | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (IntOrString) OpenAPISchemaFormat() string { return "int-or-string" } | OpenAPISchemaFormat is used by the kube-openapi generator when constructing
the OpenAPI spec of this type. | OpenAPISchemaFormat | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (IntOrString) OpenAPIV3OneOfTypes() []string { return []string{"integer", "string"} } | OpenAPIV3OneOfTypes is used by the kube-openapi generator when constructing
the OpenAPI v3 spec of this type. | OpenAPIV3OneOfTypes | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func GetScaledValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) {
if intOrPercent == nil {
return 0, errors.New("nil value for IntOrString")
}
value, isPercent, err := getIntOrPercentValueSafely(intOrPercent)
if err != nil {
return 0, fmt.Errorf("invalid value for IntOrString: %v", err)
}
if isPercent {
if roundUp {
value = int(math.Ceil(float64(value) * (float64(total)) / 100))
} else {
value = int(math.Floor(float64(value) * (float64(total)) / 100))
}
}
return value, nil
} | GetScaledValueFromIntOrPercent is meant to replace GetValueFromIntOrPercent.
This method returns a scaled value from an IntOrString type. If the IntOrString
is a percentage string value it's treated as a percentage and scaled appropriately
in accordance to the total, if it's an int value it's treated as a simple value and
if it is a string value which is either non-numeric or numeric but lacking a trailing '%' it returns an error. | GetScaledValueFromIntOrPercent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func GetValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) {
if intOrPercent == nil {
return 0, errors.New("nil value for IntOrString")
}
value, isPercent, err := getIntOrPercentValue(intOrPercent)
if err != nil {
return 0, fmt.Errorf("invalid value for IntOrString: %v", err)
}
if isPercent {
if roundUp {
value = int(math.Ceil(float64(value) * (float64(total)) / 100))
} else {
value = int(math.Floor(float64(value) * (float64(total)) / 100))
}
}
return value, nil
} | GetValueFromIntOrPercent was deprecated in favor of
GetScaledValueFromIntOrPercent. This method was treating all int as a numeric value and all
strings with or without a percent symbol as a percentage value.
Deprecated | GetValueFromIntOrPercent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func getIntOrPercentValue(intOrStr *IntOrString) (int, bool, error) {
switch intOrStr.Type {
case Int:
return intOrStr.IntValue(), false, nil
case String:
s := strings.Replace(intOrStr.StrVal, "%", "", -1)
v, err := strconv.Atoi(s)
if err != nil {
return 0, false, fmt.Errorf("invalid value %q: %v", intOrStr.StrVal, err)
}
return int(v), true, nil
}
return 0, false, fmt.Errorf("invalid type: neither int nor percentage")
} | getIntOrPercentValue is a legacy function and only meant to be called by GetValueFromIntOrPercent
For a more correct implementation call getIntOrPercentSafely | getIntOrPercentValue | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go | Apache-2.0 |
func (intstr *IntOrString) Fuzz(c fuzz.Continue) {
if intstr == nil {
return
}
if c.RandBool() {
intstr.Type = Int
c.Fuzz(&intstr.IntVal)
intstr.StrVal = ""
} else {
intstr.Type = String
intstr.IntVal = 0
c.Fuzz(&intstr.StrVal)
}
} | Fuzz satisfies fuzz.Interface | Fuzz | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go | Apache-2.0 |
func NewLRUExpireCache(maxSize int) *LRUExpireCache {
return NewLRUExpireCacheWithClock(maxSize, realClock{})
} | NewLRUExpireCache creates an expiring cache with the given size | NewLRUExpireCache | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | Apache-2.0 |
func NewLRUExpireCacheWithClock(maxSize int, clock Clock) *LRUExpireCache {
if maxSize <= 0 {
panic("maxSize must be > 0")
}
return &LRUExpireCache{
clock: clock,
maxSize: maxSize,
entries: map[interface{}]*list.Element{},
}
} | NewLRUExpireCacheWithClock creates an expiring cache with the given size, using the specified clock to obtain the current time. | NewLRUExpireCacheWithClock | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | Apache-2.0 |
func (c *LRUExpireCache) Add(key interface{}, value interface{}, ttl time.Duration) {
c.lock.Lock()
defer c.lock.Unlock()
// Key already exists
oldElement, ok := c.entries[key]
if ok {
c.evictionList.MoveToFront(oldElement)
oldElement.Value.(*cacheEntry).value = value
oldElement.Value.(*cacheEntry).expireTime = c.clock.Now().Add(ttl)
return
}
// Make space if necessary
if c.evictionList.Len() >= c.maxSize {
toEvict := c.evictionList.Back()
c.evictionList.Remove(toEvict)
delete(c.entries, toEvict.Value.(*cacheEntry).key)
}
// Add new entry
entry := &cacheEntry{
key: key,
value: value,
expireTime: c.clock.Now().Add(ttl),
}
element := c.evictionList.PushFront(entry)
c.entries[key] = element
} | Add adds the value to the cache at key with the specified maximum duration. | Add | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | Apache-2.0 |
func (c *LRUExpireCache) Get(key interface{}) (interface{}, bool) {
c.lock.Lock()
defer c.lock.Unlock()
element, ok := c.entries[key]
if !ok {
return nil, false
}
if c.clock.Now().After(element.Value.(*cacheEntry).expireTime) {
c.evictionList.Remove(element)
delete(c.entries, key)
return nil, false
}
c.evictionList.MoveToFront(element)
return element.Value.(*cacheEntry).value, true
} | Get returns the value at the specified key from the cache if it exists and is not
expired, or returns false. | Get | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | Apache-2.0 |
func (c *LRUExpireCache) Remove(key interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
element, ok := c.entries[key]
if !ok {
return
}
c.evictionList.Remove(element)
delete(c.entries, key)
} | Remove removes the specified key from the cache if it exists | Remove | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | Apache-2.0 |
func (c *LRUExpireCache) RemoveAll(predicate func(key any) bool) {
c.lock.Lock()
defer c.lock.Unlock()
for key, element := range c.entries {
if predicate(key) {
c.evictionList.Remove(element)
delete(c.entries, key)
}
}
} | RemoveAll removes all keys that match predicate. | RemoveAll | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | Apache-2.0 |
func (c *LRUExpireCache) Keys() []interface{} {
c.lock.Lock()
defer c.lock.Unlock()
now := c.clock.Now()
val := make([]interface{}, 0, c.evictionList.Len())
for element := c.evictionList.Back(); element != nil; element = element.Prev() {
// Only return unexpired keys
if !now.After(element.Value.(*cacheEntry).expireTime) {
val = append(val, element.Value.(*cacheEntry).key)
}
}
return val
} | Keys returns all unexpired keys in the cache.
Keep in mind that subsequent calls to Get() for any of the returned keys
might return "not found".
Keys are returned ordered from least recently used to most recently used. | Keys | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go | Apache-2.0 |
func NewExpiring() *Expiring {
return NewExpiringWithClock(clock.RealClock{})
} | NewExpiring returns an initialized expiring cache. | NewExpiring | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | Apache-2.0 |
func NewExpiringWithClock(clock clock.Clock) *Expiring {
return &Expiring{
clock: clock,
cache: make(map[interface{}]entry),
}
} | NewExpiringWithClock is like NewExpiring but allows passing in a custom
clock for testing. | NewExpiringWithClock | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | Apache-2.0 |
func (c *Expiring) Get(key interface{}) (val interface{}, ok bool) {
c.mu.RLock()
defer c.mu.RUnlock()
e, ok := c.cache[key]
if !ok {
return nil, false
}
if !c.AllowExpiredGet && !c.clock.Now().Before(e.expiry) {
return nil, false
}
return e.val, true
} | Get looks up an entry in the cache. | Get | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | Apache-2.0 |
func (c *Expiring) Set(key interface{}, val interface{}, ttl time.Duration) {
now := c.clock.Now()
expiry := now.Add(ttl)
c.mu.Lock()
defer c.mu.Unlock()
c.generation++
c.cache[key] = entry{
val: val,
expiry: expiry,
generation: c.generation,
}
// Run GC inline before pushing the new entry.
c.gc(now)
heap.Push(&c.heap, &expiringHeapEntry{
key: key,
expiry: expiry,
generation: c.generation,
})
} | Set sets a key/value/expiry entry in the map, overwriting any previous entry
with the same key. The entry expires at the given expiry time, but its TTL
may be lengthened or shortened by additional calls to Set(). Garbage
collection of expired entries occurs during calls to Set(), however calls to
Get() will not return expired entries that have not yet been garbage
collected. | Set | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | Apache-2.0 |
func (c *Expiring) Delete(key interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.del(key, 0)
} | Delete deletes an entry in the map. | Delete | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | Apache-2.0 |
func (c *Expiring) del(key interface{}, generation uint64) {
e, ok := c.cache[key]
if !ok {
return
}
if generation != 0 && generation != e.generation {
return
}
delete(c.cache, key)
} | del deletes the entry for the given key. The generation argument is the
generation of the entry that should be deleted. If the generation has been
changed (e.g. if a set has occurred on an existing element but the old
cleanup still runs), this is a noop. If the generation argument is 0, the
entry's generation is ignored and the entry is deleted.
del must be called under the write lock. | del | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | Apache-2.0 |
func (c *Expiring) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.cache)
} | Len returns the number of items in the cache. | Len | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go | Apache-2.0 |
func HandleCrash(additionalHandlers ...func(interface{})) {
if r := recover(); r != nil {
for _, fn := range PanicHandlers {
fn(r)
}
for _, fn := range additionalHandlers {
fn(r)
}
if ReallyCrash {
// Actually proceed to panic.
panic(r)
}
}
} | HandleCrash simply catches a crash and logs an error. Meant to be called via
defer. Additional context-specific handlers can be provided, and will be
called in case of panic. HandleCrash actually crashes, after calling the
handlers and logging the panic message.
E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. | HandleCrash | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
func logPanic(r interface{}) {
if r == http.ErrAbortHandler {
// honor the http.ErrAbortHandler sentinel panic value:
// ErrAbortHandler is a sentinel panic value to abort a handler.
// While any panic from ServeHTTP aborts the response to the client,
// panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log.
return
}
// Same as stdlib http server code. Manually allocate stack trace buffer size
// to prevent excessively large logs
const size = 64 << 10
stacktrace := make([]byte, size)
stacktrace = stacktrace[:runtime.Stack(stacktrace, false)]
if _, ok := r.(string); ok {
klog.Errorf("Observed a panic: %s\n%s", r, stacktrace)
} else {
klog.Errorf("Observed a panic: %#v (%v)\n%s", r, r, stacktrace)
}
} | logPanic logs the caller tree when a panic occurs (except in the special case of http.ErrAbortHandler). | logPanic | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
func HandleError(err error) {
// this is sometimes called with a nil error. We probably shouldn't fail and should do nothing instead
if err == nil {
return
}
for _, fn := range ErrorHandlers {
fn(err)
}
} | HandlerError is a method to invoke when a non-user facing piece of code cannot
return an error and needs to indicate it has been ignored. Invoking this method
is preferable to logging the error - the default behavior is to log but the
errors may be sent to a remote server for analysis. | HandleError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
func logError(err error) {
klog.ErrorDepth(2, err)
} | logError prints an error with the call stack of the location it was reported | logError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
func (r *rudimentaryErrorBackoff) OnError(error) {
now := time.Now() // start the timer before acquiring the lock
r.lastErrorTimeLock.Lock()
d := now.Sub(r.lastErrorTime)
r.lastErrorTime = time.Now()
r.lastErrorTimeLock.Unlock()
// Do not sleep with the lock held because that causes all callers of HandleError to block.
// We only want the current goroutine to block.
// A negative or zero duration causes time.Sleep to return immediately.
// If the time moves backwards for any reason, do nothing.
time.Sleep(r.minPeriod - d)
} | OnError will block if it is called more often than the embedded period time.
This will prevent overly tight hot error loops. | OnError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
func GetCaller() string {
var pc [1]uintptr
runtime.Callers(3, pc[:])
f := runtime.FuncForPC(pc[0])
if f == nil {
return "Unable to find caller"
}
return f.Name()
} | GetCaller returns the caller of the function that calls it. | GetCaller | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
func RecoverFromPanic(err *error) {
if r := recover(); r != nil {
// Same as stdlib http server code. Manually allocate stack trace buffer size
// to prevent excessively large logs
const size = 64 << 10
stacktrace := make([]byte, size)
stacktrace = stacktrace[:runtime.Stack(stacktrace, false)]
*err = fmt.Errorf(
"recovered from panic %q. (err=%v) Call stack:\n%s",
r,
*err,
stacktrace)
}
} | RecoverFromPanic replaces the specified error with an error containing the
original error, and the call tree when a panic occurs. This enables error
handlers to handle errors and panics the same way. | RecoverFromPanic | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
func Must(err error) {
if err != nil {
panic(err)
}
} | Must panics on non-nil errors. Useful to handling programmer level errors. | Must | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.