Skip to content

Commit

Permalink
Fix test because of jitter
Browse files Browse the repository at this point in the history
  • Loading branch information
dadgar committed Dec 18, 2015
1 parent 7536f7c commit 95f9339
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
7 changes: 5 additions & 2 deletions client/restarts.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"github.com/hashicorp/nomad/nomad/structs"
)

// jitter is the percent of jitter added to restart delays.
const jitter = 0.25

func newRestartTracker(policy *structs.RestartPolicy) *RestartTracker {
return &RestartTracker{
startTime: time.Now(),
Expand Down Expand Up @@ -57,8 +60,8 @@ func (r *RestartTracker) shouldRestart(exitCode int) bool {
// jitter returns the delay time plus a jitter.
func (r *RestartTracker) jitter() time.Duration {
d := r.policy.Delay.Nanoseconds()
j := r.rand.Int63n(d) / 4 // Up to 25% jitter
return time.Duration(d + j)
j := float64(r.rand.Int63n(d)) * jitter
return time.Duration(d + int64(j))
}

// Returns a tracker that never restarts.
Expand Down
15 changes: 11 additions & 4 deletions client/restarts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ func testPolicy(success bool, mode string) *structs.RestartPolicy {
}
}

// withinJitter is a helper that returns whether the returned delay is within
// the jitter.
func withinJitter(expected, actual time.Duration) bool {
return float64((actual.Nanoseconds()-expected.Nanoseconds())/
expected.Nanoseconds()) <= jitter
}

func TestClient_RestartTracker_ModeDelay(t *testing.T) {
t.Parallel()
p := testPolicy(true, structs.RestartPolicyModeDelay)
Expand All @@ -26,8 +33,8 @@ func TestClient_RestartTracker_ModeDelay(t *testing.T) {
if !actual {
t.Fatalf("NextRestart() returned %v, want %v", actual, true)
}
if when != p.Delay {
t.Fatalf("NextRestart() returned %v; want %v", when, p.Delay)
if !withinJitter(p.Delay, when) {
t.Fatalf("NextRestart() returned %v; want %v+jitter", when, p.Delay)
}
}

Expand All @@ -52,8 +59,8 @@ func TestClient_RestartTracker_ModeFail(t *testing.T) {
if !actual {
t.Fatalf("NextRestart() returned %v, want %v", actual, true)
}
if when != p.Delay {
t.Fatalf("NextRestart() returned %v; want %v", when, p.Delay)
if !withinJitter(p.Delay, when) {
t.Fatalf("NextRestart() returned %v; want %v+jitter", when, p.Delay)
}
}

Expand Down

0 comments on commit 95f9339

Please sign in to comment.