diff --git a/lib/cluster.go b/lib/cluster.go index 33a7788c78..5df39251d8 100644 --- a/lib/cluster.go +++ b/lib/cluster.go @@ -5,6 +5,15 @@ import ( "time" ) +// 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 + d -= RandomStagger(time.Duration(int64(d) / jitter)) + return d +} + // Returns a random stagger interval between 0 and the duration func RandomStagger(intv time.Duration) time.Duration { return time.Duration(uint64(rand.Int63()) % uint64(intv)) diff --git a/lib/cluster_test.go b/lib/cluster_test.go index d517e4677f..acd862f6f1 100644 --- a/lib/cluster_test.go +++ b/lib/cluster_test.go @@ -5,6 +5,22 @@ import ( "time" ) +func TestDurationMinusBuffer(t *testing.T) { + const ( + buffer = 10 * time.Second + jitter = 16 + ) + intv := 1 * time.Minute + minValue := (intv - buffer) - ((intv - buffer) / jitter) + maxValue := intv - buffer + for i := 0; i < 10; i++ { + d := DurationMinusBuffer(intv, buffer, jitter) + if d < minValue || d > maxValue { + t.Fatalf("Bad: %v", d) + } + } +} + func TestRandomStagger(t *testing.T) { intv := time.Minute for i := 0; i < 10; i++ {