2014-05-07 02:48:25 +02:00
|
|
|
package testutil
|
|
|
|
|
|
|
|
import (
|
2017-01-26 19:05:56 -08:00
|
|
|
"fmt"
|
2014-05-16 15:49:47 -07:00
|
|
|
"testing"
|
|
|
|
"time"
|
2017-01-26 00:13:34 -05:00
|
|
|
|
|
|
|
"github.com/hashicorp/consul/consul/structs"
|
2014-05-07 02:48:25 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type testFn func() (bool, error)
|
|
|
|
type errorFn func(error)
|
|
|
|
|
2017-01-26 17:11:16 -08:00
|
|
|
const (
|
|
|
|
baseWait = 1 * time.Millisecond
|
|
|
|
maxWait = 100 * time.Millisecond
|
|
|
|
)
|
2014-05-07 02:48:25 +02:00
|
|
|
|
2017-01-26 17:11:16 -08:00
|
|
|
func WaitForResult(try testFn, fail errorFn) {
|
|
|
|
var err error
|
|
|
|
wait := baseWait
|
|
|
|
for retries := 100; retries > 0; retries-- {
|
|
|
|
var success bool
|
|
|
|
success, err = try()
|
2014-05-07 02:48:25 +02:00
|
|
|
if success {
|
2017-01-26 19:05:56 -08:00
|
|
|
time.Sleep(25 * time.Millisecond)
|
2014-05-07 02:48:25 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-01-26 17:11:16 -08:00
|
|
|
time.Sleep(wait)
|
|
|
|
wait *= 2
|
|
|
|
if wait > maxWait {
|
|
|
|
wait = maxWait
|
2014-05-07 02:48:25 +02:00
|
|
|
}
|
|
|
|
}
|
2017-01-26 17:11:16 -08:00
|
|
|
fail(err)
|
2014-05-07 02:48:25 +02:00
|
|
|
}
|
2014-05-07 11:43:42 +02:00
|
|
|
|
2014-05-16 15:49:47 -07:00
|
|
|
type rpcFn func(string, interface{}, interface{}) error
|
2014-05-07 11:43:42 +02:00
|
|
|
|
2014-05-09 01:17:35 +02:00
|
|
|
func WaitForLeader(t *testing.T, rpc rpcFn, dc string) structs.IndexedNodes {
|
2014-05-07 13:53:29 +02:00
|
|
|
var out structs.IndexedNodes
|
2014-05-07 11:43:42 +02:00
|
|
|
WaitForResult(func() (bool, error) {
|
2017-01-26 19:05:56 -08:00
|
|
|
// Ensure we have a leader and a node registration.
|
2014-06-10 18:04:24 -07:00
|
|
|
args := &structs.DCSpecificRequest{
|
2014-05-09 01:17:35 +02:00
|
|
|
Datacenter: dc,
|
2014-05-07 23:41:14 +02:00
|
|
|
}
|
2017-01-26 19:05:56 -08: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
|
2014-05-07 11:43:42 +02:00
|
|
|
}, func(err error) {
|
|
|
|
t.Fatalf("failed to find leader: %v", err)
|
|
|
|
})
|
2014-05-07 13:53:29 +02:00
|
|
|
return out
|
2014-05-07 11:43:42 +02:00
|
|
|
}
|