2023-03-28 22:48:58 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2016-01-29 19:42:34 +00:00
|
|
|
package lib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2017-10-30 23:46:11 +00:00
|
|
|
const (
|
|
|
|
// minRate is the minimum rate at which we allow an action to be performed
|
2017-10-30 23:51:28 +00:00
|
|
|
// across the whole cluster. The value is once a day: 1 / (1 * time.Day)
|
2017-10-30 23:46:11 +00:00
|
|
|
minRate = 1.0 / 86400
|
|
|
|
)
|
|
|
|
|
2016-04-23 16:03:47 +00:00
|
|
|
// DurationMinusBuffer returns a duration, minus a buffer and jitter
|
|
|
|
// subtracted from the duration. This function is used primarily for
|
|
|
|
// servicing Consul TTL Checks in advance of the TTL.
|
|
|
|
func DurationMinusBuffer(intv time.Duration, buffer time.Duration, jitter int64) time.Duration {
|
|
|
|
d := intv - buffer
|
2016-04-23 20:11:32 +00:00
|
|
|
if jitter == 0 {
|
|
|
|
d -= RandomStagger(d)
|
|
|
|
} else {
|
|
|
|
d -= RandomStagger(time.Duration(int64(d) / jitter))
|
|
|
|
}
|
2016-04-23 16:03:47 +00:00
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
2016-04-23 20:11:32 +00:00
|
|
|
// DurationMinusBufferDomain returns the domain of valid durations from a
|
|
|
|
// call to DurationMinusBuffer. This function is used to check user
|
|
|
|
// specified input values to DurationMinusBuffer.
|
|
|
|
func DurationMinusBufferDomain(intv time.Duration, buffer time.Duration, jitter int64) (min time.Duration, max time.Duration) {
|
|
|
|
max = intv - buffer
|
|
|
|
if jitter == 0 {
|
|
|
|
min = max
|
|
|
|
} else {
|
|
|
|
min = max - time.Duration(int64(max)/jitter)
|
|
|
|
}
|
|
|
|
return min, max
|
|
|
|
}
|
|
|
|
|
2017-04-21 03:14:10 +00:00
|
|
|
// RandomStagger returns an interval between 0 and the duration
|
2016-01-29 19:42:34 +00:00
|
|
|
func RandomStagger(intv time.Duration) time.Duration {
|
2016-04-23 20:11:32 +00:00
|
|
|
if intv == 0 {
|
|
|
|
return 0
|
|
|
|
}
|
2016-01-29 19:42:34 +00:00
|
|
|
return time.Duration(uint64(rand.Int63()) % uint64(intv))
|
|
|
|
}
|
|
|
|
|
2023-02-06 19:07:41 +00:00
|
|
|
// RandomStaggerWithRange returns an interval between min and the max duration
|
|
|
|
func RandomStaggerWithRange(min time.Duration, max time.Duration) time.Duration {
|
|
|
|
return RandomStagger(max-min) + min
|
|
|
|
}
|
|
|
|
|
2016-01-29 19:42:34 +00:00
|
|
|
// RateScaledInterval is used to choose an interval to perform an action in
|
|
|
|
// order to target an aggregate number of actions per second across the whole
|
|
|
|
// cluster.
|
|
|
|
func RateScaledInterval(rate float64, min time.Duration, n int) time.Duration {
|
2016-03-25 20:26:29 +00:00
|
|
|
if rate <= minRate {
|
|
|
|
return min
|
|
|
|
}
|
2016-01-29 19:42:34 +00:00
|
|
|
interval := time.Duration(float64(time.Second) * float64(n) / rate)
|
|
|
|
if interval < min {
|
|
|
|
return min
|
|
|
|
}
|
|
|
|
|
|
|
|
return interval
|
|
|
|
}
|