github.com/lmb/consul@v1.4.1/testrpc/wait.go (about) 1 package testrpc 2 3 import ( 4 "testing" 5 6 "github.com/hashicorp/consul/agent/structs" 7 "github.com/hashicorp/consul/testutil/retry" 8 ) 9 10 type rpcFn func(string, interface{}, interface{}) error 11 12 // WaitForLeader ensures we have a leader and a node registration. 13 func WaitForLeader(t *testing.T, rpc rpcFn, dc string) { 14 var out structs.IndexedNodes 15 retry.Run(t, func(r *retry.R) { 16 args := &structs.DCSpecificRequest{Datacenter: dc} 17 if err := rpc("Catalog.ListNodes", args, &out); err != nil { 18 r.Fatalf("Catalog.ListNodes failed: %v", err) 19 } 20 if !out.QueryMeta.KnownLeader { 21 r.Fatalf("No leader") 22 } 23 if out.Index < 2 { 24 r.Fatalf("Consul index should be at least 2") 25 } 26 }) 27 } 28 29 // WaitUntilNoLeader ensures no leader is present, useful for testing lost leadership. 30 func WaitUntilNoLeader(t *testing.T, rpc rpcFn, dc string) { 31 var out structs.IndexedNodes 32 retry.Run(t, func(r *retry.R) { 33 args := &structs.DCSpecificRequest{Datacenter: dc} 34 if err := rpc("Catalog.ListNodes", args, &out); err == nil { 35 r.Fatalf("It still has a leader: %#v", out) 36 } 37 if out.QueryMeta.KnownLeader { 38 r.Fatalf("Has still a leader") 39 } 40 }) 41 } 42 43 // WaitForTestAgent ensures we have a node with serfHealth check registered 44 func WaitForTestAgent(t *testing.T, rpc rpcFn, dc string) { 45 var nodes structs.IndexedNodes 46 var checks structs.IndexedHealthChecks 47 48 retry.Run(t, func(r *retry.R) { 49 dcReq := &structs.DCSpecificRequest{Datacenter: dc} 50 if err := rpc("Catalog.ListNodes", dcReq, &nodes); err != nil { 51 r.Fatalf("Catalog.ListNodes failed: %v", err) 52 } 53 if len(nodes.Nodes) == 0 { 54 r.Fatalf("No registered nodes") 55 } 56 57 // This assumes that there is a single agent per dc, typically a TestAgent 58 nodeReq := &structs.NodeSpecificRequest{Datacenter: dc, Node: nodes.Nodes[0].Node} 59 if err := rpc("Health.NodeChecks", nodeReq, &checks); err != nil { 60 r.Fatalf("Health.NodeChecks failed: %v", err) 61 } 62 63 var found bool 64 for _, check := range checks.HealthChecks { 65 if check.CheckID == "serfHealth" { 66 found = true 67 break 68 } 69 } 70 if !found { 71 r.Fatalf("serfHealth check not found") 72 } 73 }) 74 }