Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

helper: guard against negative inputs into random stagger #14497

Merged
merged 1 commit into from
Sep 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/14497.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:bug
helpers: Fixed a bug where random stagger func did not protect against negative inputs
```
7 changes: 3 additions & 4 deletions helper/cluster.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// These functions are coming from consul/lib/cluster.go
package helper

import (
Expand All @@ -13,11 +12,11 @@ const (
)

// RandomStagger returns an interval between 0 and the duration
func RandomStagger(intv time.Duration) time.Duration {
if intv == 0 {
func RandomStagger(interval time.Duration) time.Duration {
if interval <= 0 {
return 0
}
return time.Duration(uint64(rand.Int63()) % uint64(intv))
return time.Duration(uint64(rand.Int63()) % uint64(interval))
}

// RateScaledInterval is used to choose an interval to perform an action in
Expand Down
29 changes: 29 additions & 0 deletions helper/cluster_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package helper

import (
"testing"
"time"

"github.com/shoenig/test/must"
)

func TestCluster_RandomStagger(t *testing.T) {
cases := []struct {
name string
input time.Duration
}{
{name: "positive", input: 1 * time.Second},
{name: "negative", input: -1 * time.Second},
{name: "zero", input: 0},
}

abs := func(d time.Duration) time.Duration {
return Max(d, -d)
}

for _, tc := range cases {
result := RandomStagger(tc.input)
must.GreaterEq(t, result, 0)
must.LessEq(t, result, abs(tc.input))
Comment on lines +26 to +27
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just now realizing I got these parameters backwards, shoenig/test#33

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fwiw, having the parameters in the same "direction" as the operator feels more intuitive to me. ex. must.GreaterEq(t, a, b) reads like it should be checking a > b. Whereas for something like must.Eq there isn't an obvious expectation vs result in the way the parameters are named anyways.

}
}