2014-05-07 00:48:25 +00:00
|
|
|
package testutil
|
|
|
|
|
|
|
|
import (
|
2017-01-27 03:05:56 +00:00
|
|
|
"fmt"
|
2014-05-16 22:49:47 +00:00
|
|
|
"testing"
|
|
|
|
"time"
|
2017-01-26 05:13:34 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/consul/consul/structs"
|
2017-03-24 03:04:39 +00:00
|
|
|
"github.com/pkg/errors"
|
2014-05-07 00:48:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type testFn func() (bool, error)
|
|
|
|
|
2017-01-27 01:11:16 +00:00
|
|
|
const (
|
|
|
|
baseWait = 1 * time.Millisecond
|
|
|
|
maxWait = 100 * time.Millisecond
|
|
|
|
)
|
2014-05-07 00:48:25 +00:00
|
|
|
|
2017-03-23 20:26:05 +00:00
|
|
|
func WaitForResult(try testFn) error {
|
2017-01-27 01:11:16 +00:00
|
|
|
var err error
|
|
|
|
wait := baseWait
|
|
|
|
for retries := 100; retries > 0; retries-- {
|
|
|
|
var success bool
|
|
|
|
success, err = try()
|
2014-05-07 00:48:25 +00:00
|
|
|
if success {
|
2017-01-27 03:05:56 +00:00
|
|
|
time.Sleep(25 * time.Millisecond)
|
2017-03-23 20:26:05 +00:00
|
|
|
return nil
|
2014-05-07 00:48:25 +00:00
|
|
|
}
|
|
|
|
|
2017-01-27 01:11:16 +00:00
|
|
|
time.Sleep(wait)
|
|
|
|
wait *= 2
|
|
|
|
if wait > maxWait {
|
|
|
|
wait = maxWait
|
2014-05-07 00:48:25 +00:00
|
|
|
}
|
|
|
|
}
|
2017-03-24 03:04:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "timed out with error")
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("timed out")
|
|
|
|
}
|
2014-05-07 00:48:25 +00:00
|
|
|
}
|
2014-05-07 09:43:42 +00:00
|
|
|
|
2014-05-16 22:49:47 +00:00
|
|
|
type rpcFn func(string, interface{}, interface{}) error
|
2014-05-07 09:43:42 +00:00
|
|
|
|
2014-05-08 23:17:35 +00:00
|
|
|
func WaitForLeader(t *testing.T, rpc rpcFn, dc string) structs.IndexedNodes {
|
2014-05-07 11:53:29 +00:00
|
|
|
var out structs.IndexedNodes
|
2017-03-23 20:26:05 +00:00
|
|
|
if err := WaitForResult(func() (bool, error) {
|
2017-01-27 03:05:56 +00:00
|
|
|
// Ensure we have a leader and a node registration.
|
2014-06-11 01:04:24 +00:00
|
|
|
args := &structs.DCSpecificRequest{
|
2014-05-08 23:17:35 +00:00
|
|
|
Datacenter: dc,
|
2014-05-07 21:41:14 +00:00
|
|
|
}
|
2017-01-27 03:05:56 +00:00
|
|
|
if err := rpc("Catalog.ListNodes", args, &out); err != nil {
|
|
|
|
return false, fmt.Errorf("Catalog.ListNodes failed: %v", err)
|
|
|
|
}
|
|
|
|
if !out.QueryMeta.KnownLeader {
|
|
|
|
return false, fmt.Errorf("No leader")
|
|
|
|
}
|
|
|
|
if out.Index == 0 {
|
|
|
|
return false, fmt.Errorf("Consul index is 0")
|
|
|
|
}
|
|
|
|
return true, nil
|
2017-03-23 20:26:05 +00:00
|
|
|
}); err != nil {
|
2014-05-07 09:43:42 +00:00
|
|
|
t.Fatalf("failed to find leader: %v", err)
|
2017-03-23 20:26:05 +00:00
|
|
|
}
|
2014-05-07 11:53:29 +00:00
|
|
|
return out
|
2014-05-07 09:43:42 +00:00
|
|
|
}
|