From e5c8fce96a10ef8b0c313afd0c64fa783588e7d4 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Thu, 14 May 2015 17:59:11 -0700 Subject: [PATCH] consul: adding randomStagger util method --- consul/util.go | 7 +++++++ consul/util_test.go | 11 +++++++++++ 2 files changed, 18 insertions(+) diff --git a/consul/util.go b/consul/util.go index d0ce256fe..6cc785899 100644 --- a/consul/util.go +++ b/consul/util.go @@ -4,12 +4,14 @@ import ( crand "crypto/rand" "encoding/binary" "fmt" + "math/rand" "net" "os" "path/filepath" "runtime" "strconv" "strings" + "time" "github.com/hashicorp/serf/serf" ) @@ -222,3 +224,8 @@ func generateUUID() string { buf[8:10], buf[10:16]) } + +// 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/consul/util_test.go b/consul/util_test.go index 24d9f7299..5803e95a9 100644 --- a/consul/util_test.go +++ b/consul/util_test.go @@ -4,6 +4,7 @@ import ( "net" "regexp" "testing" + "time" "github.com/hashicorp/serf/serf" ) @@ -124,3 +125,13 @@ func TestGenerateUUID(t *testing.T) { } } } + +func TestRandomStagger(t *testing.T) { + intv := time.Minute + for i := 0; i < 10; i++ { + stagger := randomStagger(intv) + if stagger < 0 || stagger >= intv { + t.Fatalf("Bad: %v", stagger) + } + } +}