agent: refactor tests for TestAgent

Refactored tests that use

 * makeAgentXXX
 * makeDNSServerXXX
 * makeHTTPServerXXX
pull/3037/head
Frank Schroeder 2017-05-21 09:11:09 +02:00
parent b5b3aa1376
commit 23a6ff383c
No known key found for this signature in database
GPG Key ID: 4D65C6EAEC87DECD
17 changed files with 1676 additions and 2379 deletions

View File

@ -3,21 +3,19 @@ package agent
import (
"errors"
"fmt"
"os"
"strings"
"testing"
"time"
rawacl "github.com/hashicorp/consul/acl"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/testutil"
"github.com/hashicorp/consul/types"
"github.com/hashicorp/serf/serf"
)
func TestACL_Bad_Config(t *testing.T) {
c := nextConfig()
c := TestConfig()
c.ACLDownPolicy = "nope"
c.DataDir = testutil.TempDir(t, "agent")
@ -39,17 +37,13 @@ func (m *MockServer) GetPolicy(args *structs.ACLPolicyRequest, reply *structs.AC
}
func TestACL_Version8(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(false)
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
config := TestConfig()
config.ACLEnforceVersion8 = &BoolFalse
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
@ -58,24 +52,20 @@ func TestACL_Version8(t *testing.T) {
t.Fatalf("should not have called to server")
return nil
}
if token, err := agent.resolveToken("nope"); token != nil || err != nil {
if token, err := a.resolveToken("nope"); token != nil || err != nil {
t.Fatalf("bad: %v err: %v", token, err)
}
}
func TestACL_Disabled(t *testing.T) {
config := nextConfig()
config := TestConfig()
config.ACLDisabledTTL = 10 * time.Millisecond
config.ACLEnforceVersion8 = Bool(true)
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
config.ACLEnforceVersion8 = &BoolTrue
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
@ -83,13 +73,13 @@ func TestACL_Disabled(t *testing.T) {
m.getPolicyFn = func(*structs.ACLPolicyRequest, *structs.ACLPolicy) error {
return errors.New(aclDisabled)
}
if agent.acls.isDisabled() {
if a.acls.isDisabled() {
t.Fatalf("should not be disabled yet")
}
if token, err := agent.resolveToken("nope"); token != nil || err != nil {
if token, err := a.resolveToken("nope"); token != nil || err != nil {
t.Fatalf("bad: %v err: %v", token, err)
}
if !agent.acls.isDisabled() {
if !a.acls.isDisabled() {
t.Fatalf("should be disabled")
}
@ -98,10 +88,10 @@ func TestACL_Disabled(t *testing.T) {
m.getPolicyFn = func(*structs.ACLPolicyRequest, *structs.ACLPolicy) error {
return errors.New(aclNotFound)
}
if token, err := agent.resolveToken("nope"); token != nil || err != nil {
if token, err := a.resolveToken("nope"); token != nil || err != nil {
t.Fatalf("bad: %v err: %v", token, err)
}
if !agent.acls.isDisabled() {
if !a.acls.isDisabled() {
t.Fatalf("should be disabled")
}
@ -109,29 +99,26 @@ func TestACL_Disabled(t *testing.T) {
// to make sure we don't think it's disabled.
time.Sleep(2 * config.ACLDisabledTTL)
for i := 0; i < 10; i++ {
_, err := agent.resolveToken("nope")
_, err := a.resolveToken("nope")
if err == nil || !strings.Contains(err.Error(), aclNotFound) {
t.Fatalf("err: %v", err)
}
if agent.acls.isDisabled() {
if a.acls.isDisabled() {
t.Fatalf("should not be disabled")
}
}
}
func TestACL_Special_IDs(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
config.ACLAgentMasterToken = "towel"
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
@ -142,7 +129,7 @@ func TestACL_Special_IDs(t *testing.T) {
}
return errors.New(aclNotFound)
}
_, err := agent.resolveToken("")
_, err := a.resolveToken("")
if err == nil || !strings.Contains(err.Error(), aclNotFound) {
t.Fatalf("err: %v", err)
}
@ -152,14 +139,14 @@ func TestACL_Special_IDs(t *testing.T) {
t.Fatalf("should not have called to server")
return nil
}
_, err = agent.resolveToken("deny")
_, err = a.resolveToken("deny")
if err == nil || !strings.Contains(err.Error(), rootDenied) {
t.Fatalf("err: %v", err)
}
// The ACL master token should also not call the server, but should give
// us a working agent token.
acl, err := agent.resolveToken("towel")
// us a working a token.
acl, err := a.resolveToken("towel")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -175,18 +162,15 @@ func TestACL_Special_IDs(t *testing.T) {
}
func TestACL_Down_Deny(t *testing.T) {
config := nextConfig()
config := TestConfig()
config.ACLDownPolicy = "deny"
config.ACLEnforceVersion8 = Bool(true)
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
@ -194,7 +178,7 @@ func TestACL_Down_Deny(t *testing.T) {
m.getPolicyFn = func(*structs.ACLPolicyRequest, *structs.ACLPolicy) error {
return fmt.Errorf("ACLs are broken")
}
acl, err := agent.resolveToken("nope")
acl, err := a.resolveToken("nope")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -207,18 +191,15 @@ func TestACL_Down_Deny(t *testing.T) {
}
func TestACL_Down_Allow(t *testing.T) {
config := nextConfig()
config := TestConfig()
config.ACLDownPolicy = "allow"
config.ACLEnforceVersion8 = Bool(true)
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
@ -226,7 +207,7 @@ func TestACL_Down_Allow(t *testing.T) {
m.getPolicyFn = func(*structs.ACLPolicyRequest, *structs.ACLPolicy) error {
return fmt.Errorf("ACLs are broken")
}
acl, err := agent.resolveToken("nope")
acl, err := a.resolveToken("nope")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -239,18 +220,15 @@ func TestACL_Down_Allow(t *testing.T) {
}
func TestACL_Down_Extend(t *testing.T) {
config := nextConfig()
config := TestConfig()
config.ACLDownPolicy = "extend-cache"
config.ACLEnforceVersion8 = Bool(true)
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
@ -269,7 +247,7 @@ func TestACL_Down_Extend(t *testing.T) {
}
return nil
}
acl, err := agent.resolveToken("yep")
acl, err := a.resolveToken("yep")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -287,7 +265,7 @@ func TestACL_Down_Extend(t *testing.T) {
m.getPolicyFn = func(*structs.ACLPolicyRequest, *structs.ACLPolicy) error {
return fmt.Errorf("ACLs are broken")
}
acl, err = agent.resolveToken("nope")
acl, err = a.resolveToken("nope")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -303,7 +281,7 @@ func TestACL_Down_Extend(t *testing.T) {
// Read the token from the cache while ACLs are broken, which should
// extend.
acl, err = agent.resolveToken("yep")
acl, err = a.resolveToken("yep")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -319,17 +297,14 @@ func TestACL_Down_Extend(t *testing.T) {
}
func TestACL_Cache(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
@ -350,7 +325,7 @@ func TestACL_Cache(t *testing.T) {
}
return nil
}
acl, err := agent.resolveToken("yep")
acl, err := a.resolveToken("yep")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -372,7 +347,7 @@ func TestACL_Cache(t *testing.T) {
t.Fatalf("should not have called to server")
return nil
}
acl, err = agent.resolveToken("yep")
acl, err = a.resolveToken("yep")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -395,7 +370,7 @@ func TestACL_Cache(t *testing.T) {
m.getPolicyFn = func(req *structs.ACLPolicyRequest, reply *structs.ACLPolicy) error {
return errors.New(aclNotFound)
}
_, err = agent.resolveToken("yep")
_, err = a.resolveToken("yep")
if err == nil || !strings.Contains(err.Error(), aclNotFound) {
t.Fatalf("err: %v", err)
}
@ -417,7 +392,7 @@ func TestACL_Cache(t *testing.T) {
}
return nil
}
acl, err = agent.resolveToken("yep")
acl, err = a.resolveToken("yep")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -447,7 +422,7 @@ func TestACL_Cache(t *testing.T) {
didRefresh = true
return nil
}
acl, err = agent.resolveToken("yep")
acl, err = a.resolveToken("yep")
if err != nil {
t.Fatalf("err: %v", err)
}
@ -503,22 +478,19 @@ func catalogPolicy(req *structs.ACLPolicyRequest, reply *structs.ACLPolicy) erro
}
func TestACL_vetServiceRegister(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{catalogPolicy}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
// Register a new service, with permission.
err := agent.vetServiceRegister("service-rw", &structs.NodeService{
err := a.vetServiceRegister("service-rw", &structs.NodeService{
ID: "my-service",
Service: "service",
})
@ -527,7 +499,7 @@ func TestACL_vetServiceRegister(t *testing.T) {
}
// Register a new service without write privs.
err = agent.vetServiceRegister("service-ro", &structs.NodeService{
err = a.vetServiceRegister("service-ro", &structs.NodeService{
ID: "my-service",
Service: "service",
})
@ -537,11 +509,11 @@ func TestACL_vetServiceRegister(t *testing.T) {
// Try to register over a service without write privs to the existing
// service.
agent.state.AddService(&structs.NodeService{
a.state.AddService(&structs.NodeService{
ID: "my-service",
Service: "other",
}, "")
err = agent.vetServiceRegister("service-rw", &structs.NodeService{
err = a.vetServiceRegister("service-rw", &structs.NodeService{
ID: "my-service",
Service: "service",
})
@ -551,60 +523,54 @@ func TestACL_vetServiceRegister(t *testing.T) {
}
func TestACL_vetServiceUpdate(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{catalogPolicy}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
// Update a service that doesn't exist.
err := agent.vetServiceUpdate("service-rw", "my-service")
err := a.vetServiceUpdate("service-rw", "my-service")
if err == nil || !strings.Contains(err.Error(), "Unknown service") {
t.Fatalf("err: %v", err)
}
// Update with write privs.
agent.state.AddService(&structs.NodeService{
a.state.AddService(&structs.NodeService{
ID: "my-service",
Service: "service",
}, "")
err = agent.vetServiceUpdate("service-rw", "my-service")
err = a.vetServiceUpdate("service-rw", "my-service")
if err != nil {
t.Fatalf("err: %v", err)
}
// Update without write privs.
err = agent.vetServiceUpdate("service-ro", "my-service")
err = a.vetServiceUpdate("service-ro", "my-service")
if !isPermissionDenied(err) {
t.Fatalf("err: %v", err)
}
}
func TestACL_vetCheckRegister(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{catalogPolicy}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
// Register a new service check with write privs.
err := agent.vetCheckRegister("service-rw", &structs.HealthCheck{
err := a.vetCheckRegister("service-rw", &structs.HealthCheck{
CheckID: types.CheckID("my-check"),
ServiceID: "my-service",
ServiceName: "service",
@ -614,7 +580,7 @@ func TestACL_vetCheckRegister(t *testing.T) {
}
// Register a new service check without write privs.
err = agent.vetCheckRegister("service-ro", &structs.HealthCheck{
err = a.vetCheckRegister("service-ro", &structs.HealthCheck{
CheckID: types.CheckID("my-check"),
ServiceID: "my-service",
ServiceName: "service",
@ -624,7 +590,7 @@ func TestACL_vetCheckRegister(t *testing.T) {
}
// Register a new node check with write privs.
err = agent.vetCheckRegister("node-rw", &structs.HealthCheck{
err = a.vetCheckRegister("node-rw", &structs.HealthCheck{
CheckID: types.CheckID("my-check"),
})
if err != nil {
@ -632,7 +598,7 @@ func TestACL_vetCheckRegister(t *testing.T) {
}
// Register a new node check without write privs.
err = agent.vetCheckRegister("node-ro", &structs.HealthCheck{
err = a.vetCheckRegister("node-ro", &structs.HealthCheck{
CheckID: types.CheckID("my-check"),
})
if !isPermissionDenied(err) {
@ -641,16 +607,16 @@ func TestACL_vetCheckRegister(t *testing.T) {
// Try to register over a service check without write privs to the
// existing service.
agent.state.AddService(&structs.NodeService{
a.state.AddService(&structs.NodeService{
ID: "my-service",
Service: "service",
}, "")
agent.state.AddCheck(&structs.HealthCheck{
a.state.AddCheck(&structs.HealthCheck{
CheckID: types.CheckID("my-check"),
ServiceID: "my-service",
ServiceName: "other",
}, "")
err = agent.vetCheckRegister("service-rw", &structs.HealthCheck{
err = a.vetCheckRegister("service-rw", &structs.HealthCheck{
CheckID: types.CheckID("my-check"),
ServiceID: "my-service",
ServiceName: "service",
@ -660,10 +626,10 @@ func TestACL_vetCheckRegister(t *testing.T) {
}
// Try to register over a node check without write privs to the node.
agent.state.AddCheck(&structs.HealthCheck{
a.state.AddCheck(&structs.HealthCheck{
CheckID: types.CheckID("my-node-check"),
}, "")
err = agent.vetCheckRegister("service-rw", &structs.HealthCheck{
err = a.vetCheckRegister("service-rw", &structs.HealthCheck{
CheckID: types.CheckID("my-node-check"),
ServiceID: "my-service",
ServiceName: "service",
@ -674,80 +640,74 @@ func TestACL_vetCheckRegister(t *testing.T) {
}
func TestACL_vetCheckUpdate(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{catalogPolicy}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
// Update a check that doesn't exist.
err := agent.vetCheckUpdate("node-rw", "my-check")
err := a.vetCheckUpdate("node-rw", "my-check")
if err == nil || !strings.Contains(err.Error(), "Unknown check") {
t.Fatalf("err: %v", err)
}
// Update service check with write privs.
agent.state.AddService(&structs.NodeService{
a.state.AddService(&structs.NodeService{
ID: "my-service",
Service: "service",
}, "")
agent.state.AddCheck(&structs.HealthCheck{
a.state.AddCheck(&structs.HealthCheck{
CheckID: types.CheckID("my-service-check"),
ServiceID: "my-service",
ServiceName: "service",
}, "")
err = agent.vetCheckUpdate("service-rw", "my-service-check")
err = a.vetCheckUpdate("service-rw", "my-service-check")
if err != nil {
t.Fatalf("err: %v", err)
}
// Update service check without write privs.
err = agent.vetCheckUpdate("service-ro", "my-service-check")
err = a.vetCheckUpdate("service-ro", "my-service-check")
if !isPermissionDenied(err) {
t.Fatalf("err: %v", err)
}
// Update node check with write privs.
agent.state.AddCheck(&structs.HealthCheck{
a.state.AddCheck(&structs.HealthCheck{
CheckID: types.CheckID("my-node-check"),
}, "")
err = agent.vetCheckUpdate("node-rw", "my-node-check")
err = a.vetCheckUpdate("node-rw", "my-node-check")
if err != nil {
t.Fatalf("err: %v", err)
}
// Update without write privs.
err = agent.vetCheckUpdate("node-ro", "my-node-check")
err = a.vetCheckUpdate("node-ro", "my-node-check")
if !isPermissionDenied(err) {
t.Fatalf("err: %v", err)
}
}
func TestACL_filterMembers(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{catalogPolicy}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
var members []serf.Member
if err := agent.filterMembers("node-ro", &members); err != nil {
if err := a.filterMembers("node-ro", &members); err != nil {
t.Fatalf("err: %v", err)
}
if len(members) != 0 {
@ -759,7 +719,7 @@ func TestACL_filterMembers(t *testing.T) {
serf.Member{Name: "Nope"},
serf.Member{Name: "Node 2"},
}
if err := agent.filterMembers("node-ro", &members); err != nil {
if err := a.filterMembers("node-ro", &members); err != nil {
t.Fatalf("err: %v", err)
}
if len(members) != 2 ||
@ -770,28 +730,25 @@ func TestACL_filterMembers(t *testing.T) {
}
func TestACL_filterServices(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{catalogPolicy}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
services := make(map[string]*structs.NodeService)
if err := agent.filterServices("node-ro", &services); err != nil {
if err := a.filterServices("node-ro", &services); err != nil {
t.Fatalf("err: %v", err)
}
services["my-service"] = &structs.NodeService{ID: "my-service", Service: "service"}
services["my-other"] = &structs.NodeService{ID: "my-other", Service: "other"}
if err := agent.filterServices("service-ro", &services); err != nil {
if err := a.filterServices("service-ro", &services); err != nil {
t.Fatalf("err: %v", err)
}
if _, ok := services["my-service"]; !ok {
@ -803,29 +760,26 @@ func TestACL_filterServices(t *testing.T) {
}
func TestACL_filterChecks(t *testing.T) {
config := nextConfig()
config.ACLEnforceVersion8 = Bool(true)
config := TestConfig()
config.ACLEnforceVersion8 = &BoolTrue
dir, agent := makeAgent(t, config)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), config)
defer a.Shutdown()
m := MockServer{catalogPolicy}
if err := agent.InjectEndpoint("ACL", &m); err != nil {
if err := a.InjectEndpoint("ACL", &m); err != nil {
t.Fatalf("err: %v", err)
}
checks := make(map[types.CheckID]*structs.HealthCheck)
if err := agent.filterChecks("node-ro", &checks); err != nil {
if err := a.filterChecks("node-ro", &checks); err != nil {
t.Fatalf("err: %v", err)
}
checks["my-node"] = &structs.HealthCheck{}
checks["my-service"] = &structs.HealthCheck{ServiceName: "service"}
checks["my-other"] = &structs.HealthCheck{ServiceName: "other"}
if err := agent.filterChecks("service-ro", &checks); err != nil {
if err := a.filterChecks("service-ro", &checks); err != nil {
t.Fatalf("err: %v", err)
}
if _, ok := checks["my-node"]; ok {
@ -841,7 +795,7 @@ func TestACL_filterChecks(t *testing.T) {
checks["my-node"] = &structs.HealthCheck{}
checks["my-service"] = &structs.HealthCheck{ServiceName: "service"}
checks["my-other"] = &structs.HealthCheck{ServiceName: "other"}
if err := agent.filterChecks("node-ro", &checks); err != nil {
if err := a.filterChecks("node-ro", &checks); err != nil {
t.Fatalf("err: %v", err)
}
if _, ok := checks["my-node"]; !ok {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -4,22 +4,17 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/testutil/retry"
"github.com/hashicorp/serf/coordinate"
)
func TestCatalogRegister(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register node
args := &structs.RegisterRequest{
@ -27,7 +22,7 @@ func TestCatalogRegister(t *testing.T) {
Address: "127.0.0.1",
}
req, _ := http.NewRequest("GET", "/v1/catalog/register", jsonReader(args))
obj, err := srv.CatalogRegister(nil, req)
obj, err := a.srv.CatalogRegister(nil, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -38,23 +33,20 @@ func TestCatalogRegister(t *testing.T) {
}
// Service should be in sync
if err := srv.agent.state.syncService("foo"); err != nil {
if err := a.state.syncService("foo"); err != nil {
t.Fatalf("err: %s", err)
}
if _, ok := srv.agent.state.serviceStatus["foo"]; !ok {
t.Fatalf("bad: %#v", srv.agent.state.serviceStatus)
if _, ok := a.state.serviceStatus["foo"]; !ok {
t.Fatalf("bad: %#v", a.state.serviceStatus)
}
if !srv.agent.state.serviceStatus["foo"].inSync {
if !a.state.serviceStatus["foo"].inSync {
t.Fatalf("should be in sync")
}
}
func TestCatalogRegister_Service_InvalidAddress(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
for _, addr := range []string{"0.0.0.0", "::", "[::]"} {
t.Run("addr "+addr, func(t *testing.T) {
@ -68,7 +60,7 @@ func TestCatalogRegister_Service_InvalidAddress(t *testing.T) {
},
}
req, _ := http.NewRequest("GET", "/v1/catalog/register", jsonReader(args))
_, err := srv.CatalogRegister(nil, req)
_, err := a.srv.CatalogRegister(nil, req)
if err == nil || err.Error() != "Invalid service address" {
t.Fatalf("err: %v", err)
}
@ -77,16 +69,13 @@ func TestCatalogRegister_Service_InvalidAddress(t *testing.T) {
}
func TestCatalogDeregister(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register node
args := &structs.DeregisterRequest{Node: "foo"}
req, _ := http.NewRequest("GET", "/v1/catalog/deregister", jsonReader(args))
obj, err := srv.CatalogDeregister(nil, req)
obj, err := a.srv.CatalogDeregister(nil, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -98,12 +87,11 @@ func TestCatalogDeregister(t *testing.T) {
}
func TestCatalogDatacenters(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
retry.Run(t, func(r *retry.R) {
obj, err := srv.CatalogDatacenters(nil, nil)
obj, err := a.srv.CatalogDatacenters(nil, nil)
if err != nil {
r.Fatal(err)
}
@ -116,11 +104,8 @@ func TestCatalogDatacenters(t *testing.T) {
}
func TestCatalogNodes(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register node
args := &structs.RegisterRequest{
@ -130,13 +115,13 @@ func TestCatalogNodes(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/catalog/nodes?dc=dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogNodes(resp, req)
obj, err := a.srv.CatalogNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -151,11 +136,8 @@ func TestCatalogNodes(t *testing.T) {
}
func TestCatalogNodes_MetaFilter(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register a node with a meta field
args := &structs.RegisterRequest{
@ -168,13 +150,13 @@ func TestCatalogNodes_MetaFilter(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/catalog/nodes?node-meta=somekey:somevalue", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogNodes(resp, req)
obj, err := a.srv.CatalogNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -193,33 +175,27 @@ func TestCatalogNodes_MetaFilter(t *testing.T) {
}
func TestCatalogNodes_WanTranslation(t *testing.T) {
dir1, srv1 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc1"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir1)
defer srv1.agent.Shutdown()
testrpc.WaitForLeader(t, srv1.agent.RPC, "dc1")
c1 := TestConfig()
c1.Datacenter = "dc1"
c1.TranslateWanAddrs = true
c1.ACLDatacenter = ""
a1 := NewTestAgent(t.Name(), c1)
defer a1.Shutdown()
dir2, srv2 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc2"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir2)
defer srv2.agent.Shutdown()
testrpc.WaitForLeader(t, srv2.agent.RPC, "dc2")
c2 := TestConfig()
c2.Datacenter = "dc2"
c2.TranslateWanAddrs = true
c2.ACLDatacenter = ""
a2 := NewTestAgent(t.Name(), c2)
defer a2.Shutdown()
// Wait for the WAN join.
addr := fmt.Sprintf("127.0.0.1:%d", srv1.agent.config.Ports.SerfWan)
if _, err := srv2.agent.JoinWAN([]string{addr}); err != nil {
addr := fmt.Sprintf("127.0.0.1:%d", a1.Config.Ports.SerfWan)
if _, err := a2.JoinWAN([]string{addr}); err != nil {
t.Fatalf("err: %v", err)
}
retry.Run(t, func(r *retry.R) {
if got, want := len(srv1.agent.WANMembers()), 2; got < want {
if got, want := len(a1.WANMembers()), 2; got < want {
r.Fatalf("got %d WAN members want at least %d", got, want)
}
})
@ -239,7 +215,7 @@ func TestCatalogNodes_WanTranslation(t *testing.T) {
}
var out struct{}
if err := srv2.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a2.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
}
@ -247,7 +223,7 @@ func TestCatalogNodes_WanTranslation(t *testing.T) {
// Query nodes in DC2 from DC1.
req, _ := http.NewRequest("GET", "/v1/catalog/nodes?dc=dc2", nil)
resp1 := httptest.NewRecorder()
obj1, err1 := srv1.CatalogNodes(resp1, req)
obj1, err1 := a1.srv.CatalogNodes(resp1, req)
if err1 != nil {
t.Fatalf("err: %v", err1)
}
@ -270,7 +246,7 @@ func TestCatalogNodes_WanTranslation(t *testing.T) {
// Query DC2 from DC2.
resp2 := httptest.NewRecorder()
obj2, err2 := srv2.CatalogNodes(resp2, req)
obj2, err2 := a2.srv.CatalogNodes(resp2, req)
if err2 != nil {
t.Fatalf("err: %v", err2)
}
@ -292,11 +268,8 @@ func TestCatalogNodes_WanTranslation(t *testing.T) {
}
func TestCatalogNodes_Blocking(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register node
args := &structs.DCSpecificRequest{
@ -304,7 +277,7 @@ func TestCatalogNodes_Blocking(t *testing.T) {
}
var out structs.IndexedNodes
if err := srv.agent.RPC("Catalog.ListNodes", *args, &out); err != nil {
if err := a.RPC("Catalog.ListNodes", *args, &out); err != nil {
t.Fatalf("err: %v", err)
}
@ -318,7 +291,7 @@ func TestCatalogNodes_Blocking(t *testing.T) {
Address: "127.0.0.1",
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
}()
@ -326,7 +299,7 @@ func TestCatalogNodes_Blocking(t *testing.T) {
// Do a blocking read
req, _ := http.NewRequest("GET", fmt.Sprintf("/v1/catalog/nodes?wait=60s&index=%d", out.Index), nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogNodes(resp, req)
obj, err := a.srv.CatalogNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -347,11 +320,8 @@ func TestCatalogNodes_Blocking(t *testing.T) {
}
func TestCatalogNodes_DistanceSort(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register nodes.
args := &structs.RegisterRequest{
@ -360,7 +330,7 @@ func TestCatalogNodes_DistanceSort(t *testing.T) {
Address: "127.0.0.1",
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
@ -369,7 +339,7 @@ func TestCatalogNodes_DistanceSort(t *testing.T) {
Node: "bar",
Address: "127.0.0.2",
}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
@ -377,7 +347,7 @@ func TestCatalogNodes_DistanceSort(t *testing.T) {
// order they are indexed.
req, _ := http.NewRequest("GET", "/v1/catalog/nodes?dc=dc1&near=foo", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogNodes(resp, req)
obj, err := a.srv.CatalogNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -393,7 +363,7 @@ func TestCatalogNodes_DistanceSort(t *testing.T) {
if nodes[1].Node != "foo" {
t.Fatalf("bad: %v", nodes)
}
if nodes[2].Node != srv.agent.config.NodeName {
if nodes[2].Node != a.Config.NodeName {
t.Fatalf("bad: %v", nodes)
}
@ -403,7 +373,7 @@ func TestCatalogNodes_DistanceSort(t *testing.T) {
Node: "foo",
Coord: coordinate.NewCoordinate(coordinate.DefaultConfig()),
}
if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
if err := a.RPC("Coordinate.Update", &arg, &out); err != nil {
t.Fatalf("err: %v", err)
}
time.Sleep(300 * time.Millisecond)
@ -411,7 +381,7 @@ func TestCatalogNodes_DistanceSort(t *testing.T) {
// Query again and now foo should have moved to the front of the line.
req, _ = http.NewRequest("GET", "/v1/catalog/nodes?dc=dc1&near=foo", nil)
resp = httptest.NewRecorder()
obj, err = srv.CatalogNodes(resp, req)
obj, err = a.srv.CatalogNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -427,17 +397,14 @@ func TestCatalogNodes_DistanceSort(t *testing.T) {
if nodes[1].Node != "bar" {
t.Fatalf("bad: %v", nodes)
}
if nodes[2].Node != srv.agent.config.NodeName {
if nodes[2].Node != a.Config.NodeName {
t.Fatalf("bad: %v", nodes)
}
}
func TestCatalogServices(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register node
args := &structs.RegisterRequest{
@ -450,13 +417,13 @@ func TestCatalogServices(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/catalog/services?dc=dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogServices(resp, req)
obj, err := a.srv.CatalogServices(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -470,11 +437,8 @@ func TestCatalogServices(t *testing.T) {
}
func TestCatalogServices_NodeMetaFilter(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register node
args := &structs.RegisterRequest{
@ -490,13 +454,13 @@ func TestCatalogServices_NodeMetaFilter(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/catalog/services?node-meta=somekey:somevalue", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogServices(resp, req)
obj, err := a.srv.CatalogServices(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -513,17 +477,14 @@ func TestCatalogServices_NodeMetaFilter(t *testing.T) {
}
func TestCatalogServiceNodes(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Make sure an empty list is returned, not a nil
{
req, _ := http.NewRequest("GET", "/v1/catalog/service/api?tag=a", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogServiceNodes(resp, req)
obj, err := a.srv.CatalogServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -548,13 +509,13 @@ func TestCatalogServiceNodes(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/catalog/service/api?tag=a", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogServiceNodes(resp, req)
obj, err := a.srv.CatalogServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -568,17 +529,14 @@ func TestCatalogServiceNodes(t *testing.T) {
}
func TestCatalogServiceNodes_NodeMetaFilter(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Make sure an empty list is returned, not a nil
{
req, _ := http.NewRequest("GET", "/v1/catalog/service/api?node-meta=somekey:somevalue", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogServiceNodes(resp, req)
obj, err := a.srv.CatalogServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -605,13 +563,13 @@ func TestCatalogServiceNodes_NodeMetaFilter(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/catalog/service/api?node-meta=somekey:somevalue", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogServiceNodes(resp, req)
obj, err := a.srv.CatalogServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -625,34 +583,27 @@ func TestCatalogServiceNodes_NodeMetaFilter(t *testing.T) {
}
func TestCatalogServiceNodes_WanTranslation(t *testing.T) {
dir1, srv1 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc1"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir1)
defer srv1.agent.Shutdown()
testrpc.WaitForLeader(t, srv1.agent.RPC, "dc1")
c1 := TestConfig()
c1.Datacenter = "dc1"
c1.TranslateWanAddrs = true
c1.ACLDatacenter = ""
a1 := NewTestAgent(t.Name(), c1)
defer a1.Shutdown()
dir2, srv2 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc2"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir2)
defer srv2.agent.Shutdown()
testrpc.WaitForLeader(t, srv2.agent.RPC, "dc2")
c2 := TestConfig()
c2.Datacenter = "dc2"
c2.TranslateWanAddrs = true
c2.ACLDatacenter = ""
a2 := NewTestAgent(t.Name(), c2)
defer a2.Shutdown()
// Wait for the WAN join.
addr := fmt.Sprintf("127.0.0.1:%d",
srv1.agent.config.Ports.SerfWan)
if _, err := srv2.agent.JoinWAN([]string{addr}); err != nil {
addr := fmt.Sprintf("127.0.0.1:%d", a1.Config.Ports.SerfWan)
if _, err := a2.srv.agent.JoinWAN([]string{addr}); err != nil {
t.Fatalf("err: %v", err)
}
retry.Run(t, func(r *retry.R) {
if got, want := len(srv1.agent.WANMembers()), 2; got < want {
if got, want := len(a1.WANMembers()), 2; got < want {
r.Fatalf("got %d WAN members want at least %d", got, want)
}
})
@ -672,7 +623,7 @@ func TestCatalogServiceNodes_WanTranslation(t *testing.T) {
}
var out struct{}
if err := srv2.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a2.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
}
@ -680,7 +631,7 @@ func TestCatalogServiceNodes_WanTranslation(t *testing.T) {
// Query for the node in DC2 from DC1.
req, _ := http.NewRequest("GET", "/v1/catalog/service/http_wan_translation_test?dc=dc2", nil)
resp1 := httptest.NewRecorder()
obj1, err1 := srv1.CatalogServiceNodes(resp1, req)
obj1, err1 := a1.srv.CatalogServiceNodes(resp1, req)
if err1 != nil {
t.Fatalf("err: %v", err1)
}
@ -698,7 +649,7 @@ func TestCatalogServiceNodes_WanTranslation(t *testing.T) {
// Query DC2 from DC2.
resp2 := httptest.NewRecorder()
obj2, err2 := srv2.CatalogServiceNodes(resp2, req)
obj2, err2 := a2.srv.CatalogServiceNodes(resp2, req)
if err2 != nil {
t.Fatalf("err: %v", err2)
}
@ -716,11 +667,8 @@ func TestCatalogServiceNodes_WanTranslation(t *testing.T) {
}
func TestCatalogServiceNodes_DistanceSort(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register nodes.
args := &structs.RegisterRequest{
@ -733,7 +681,7 @@ func TestCatalogServiceNodes_DistanceSort(t *testing.T) {
},
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
@ -747,7 +695,7 @@ func TestCatalogServiceNodes_DistanceSort(t *testing.T) {
Tags: []string{"a"},
},
}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
@ -755,7 +703,7 @@ func TestCatalogServiceNodes_DistanceSort(t *testing.T) {
// order they are indexed.
req, _ = http.NewRequest("GET", "/v1/catalog/service/api?tag=a&near=foo", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogServiceNodes(resp, req)
obj, err := a.srv.CatalogServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -778,7 +726,7 @@ func TestCatalogServiceNodes_DistanceSort(t *testing.T) {
Node: "foo",
Coord: coordinate.NewCoordinate(coordinate.DefaultConfig()),
}
if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
if err := a.RPC("Coordinate.Update", &arg, &out); err != nil {
t.Fatalf("err: %v", err)
}
time.Sleep(300 * time.Millisecond)
@ -786,7 +734,7 @@ func TestCatalogServiceNodes_DistanceSort(t *testing.T) {
// Query again and now foo should have moved to the front of the line.
req, _ = http.NewRequest("GET", "/v1/catalog/service/api?tag=a&near=foo", nil)
resp = httptest.NewRecorder()
obj, err = srv.CatalogServiceNodes(resp, req)
obj, err = a.srv.CatalogServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -805,11 +753,8 @@ func TestCatalogServiceNodes_DistanceSort(t *testing.T) {
}
func TestCatalogNodeServices(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Register node
args := &structs.RegisterRequest{
@ -823,13 +768,13 @@ func TestCatalogNodeServices(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/catalog/node/foo?dc=dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.CatalogNodeServices(resp, req)
obj, err := a.srv.CatalogNodeServices(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -842,34 +787,27 @@ func TestCatalogNodeServices(t *testing.T) {
}
func TestCatalogNodeServices_WanTranslation(t *testing.T) {
dir1, srv1 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc1"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir1)
defer srv1.agent.Shutdown()
testrpc.WaitForLeader(t, srv1.agent.RPC, "dc1")
c1 := TestConfig()
c1.Datacenter = "dc1"
c1.TranslateWanAddrs = true
c1.ACLDatacenter = ""
a1 := NewTestAgent(t.Name(), c1)
defer a1.Shutdown()
dir2, srv2 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc2"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir2)
defer srv2.agent.Shutdown()
testrpc.WaitForLeader(t, srv2.agent.RPC, "dc2")
c2 := TestConfig()
c2.Datacenter = "dc2"
c2.TranslateWanAddrs = true
c2.ACLDatacenter = ""
a2 := NewTestAgent(t.Name(), c2)
defer a2.Shutdown()
// Wait for the WAN join.
addr := fmt.Sprintf("127.0.0.1:%d",
srv1.agent.config.Ports.SerfWan)
if _, err := srv2.agent.JoinWAN([]string{addr}); err != nil {
addr := fmt.Sprintf("127.0.0.1:%d", a1.Config.Ports.SerfWan)
if _, err := a2.srv.agent.JoinWAN([]string{addr}); err != nil {
t.Fatalf("err: %v", err)
}
retry.Run(t, func(r *retry.R) {
if got, want := len(srv1.agent.WANMembers()), 2; got < want {
if got, want := len(a1.WANMembers()), 2; got < want {
r.Fatalf("got %d WAN members want at least %d", got, want)
}
})
@ -889,7 +827,7 @@ func TestCatalogNodeServices_WanTranslation(t *testing.T) {
}
var out struct{}
if err := srv2.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a2.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
}
@ -897,7 +835,7 @@ func TestCatalogNodeServices_WanTranslation(t *testing.T) {
// Query for the node in DC2 from DC1.
req, _ := http.NewRequest("GET", "/v1/catalog/node/foo?dc=dc2", nil)
resp1 := httptest.NewRecorder()
obj1, err1 := srv1.CatalogNodeServices(resp1, req)
obj1, err1 := a1.srv.CatalogNodeServices(resp1, req)
if err1 != nil {
t.Fatalf("err: %v", err1)
}
@ -915,7 +853,7 @@ func TestCatalogNodeServices_WanTranslation(t *testing.T) {
// Query DC2 from DC2.
resp2 := httptest.NewRecorder()
obj2, err2 := srv2.CatalogNodeServices(resp2, req)
obj2, err2 := a2.srv.CatalogNodeServices(resp2, req)
if err2 != nil {
t.Fatalf("err: %v", err2)
}

View File

@ -98,11 +98,10 @@ func TestConfigFail(t *testing.T) {
}
func TestRetryJoin(t *testing.T) {
dir, agent := makeAgent(t, nextConfig())
defer os.RemoveAll(dir)
defer agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
conf2 := nextConfig()
conf2 := TestConfig()
tmpDir := testutil.TempDir(t, "consul")
defer os.RemoveAll(tmpDir)
@ -122,20 +121,20 @@ func TestRetryJoin(t *testing.T) {
serfAddr := fmt.Sprintf(
"%s:%d",
agent.config.BindAddr,
agent.config.Ports.SerfLan)
a.Config.BindAddr,
a.Config.Ports.SerfLan)
serfWanAddr := fmt.Sprintf(
"%s:%d",
agent.config.BindAddr,
agent.config.Ports.SerfWan)
a.Config.BindAddr,
a.Config.Ports.SerfWan)
args := []string{
"-server",
"-bind", agent.config.BindAddr,
"-bind", a.Config.BindAddr,
"-data-dir", tmpDir,
"-node", fmt.Sprintf(`"%s"`, conf2.NodeName),
"-advertise", agent.config.BindAddr,
"-advertise", a.Config.BindAddr,
"-retry-join", serfAddr,
"-retry-interval", "1s",
"-retry-join-wan", serfWanAddr,
@ -149,10 +148,10 @@ func TestRetryJoin(t *testing.T) {
close(doneCh)
}()
retry.Run(t, func(r *retry.R) {
if got, want := len(agent.LANMembers()), 2; got != want {
if got, want := len(a.LANMembers()), 2; got != want {
r.Fatalf("got %d LAN members want %d", got, want)
}
if got, want := len(agent.WANMembers()), 2; got != want {
if got, want := len(a.WANMembers()), 2; got != want {
r.Fatalf("got %d WAN members want %d", got, want)
}
})
@ -287,7 +286,7 @@ func TestReadCliConfig(t *testing.T) {
}
func TestRetryJoinFail(t *testing.T) {
conf := nextConfig()
conf := TestConfig()
tmpDir := testutil.TempDir(t, "consul")
defer os.RemoveAll(tmpDir)
@ -315,7 +314,7 @@ func TestRetryJoinFail(t *testing.T) {
}
func TestRetryJoinWanFail(t *testing.T) {
conf := nextConfig()
conf := TestConfig()
tmpDir := testutil.TempDir(t, "consul")
defer os.RemoveAll(tmpDir)

View File

@ -3,25 +3,20 @@ package agent
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/serf/coordinate"
)
func TestCoordinate_Datacenters(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
req, _ := http.NewRequest("GET", "/v1/coordinate/datacenters", nil)
resp := httptest.NewRecorder()
obj, err := srv.CoordinateDatacenters(resp, req)
obj, err := a.srv.CoordinateDatacenters(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -30,22 +25,19 @@ func TestCoordinate_Datacenters(t *testing.T) {
if len(maps) != 1 ||
maps[0].Datacenter != "dc1" ||
len(maps[0].Coordinates) != 1 ||
maps[0].Coordinates[0].Node != srv.agent.config.NodeName {
maps[0].Coordinates[0].Node != a.Config.NodeName {
t.Fatalf("bad: %v", maps)
}
}
func TestCoordinate_Nodes(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Make sure an empty list is non-nil.
req, _ := http.NewRequest("GET", "/v1/coordinate/nodes?dc=dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.CoordinateNodes(resp, req)
obj, err := a.srv.CoordinateNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -64,7 +56,7 @@ func TestCoordinate_Nodes(t *testing.T) {
Address: "127.0.0.1",
}
var reply struct{}
if err := srv.agent.RPC("Catalog.Register", &req, &reply); err != nil {
if err := a.RPC("Catalog.Register", &req, &reply); err != nil {
t.Fatalf("err: %s", err)
}
}
@ -77,7 +69,7 @@ func TestCoordinate_Nodes(t *testing.T) {
Coord: coordinate.NewCoordinate(coordinate.DefaultConfig()),
}
var out struct{}
if err := srv.agent.RPC("Coordinate.Update", &arg1, &out); err != nil {
if err := a.RPC("Coordinate.Update", &arg1, &out); err != nil {
t.Fatalf("err: %v", err)
}
@ -86,7 +78,7 @@ func TestCoordinate_Nodes(t *testing.T) {
Node: "bar",
Coord: coordinate.NewCoordinate(coordinate.DefaultConfig()),
}
if err := srv.agent.RPC("Coordinate.Update", &arg2, &out); err != nil {
if err := a.RPC("Coordinate.Update", &arg2, &out); err != nil {
t.Fatalf("err: %v", err)
}
time.Sleep(300 * time.Millisecond)
@ -94,7 +86,7 @@ func TestCoordinate_Nodes(t *testing.T) {
// Query back and check the nodes are present and sorted correctly.
req, _ = http.NewRequest("GET", "/v1/coordinate/nodes?dc=dc1", nil)
resp = httptest.NewRecorder()
obj, err = srv.CoordinateNodes(resp, req)
obj, err = a.srv.CoordinateNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
@ -176,13 +175,12 @@ func TestEventList_Filter(t *testing.T) {
}
func TestEventList_ACLFilter(t *testing.T) {
dir, srv := makeHTTPServerWithACLs(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), TestACLConfig())
defer a.Shutdown()
// Fire an event.
p := &UserEvent{Name: "foo"}
if err := srv.agent.UserEvent("dc1", "root", p); err != nil {
if err := a.UserEvent("dc1", "root", p); err != nil {
t.Fatalf("err: %v", err)
}
@ -190,7 +188,7 @@ func TestEventList_ACLFilter(t *testing.T) {
retry.Run(t, func(r *retry.R) {
req, _ := http.NewRequest("GET", "/v1/event/list", nil)
resp := httptest.NewRecorder()
obj, err := srv.EventList(resp, req)
obj, err := a.srv.EventList(resp, req)
if err != nil {
r.Fatal(err)
}
@ -209,7 +207,7 @@ func TestEventList_ACLFilter(t *testing.T) {
retry.Run(t, func(r *retry.R) {
req, _ := http.NewRequest("GET", "/v1/event/list?token=root", nil)
resp := httptest.NewRecorder()
obj, err := srv.EventList(resp, req)
obj, err := a.srv.EventList(resp, req)
if err != nil {
r.Fatal(err)
}

View File

@ -4,13 +4,11 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"reflect"
"testing"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/testutil/retry"
"github.com/hashicorp/serf/coordinate"
)
@ -96,11 +94,8 @@ func TestHealthChecksInState_NodeMetaFilter(t *testing.T) {
}
func TestHealthChecksInState_DistanceSort(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
args := &structs.RegisterRequest{
Datacenter: "dc1",
@ -114,18 +109,18 @@ func TestHealthChecksInState_DistanceSort(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
args.Node, args.Check.Node = "foo", "foo"
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/health/state/critical?dc=dc1&near=foo", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthChecksInState(resp, req)
obj, err := a.srv.HealthChecksInState(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -147,13 +142,13 @@ func TestHealthChecksInState_DistanceSort(t *testing.T) {
Node: "foo",
Coord: coordinate.NewCoordinate(coordinate.DefaultConfig()),
}
if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
if err := a.RPC("Coordinate.Update", &arg, &out); err != nil {
t.Fatalf("err: %v", err)
}
// Retry until foo moves to the front of the line.
retry.Run(t, func(r *retry.R) {
resp = httptest.NewRecorder()
obj, err = srv.HealthChecksInState(resp, req)
obj, err = a.srv.HealthChecksInState(resp, req)
if err != nil {
r.Fatalf("err: %v", err)
}
@ -172,15 +167,12 @@ func TestHealthChecksInState_DistanceSort(t *testing.T) {
}
func TestHealthNodeChecks(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
req, _ := http.NewRequest("GET", "/v1/health/node/nope?dc=dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthNodeChecks(resp, req)
obj, err := a.srv.HealthNodeChecks(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -192,9 +184,9 @@ func TestHealthNodeChecks(t *testing.T) {
t.Fatalf("bad: %v", obj)
}
req, _ = http.NewRequest("GET", fmt.Sprintf("/v1/health/node/%s?dc=dc1", srv.agent.config.NodeName), nil)
req, _ = http.NewRequest("GET", fmt.Sprintf("/v1/health/node/%s?dc=dc1", a.Config.NodeName), nil)
resp = httptest.NewRecorder()
obj, err = srv.HealthNodeChecks(resp, req)
obj, err = a.srv.HealthNodeChecks(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -208,15 +200,12 @@ func TestHealthNodeChecks(t *testing.T) {
}
func TestHealthServiceChecks(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
req, _ := http.NewRequest("GET", "/v1/health/checks/consul?dc=dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthServiceChecks(resp, req)
obj, err := a.srv.HealthServiceChecks(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -231,23 +220,23 @@ func TestHealthServiceChecks(t *testing.T) {
// Create a service check
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: srv.agent.config.NodeName,
Node: a.Config.NodeName,
Address: "127.0.0.1",
Check: &structs.HealthCheck{
Node: srv.agent.config.NodeName,
Node: a.Config.NodeName,
Name: "consul check",
ServiceID: "consul",
},
}
var out struct{}
if err = srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err = a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ = http.NewRequest("GET", "/v1/health/checks/consul?dc=dc1", nil)
resp = httptest.NewRecorder()
obj, err = srv.HealthServiceChecks(resp, req)
obj, err = a.srv.HealthServiceChecks(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -261,15 +250,12 @@ func TestHealthServiceChecks(t *testing.T) {
}
func TestHealthServiceChecks_NodeMetaFilter(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
req, _ := http.NewRequest("GET", "/v1/health/checks/consul?dc=dc1&node-meta=somekey:somevalue", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthServiceChecks(resp, req)
obj, err := a.srv.HealthServiceChecks(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -284,24 +270,24 @@ func TestHealthServiceChecks_NodeMetaFilter(t *testing.T) {
// Create a service check
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: srv.agent.config.NodeName,
Node: a.Config.NodeName,
Address: "127.0.0.1",
NodeMeta: map[string]string{"somekey": "somevalue"},
Check: &structs.HealthCheck{
Node: srv.agent.config.NodeName,
Node: a.Config.NodeName,
Name: "consul check",
ServiceID: "consul",
},
}
var out struct{}
if err = srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err = a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ = http.NewRequest("GET", "/v1/health/checks/consul?dc=dc1&node-meta=somekey:somevalue", nil)
resp = httptest.NewRecorder()
obj, err = srv.HealthServiceChecks(resp, req)
obj, err = a.srv.HealthServiceChecks(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -315,11 +301,8 @@ func TestHealthServiceChecks_NodeMetaFilter(t *testing.T) {
}
func TestHealthServiceChecks_DistanceSort(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Create a service check
args := &structs.RegisterRequest{
@ -338,18 +321,18 @@ func TestHealthServiceChecks_DistanceSort(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
args.Node, args.Check.Node = "foo", "foo"
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/health/checks/test?dc=dc1&near=foo", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthServiceChecks(resp, req)
obj, err := a.srv.HealthServiceChecks(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -371,13 +354,13 @@ func TestHealthServiceChecks_DistanceSort(t *testing.T) {
Node: "foo",
Coord: coordinate.NewCoordinate(coordinate.DefaultConfig()),
}
if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
if err := a.RPC("Coordinate.Update", &arg, &out); err != nil {
t.Fatalf("err: %v", err)
}
// Retry until foo has moved to the front of the line.
retry.Run(t, func(r *retry.R) {
resp = httptest.NewRecorder()
obj, err = srv.HealthServiceChecks(resp, req)
obj, err = a.srv.HealthServiceChecks(resp, req)
if err != nil {
r.Fatalf("err: %v", err)
}
@ -396,15 +379,12 @@ func TestHealthServiceChecks_DistanceSort(t *testing.T) {
}
func TestHealthServiceNodes(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
req, _ := http.NewRequest("GET", "/v1/health/service/consul?dc=dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthServiceNodes(resp, req)
obj, err := a.srv.HealthServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -419,7 +399,7 @@ func TestHealthServiceNodes(t *testing.T) {
req, _ = http.NewRequest("GET", "/v1/health/service/nope?dc=dc1", nil)
resp = httptest.NewRecorder()
obj, err = srv.HealthServiceNodes(resp, req)
obj, err = a.srv.HealthServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -443,13 +423,13 @@ func TestHealthServiceNodes(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ = http.NewRequest("GET", "/v1/health/service/test?dc=dc1", nil)
resp = httptest.NewRecorder()
obj, err = srv.HealthServiceNodes(resp, req)
obj, err = a.srv.HealthServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -464,15 +444,12 @@ func TestHealthServiceNodes(t *testing.T) {
}
func TestHealthServiceNodes_NodeMetaFilter(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
req, _ := http.NewRequest("GET", "/v1/health/service/consul?dc=dc1&node-meta=somekey:somevalue", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthServiceNodes(resp, req)
obj, err := a.srv.HealthServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -497,13 +474,13 @@ func TestHealthServiceNodes_NodeMetaFilter(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ = http.NewRequest("GET", "/v1/health/service/test?dc=dc1&node-meta=somekey:somevalue", nil)
resp = httptest.NewRecorder()
obj, err = srv.HealthServiceNodes(resp, req)
obj, err = a.srv.HealthServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -518,11 +495,8 @@ func TestHealthServiceNodes_NodeMetaFilter(t *testing.T) {
}
func TestHealthServiceNodes_DistanceSort(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Create a service check
args := &structs.RegisterRequest{
@ -541,18 +515,18 @@ func TestHealthServiceNodes_DistanceSort(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
args.Node, args.Check.Node = "foo", "foo"
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/health/service/test?dc=dc1&near=foo", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthServiceNodes(resp, req)
obj, err := a.srv.HealthServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -574,13 +548,13 @@ func TestHealthServiceNodes_DistanceSort(t *testing.T) {
Node: "foo",
Coord: coordinate.NewCoordinate(coordinate.DefaultConfig()),
}
if err := srv.agent.RPC("Coordinate.Update", &arg, &out); err != nil {
if err := a.RPC("Coordinate.Update", &arg, &out); err != nil {
t.Fatalf("err: %v", err)
}
// Retry until foo has moved to the front of the line.
retry.Run(t, func(r *retry.R) {
resp = httptest.NewRecorder()
obj, err = srv.HealthServiceNodes(resp, req)
obj, err = a.srv.HealthServiceNodes(resp, req)
if err != nil {
r.Fatalf("err: %v", err)
}
@ -599,19 +573,16 @@ func TestHealthServiceNodes_DistanceSort(t *testing.T) {
}
func TestHealthServiceNodes_PassingFilter(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Create a failing service check
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: srv.agent.config.NodeName,
Node: a.Config.NodeName,
Address: "127.0.0.1",
Check: &structs.HealthCheck{
Node: srv.agent.config.NodeName,
Node: a.Config.NodeName,
Name: "consul check",
ServiceID: "consul",
Status: api.HealthCritical,
@ -619,13 +590,13 @@ func TestHealthServiceNodes_PassingFilter(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/health/service/consul?passing", nil)
resp := httptest.NewRecorder()
obj, err := srv.HealthServiceNodes(resp, req)
obj, err := a.srv.HealthServiceNodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -640,33 +611,27 @@ func TestHealthServiceNodes_PassingFilter(t *testing.T) {
}
func TestHealthServiceNodes_WanTranslation(t *testing.T) {
dir1, srv1 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc1"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir1)
defer srv1.agent.Shutdown()
testrpc.WaitForLeader(t, srv1.agent.RPC, "dc1")
c1 := TestConfig()
c1.Datacenter = "dc1"
c1.TranslateWanAddrs = true
c1.ACLDatacenter = ""
a1 := NewTestAgent(t.Name(), c1)
defer a1.Shutdown()
dir2, srv2 := makeHTTPServerWithConfig(t,
func(c *Config) {
c.Datacenter = "dc2"
c.TranslateWanAddrs = true
c.ACLDatacenter = ""
})
defer os.RemoveAll(dir2)
defer srv2.agent.Shutdown()
testrpc.WaitForLeader(t, srv2.agent.RPC, "dc2")
c2 := TestConfig()
c2.Datacenter = "dc2"
c2.TranslateWanAddrs = true
c2.ACLDatacenter = ""
a2 := NewTestAgent(t.Name(), c2)
defer a2.Shutdown()
// Wait for the WAN join.
addr := fmt.Sprintf("127.0.0.1:%d", srv1.agent.config.Ports.SerfWan)
if _, err := srv2.agent.JoinWAN([]string{addr}); err != nil {
addr := fmt.Sprintf("127.0.0.1:%d", a1.Config.Ports.SerfWan)
if _, err := a2.JoinWAN([]string{addr}); err != nil {
t.Fatalf("err: %v", err)
}
retry.Run(t, func(r *retry.R) {
if got, want := len(srv1.agent.WANMembers()), 2; got < want {
if got, want := len(a1.WANMembers()), 2; got < want {
r.Fatalf("got %d WAN members want at least %d", got, want)
}
})
@ -686,7 +651,7 @@ func TestHealthServiceNodes_WanTranslation(t *testing.T) {
}
var out struct{}
if err := srv2.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a2.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
}
@ -694,7 +659,7 @@ func TestHealthServiceNodes_WanTranslation(t *testing.T) {
// Query for a service in DC2 from DC1.
req, _ := http.NewRequest("GET", "/v1/health/service/http_wan_translation_test?dc=dc2", nil)
resp1 := httptest.NewRecorder()
obj1, err1 := srv1.HealthServiceNodes(resp1, req)
obj1, err1 := a1.srv.HealthServiceNodes(resp1, req)
if err1 != nil {
t.Fatalf("err: %v", err1)
}
@ -712,7 +677,7 @@ func TestHealthServiceNodes_WanTranslation(t *testing.T) {
// Query DC2 from DC2.
resp2 := httptest.NewRecorder()
obj2, err2 := srv2.HealthServiceNodes(resp2, req)
obj2, err2 := a2.srv.HealthServiceNodes(resp2, req)
if err2 != nil {
t.Fatalf("err: %v", err2)
}

View File

@ -7,7 +7,6 @@ import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
@ -20,46 +19,10 @@ import (
"time"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/logger"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/testutil"
"github.com/hashicorp/go-cleanhttp"
)
func makeHTTPServer(t *testing.T) (string, *HTTPServer) {
return makeHTTPServerWithConfig(t, nil)
}
func makeHTTPServerWithConfig(t *testing.T, cb func(c *Config)) (string, *HTTPServer) {
return makeHTTPServerWithConfigLog(t, cb, nil, nil)
}
func makeHTTPServerWithACLs(t *testing.T) (string, *HTTPServer) {
dir, srv := makeHTTPServerWithConfig(t, func(c *Config) {
c.ACLDatacenter = c.Datacenter
c.ACLDefaultPolicy = "deny"
c.ACLMasterToken = "root"
c.ACLAgentToken = "root"
c.ACLAgentMasterToken = "towel"
c.ACLEnforceVersion8 = Bool(true)
})
// Need a leader to look up ACLs, so wait here so we don't need to
// repeat this in each test.
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
return dir, srv
}
func makeHTTPServerWithConfigLog(t *testing.T, cb func(c *Config), l io.Writer, logWriter *logger.LogWriter) (string, *HTTPServer) {
conf := nextConfig()
if cb != nil {
cb(conf)
}
dir, agent := makeAgentLog(t, conf, l, logWriter)
return dir, agent.httpServers[0]
}
func TestHTTPServer_UnixSocket(t *testing.T) {
if runtime.GOOS == "windows" {
t.SkipNow()
@ -69,16 +32,15 @@ func TestHTTPServer_UnixSocket(t *testing.T) {
defer os.RemoveAll(tempDir)
socket := filepath.Join(tempDir, "test.sock")
dir, srv := makeHTTPServerWithConfig(t, func(c *Config) {
c.Addresses.HTTP = "unix://" + socket
c := TestConfig()
c.Addresses.HTTP = "unix://" + socket
// Only testing mode, since uid/gid might not be settable
// from test environment.
c.UnixSockets = UnixSocketConfig{}
c.UnixSockets.Perms = "0777"
})
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
// Only testing mode, since uid/gid might not be settable
// from test environment.
c.UnixSockets = UnixSocketConfig{}
c.UnixSockets.Perms = "0777"
a := NewTestAgent(t.Name(), c)
defer a.Shutdown()
// Ensure the socket was created
if _, err := os.Stat(socket); err != nil {
@ -95,7 +57,7 @@ func TestHTTPServer_UnixSocket(t *testing.T) {
}
// Ensure we can get a response from the socket.
path := socketPath(srv.agent.config.Addresses.HTTP)
path := socketPath(a.Config.Addresses.HTTP)
trans := cleanhttp.DefaultTransport()
trans.DialContext = func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", path)
@ -139,14 +101,11 @@ func TestHTTPServer_UnixSocket_FileExists(t *testing.T) {
t.Fatalf("not a regular file: %s", socket)
}
conf := nextConfig()
conf := TestConfig()
conf.Addresses.HTTP = "unix://" + socket
a := NewTestAgent(t.Name(), conf)
defer a.Shutdown()
dir, agent := makeAgent(t, conf)
defer os.RemoveAll(dir)
defer agent.Shutdown()
defer agent.Shutdown()
// Ensure the file was replaced by the socket
fi, err = os.Stat(socket)
if err != nil {
@ -219,9 +178,8 @@ func TestSetMeta(t *testing.T) {
func TestHTTPAPI_TranslateAddrHeader(t *testing.T) {
// Header should not be present if address translation is off.
{
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
resp := httptest.NewRecorder()
handler := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
@ -229,7 +187,7 @@ func TestHTTPAPI_TranslateAddrHeader(t *testing.T) {
}
req, _ := http.NewRequest("GET", "/v1/agent/self", nil)
srv.wrap(handler)(resp, req)
a.srv.wrap(handler)(resp, req)
translate := resp.Header().Get("X-Consul-Translate-Addresses")
if translate != "" {
@ -239,10 +197,10 @@ func TestHTTPAPI_TranslateAddrHeader(t *testing.T) {
// Header should be set to true if it's turned on.
{
dir, srv := makeHTTPServer(t)
srv.agent.config.TranslateWanAddrs = true
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
c := TestConfig()
c.TranslateWanAddrs = true
a := NewTestAgent(t.Name(), c)
defer a.Shutdown()
resp := httptest.NewRecorder()
handler := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
@ -250,7 +208,7 @@ func TestHTTPAPI_TranslateAddrHeader(t *testing.T) {
}
req, _ := http.NewRequest("GET", "/v1/agent/self", nil)
srv.wrap(handler)(resp, req)
a.srv.wrap(handler)(resp, req)
translate := resp.Header().Get("X-Consul-Translate-Addresses")
if translate != "true" {
@ -260,23 +218,21 @@ func TestHTTPAPI_TranslateAddrHeader(t *testing.T) {
}
func TestHTTPAPIResponseHeaders(t *testing.T) {
dir, srv := makeHTTPServer(t)
srv.agent.config.HTTPAPIResponseHeaders = map[string]string{
c := TestConfig()
c.HTTPAPIResponseHeaders = map[string]string{
"Access-Control-Allow-Origin": "*",
"X-XSS-Protection": "1; mode=block",
}
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), c)
defer a.Shutdown()
resp := httptest.NewRecorder()
handler := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
return nil, nil
}
req, _ := http.NewRequest("GET", "/v1/agent/self", nil)
srv.wrap(handler)(resp, req)
a.srv.wrap(handler)(resp, req)
origin := resp.Header().Get("Access-Control-Allow-Origin")
if origin != "*" {
@ -290,20 +246,17 @@ func TestHTTPAPIResponseHeaders(t *testing.T) {
}
func TestContentTypeIsJSON(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
resp := httptest.NewRecorder()
handler := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// stub out a DirEntry so that it will be encoded as JSON
return &structs.DirEntry{Key: "key"}, nil
}
req, _ := http.NewRequest("GET", "/v1/kv/key", nil)
srv.wrap(handler)(resp, req)
a.srv.wrap(handler)(resp, req)
contentType := resp.Header().Get("Content-Type")
@ -313,20 +266,17 @@ func TestContentTypeIsJSON(t *testing.T) {
}
func TestHTTP_wrap_obfuscateLog(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
// Attach a custom logger so we can inspect it
buf := &bytes.Buffer{}
srv.agent.logger = log.New(buf, "", log.LstdFlags)
buf := new(bytes.Buffer)
a := &TestAgent{Name: t.Name(), LogOutput: buf}
a.Start()
defer a.Shutdown()
resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/some/url?token=secret1&token=secret2", nil)
handler := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
return nil, nil
}
srv.wrap(handler)(resp, req)
a.srv.wrap(handler)(resp, req)
// Make sure no tokens from the URL show up in the log
if strings.Contains(buf.String(), "secret") {
@ -343,9 +293,8 @@ func TestPrettyPrintBare(t *testing.T) {
}
func testPrettyPrint(pretty string, t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
r := &structs.DirEntry{Key: "key"}
@ -356,7 +305,7 @@ func testPrettyPrint(pretty string, t *testing.T) {
urlStr := "/v1/kv/key?" + pretty
req, _ := http.NewRequest("GET", urlStr, nil)
srv.wrap(handler)(resp, req)
a.srv.wrap(handler)(resp, req)
expected, _ := json.MarshalIndent(r, "", " ")
expected = append(expected, "\n"...)
@ -371,15 +320,14 @@ func testPrettyPrint(pretty string, t *testing.T) {
}
func TestParseSource(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
// Default is agent's DC and no node (since the user didn't care, then
// just give them the cheapest possible query).
req, _ := http.NewRequest("GET", "/v1/catalog/nodes", nil)
source := structs.QuerySource{}
srv.parseSource(req, &source)
a.srv.parseSource(req, &source)
if source.Datacenter != "dc1" || source.Node != "" {
t.Fatalf("bad: %v", source)
}
@ -387,7 +335,7 @@ func TestParseSource(t *testing.T) {
// Adding the source parameter should set that node.
req, _ = http.NewRequest("GET", "/v1/catalog/nodes?near=bob", nil)
source = structs.QuerySource{}
srv.parseSource(req, &source)
a.srv.parseSource(req, &source)
if source.Datacenter != "dc1" || source.Node != "bob" {
t.Fatalf("bad: %v", source)
}
@ -396,7 +344,7 @@ func TestParseSource(t *testing.T) {
// looked up correctly on the receiving end.
req, _ = http.NewRequest("GET", "/v1/catalog/nodes?near=bob&dc=foo", nil)
source = structs.QuerySource{}
srv.parseSource(req, &source)
a.srv.parseSource(req, &source)
if source.Datacenter != "foo" || source.Node != "bob" {
t.Fatalf("bad: %v", source)
}
@ -404,8 +352,8 @@ func TestParseSource(t *testing.T) {
// The magic "_agent" node name will use the agent's local node name.
req, _ = http.NewRequest("GET", "/v1/catalog/nodes?near=_agent", nil)
source = structs.QuerySource{}
srv.parseSource(req, &source)
if source.Datacenter != "dc1" || source.Node != srv.agent.config.NodeName {
a.srv.parseSource(req, &source)
if source.Datacenter != "dc1" || source.Node != a.Config.NodeName {
t.Fatalf("bad: %v", source)
}
}
@ -552,11 +500,8 @@ func TestACLResolution(t *testing.T) {
func TestEnableWebUI(t *testing.T) {
httpTestWithConfig(t, func(s *HTTPServer) {
req, _ := http.NewRequest("GET", "/ui/", nil)
// Perform the request
resp := httptest.NewRecorder()
s.Handler.ServeHTTP(resp, req)
// Check the result
if resp.Code != 200 {
t.Fatalf("should handle ui")
}
@ -600,11 +545,13 @@ func httpTest(t *testing.T, f func(srv *HTTPServer)) {
}
func httpTestWithConfig(t *testing.T, f func(srv *HTTPServer), cb func(c *Config)) {
dir, srv := makeHTTPServerWithConfig(t, cb)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
f(srv)
c := TestConfig()
if cb != nil {
cb(c)
}
a := NewTestAgent(t.Name(), c)
defer a.Shutdown()
f(a.srv)
}
func isPermissionDenied(err error) bool {

View File

@ -8,7 +8,6 @@ import (
"strings"
"testing"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/testutil"
)
@ -16,63 +15,60 @@ func TestAgent_LoadKeyrings(t *testing.T) {
key := "tbLJg26ZJyJ9pK3qhc9jig=="
// Should be no configured keyring file by default
conf1 := nextConfig()
dir1, agent1 := makeAgent(t, conf1)
defer os.RemoveAll(dir1)
defer agent1.Shutdown()
a1 := NewTestAgent(t.Name(), nil)
defer a1.Shutdown()
c := agent1.config.ConsulConfig
if c.SerfLANConfig.KeyringFile != "" {
t.Fatalf("bad: %#v", c.SerfLANConfig.KeyringFile)
c1 := a1.Config.ConsulConfig
if c1.SerfLANConfig.KeyringFile != "" {
t.Fatalf("bad: %#v", c1.SerfLANConfig.KeyringFile)
}
if c.SerfLANConfig.MemberlistConfig.Keyring != nil {
if c1.SerfLANConfig.MemberlistConfig.Keyring != nil {
t.Fatalf("keyring should not be loaded")
}
if c.SerfWANConfig.KeyringFile != "" {
t.Fatalf("bad: %#v", c.SerfLANConfig.KeyringFile)
if c1.SerfWANConfig.KeyringFile != "" {
t.Fatalf("bad: %#v", c1.SerfLANConfig.KeyringFile)
}
if c.SerfWANConfig.MemberlistConfig.Keyring != nil {
if c1.SerfWANConfig.MemberlistConfig.Keyring != nil {
t.Fatalf("keyring should not be loaded")
}
// Server should auto-load LAN and WAN keyring files
conf2 := nextConfig()
dir2, agent2 := makeAgentKeyring(t, conf2, key)
defer os.RemoveAll(dir2)
defer agent2.Shutdown()
a2 := &TestAgent{Name: t.Name(), Key: key}
a2.Start()
defer a2.Shutdown()
c = agent2.config.ConsulConfig
if c.SerfLANConfig.KeyringFile == "" {
c2 := a2.Config.ConsulConfig
if c2.SerfLANConfig.KeyringFile == "" {
t.Fatalf("should have keyring file")
}
if c.SerfLANConfig.MemberlistConfig.Keyring == nil {
if c2.SerfLANConfig.MemberlistConfig.Keyring == nil {
t.Fatalf("keyring should be loaded")
}
if c.SerfWANConfig.KeyringFile == "" {
if c2.SerfWANConfig.KeyringFile == "" {
t.Fatalf("should have keyring file")
}
if c.SerfWANConfig.MemberlistConfig.Keyring == nil {
if c2.SerfWANConfig.MemberlistConfig.Keyring == nil {
t.Fatalf("keyring should be loaded")
}
// Client should auto-load only the LAN keyring file
conf3 := nextConfig()
conf3 := TestConfig()
conf3.Server = false
dir3, agent3 := makeAgentKeyring(t, conf3, key)
defer os.RemoveAll(dir3)
defer agent3.Shutdown()
a3 := &TestAgent{Name: t.Name(), Config: conf3, Key: key}
a3.Start()
defer a3.Shutdown()
c = agent3.config.ConsulConfig
if c.SerfLANConfig.KeyringFile == "" {
c3 := a3.Config.ConsulConfig
if c3.SerfLANConfig.KeyringFile == "" {
t.Fatalf("should have keyring file")
}
if c.SerfLANConfig.MemberlistConfig.Keyring == nil {
if c3.SerfLANConfig.MemberlistConfig.Keyring == nil {
t.Fatalf("keyring should be loaded")
}
if c.SerfWANConfig.KeyringFile != "" {
t.Fatalf("bad: %#v", c.SerfWANConfig.KeyringFile)
if c3.SerfWANConfig.KeyringFile != "" {
t.Fatalf("bad: %#v", c3.SerfWANConfig.KeyringFile)
}
if c.SerfWANConfig.MemberlistConfig.Keyring != nil {
if c3.SerfWANConfig.MemberlistConfig.Keyring != nil {
t.Fatalf("keyring should not be loaded")
}
}
@ -119,60 +115,58 @@ func TestAgentKeyring_ACL(t *testing.T) {
key1 := "tbLJg26ZJyJ9pK3qhc9jig=="
key2 := "4leC33rgtXKIVUr9Nr0snQ=="
conf := nextConfig()
conf := TestACLConfig()
conf.ACLDatacenter = "dc1"
conf.ACLMasterToken = "root"
conf.ACLDefaultPolicy = "deny"
dir, agent := makeAgentKeyring(t, conf, key1)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := &TestAgent{Name: t.Name(), Config: conf, Key: key1}
a.Start()
defer a.Shutdown()
// List keys without access fails
_, err := agent.ListKeys("", 0)
_, err := a.ListKeys("", 0)
if err == nil || !strings.Contains(err.Error(), "denied") {
t.Fatalf("expected denied error, got: %#v", err)
}
// List keys with access works
_, err = agent.ListKeys("root", 0)
_, err = a.ListKeys("root", 0)
if err != nil {
t.Fatalf("err: %s", err)
}
// Install without access fails
_, err = agent.InstallKey(key2, "", 0)
_, err = a.InstallKey(key2, "", 0)
if err == nil || !strings.Contains(err.Error(), "denied") {
t.Fatalf("expected denied error, got: %#v", err)
}
// Install with access works
_, err = agent.InstallKey(key2, "root", 0)
_, err = a.InstallKey(key2, "root", 0)
if err != nil {
t.Fatalf("err: %s", err)
}
// Use without access fails
_, err = agent.UseKey(key2, "", 0)
_, err = a.UseKey(key2, "", 0)
if err == nil || !strings.Contains(err.Error(), "denied") {
t.Fatalf("expected denied error, got: %#v", err)
}
// Use with access works
_, err = agent.UseKey(key2, "root", 0)
_, err = a.UseKey(key2, "root", 0)
if err != nil {
t.Fatalf("err: %s", err)
}
// Remove without access fails
_, err = agent.RemoveKey(key1, "", 0)
_, err = a.RemoveKey(key1, "", 0)
if err == nil || !strings.Contains(err.Error(), "denied") {
t.Fatalf("expected denied error, got: %#v", err)
}
// Remove with access works
_, err = agent.RemoveKey(key1, "root", 0)
_, err = a.RemoveKey(key1, "root", 0)
if err != nil {
t.Fatalf("err: %s", err)
}

View File

@ -5,20 +5,15 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"reflect"
"testing"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
)
func TestKVSEndpoint_PUT_GET_DELETE(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
keys := []string{
"baz",
@ -32,7 +27,7 @@ func TestKVSEndpoint_PUT_GET_DELETE(t *testing.T) {
buf := bytes.NewBuffer([]byte("test"))
req, _ := http.NewRequest("PUT", "/v1/kv/"+key, buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -45,7 +40,7 @@ func TestKVSEndpoint_PUT_GET_DELETE(t *testing.T) {
for _, key := range keys {
req, _ := http.NewRequest("GET", "/v1/kv/"+key, nil)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -68,18 +63,15 @@ func TestKVSEndpoint_PUT_GET_DELETE(t *testing.T) {
for _, key := range keys {
req, _ := http.NewRequest("DELETE", "/v1/kv/"+key, nil)
resp := httptest.NewRecorder()
if _, err := srv.KVSEndpoint(resp, req); err != nil {
if _, err := a.srv.KVSEndpoint(resp, req); err != nil {
t.Fatalf("err: %v", err)
}
}
}
func TestKVSEndpoint_Recurse(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
keys := []string{
"bar",
@ -93,7 +85,7 @@ func TestKVSEndpoint_Recurse(t *testing.T) {
buf := bytes.NewBuffer([]byte("test"))
req, _ := http.NewRequest("PUT", "/v1/kv/"+key, buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -107,7 +99,7 @@ func TestKVSEndpoint_Recurse(t *testing.T) {
// Get all the keys
req, _ := http.NewRequest("GET", "/v1/kv/?recurse", nil)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -132,7 +124,7 @@ func TestKVSEndpoint_Recurse(t *testing.T) {
{
req, _ := http.NewRequest("DELETE", "/v1/kv/?recurse", nil)
resp := httptest.NewRecorder()
if _, err := srv.KVSEndpoint(resp, req); err != nil {
if _, err := a.srv.KVSEndpoint(resp, req); err != nil {
t.Fatalf("err: %v", err)
}
}
@ -141,7 +133,7 @@ func TestKVSEndpoint_Recurse(t *testing.T) {
// Get all the keys
req, _ := http.NewRequest("GET", "/v1/kv/?recurse", nil)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -153,17 +145,14 @@ func TestKVSEndpoint_Recurse(t *testing.T) {
}
func TestKVSEndpoint_DELETE_CAS(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
{
buf := bytes.NewBuffer([]byte("test"))
req, _ := http.NewRequest("PUT", "/v1/kv/test", buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -175,7 +164,7 @@ func TestKVSEndpoint_DELETE_CAS(t *testing.T) {
req, _ := http.NewRequest("GET", "/v1/kv/test", nil)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -186,7 +175,7 @@ func TestKVSEndpoint_DELETE_CAS(t *testing.T) {
buf := bytes.NewBuffer([]byte("zip"))
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/v1/kv/test?cas=%d", d.ModifyIndex-1), buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -201,7 +190,7 @@ func TestKVSEndpoint_DELETE_CAS(t *testing.T) {
buf := bytes.NewBuffer([]byte("zip"))
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/v1/kv/test?cas=%d", d.ModifyIndex), buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -214,24 +203,21 @@ func TestKVSEndpoint_DELETE_CAS(t *testing.T) {
// Verify the delete
req, _ = http.NewRequest("GET", "/v1/kv/test", nil)
resp = httptest.NewRecorder()
obj, _ = srv.KVSEndpoint(resp, req)
obj, _ = a.srv.KVSEndpoint(resp, req)
if obj != nil {
t.Fatalf("should be destroyed")
}
}
func TestKVSEndpoint_CAS(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
{
buf := bytes.NewBuffer([]byte("test"))
req, _ := http.NewRequest("PUT", "/v1/kv/test?flags=50", buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -243,7 +229,7 @@ func TestKVSEndpoint_CAS(t *testing.T) {
req, _ := http.NewRequest("GET", "/v1/kv/test", nil)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -259,7 +245,7 @@ func TestKVSEndpoint_CAS(t *testing.T) {
buf := bytes.NewBuffer([]byte("zip"))
req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/kv/test?flags=42&cas=%d", d.ModifyIndex-1), buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -274,7 +260,7 @@ func TestKVSEndpoint_CAS(t *testing.T) {
buf := bytes.NewBuffer([]byte("zip"))
req, _ := http.NewRequest("PUT", fmt.Sprintf("/v1/kv/test?flags=42&cas=%d", d.ModifyIndex), buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -287,7 +273,7 @@ func TestKVSEndpoint_CAS(t *testing.T) {
// Verify the update
req, _ = http.NewRequest("GET", "/v1/kv/test", nil)
resp = httptest.NewRecorder()
obj, _ = srv.KVSEndpoint(resp, req)
obj, _ = a.srv.KVSEndpoint(resp, req)
d = obj.(structs.DirEntries)[0]
if d.Flags != 42 {
@ -299,11 +285,8 @@ func TestKVSEndpoint_CAS(t *testing.T) {
}
func TestKVSEndpoint_ListKeys(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
keys := []string{
"bar",
@ -317,7 +300,7 @@ func TestKVSEndpoint_ListKeys(t *testing.T) {
buf := bytes.NewBuffer([]byte("test"))
req, _ := http.NewRequest("PUT", "/v1/kv/"+key, buf)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -331,7 +314,7 @@ func TestKVSEndpoint_ListKeys(t *testing.T) {
// Get all the keys
req, _ := http.NewRequest("GET", "/v1/kv/?keys&seperator=/", nil)
resp := httptest.NewRecorder()
obj, err := srv.KVSEndpoint(resp, req)
obj, err := a.srv.KVSEndpoint(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}

File diff suppressed because it is too large Load Diff

View File

@ -4,14 +4,12 @@ import (
"bytes"
"encoding/json"
"fmt"
"os"
"reflect"
"testing"
"time"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/go-uuid"
)
@ -95,12 +93,12 @@ func TestRexecWriter(t *testing.T) {
}
func TestRemoteExecGetSpec(t *testing.T) {
config := nextConfig()
config := TestConfig()
testRemoteExecGetSpec(t, config)
}
func TestRemoteExecGetSpec_ACLToken(t *testing.T) {
config := nextConfig()
config := TestConfig()
config.ACLDatacenter = "dc1"
config.ACLToken = "root"
config.ACLDefaultPolicy = "deny"
@ -108,16 +106,14 @@ func TestRemoteExecGetSpec_ACLToken(t *testing.T) {
}
func testRemoteExecGetSpec(t *testing.T, c *Config) {
dir, agent := makeAgent(t, c)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
event := &remoteExecEvent{
Prefix: "_rexec",
Session: makeRexecSession(t, agent),
Session: makeRexecSession(t, a.Agent),
}
defer destroySession(t, agent, event.Session)
defer destroySession(t, a.Agent, event.Session)
spec := &remoteExecSpec{
Command: "uptime",
@ -129,10 +125,10 @@ func testRemoteExecGetSpec(t *testing.T, c *Config) {
t.Fatalf("err: %v", err)
}
key := "_rexec/" + event.Session + "/job"
setKV(t, agent, key, buf)
setKV(t, a.Agent, key, buf)
var out remoteExecSpec
if !agent.remoteExecGetSpec(event, &out) {
if !a.remoteExecGetSpec(event, &out) {
t.Fatalf("bad")
}
if !reflect.DeepEqual(spec, &out) {
@ -141,12 +137,12 @@ func testRemoteExecGetSpec(t *testing.T, c *Config) {
}
func TestRemoteExecWrites(t *testing.T) {
config := nextConfig()
config := TestConfig()
testRemoteExecWrites(t, config)
}
func TestRemoteExecWrites_ACLToken(t *testing.T) {
config := nextConfig()
config := TestConfig()
config.ACLDatacenter = "dc1"
config.ACLToken = "root"
config.ACLDefaultPolicy = "deny"
@ -154,70 +150,66 @@ func TestRemoteExecWrites_ACLToken(t *testing.T) {
}
func testRemoteExecWrites(t *testing.T, c *Config) {
dir, agent := makeAgent(t, c)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
event := &remoteExecEvent{
Prefix: "_rexec",
Session: makeRexecSession(t, agent),
Session: makeRexecSession(t, a.Agent),
}
defer destroySession(t, agent, event.Session)
defer destroySession(t, a.Agent, event.Session)
if !agent.remoteExecWriteAck(event) {
if !a.remoteExecWriteAck(event) {
t.Fatalf("bad")
}
output := []byte("testing")
if !agent.remoteExecWriteOutput(event, 0, output) {
if !a.remoteExecWriteOutput(event, 0, output) {
t.Fatalf("bad")
}
if !agent.remoteExecWriteOutput(event, 10, output) {
if !a.remoteExecWriteOutput(event, 10, output) {
t.Fatalf("bad")
}
exitCode := 1
if !agent.remoteExecWriteExitCode(event, &exitCode) {
if !a.remoteExecWriteExitCode(event, &exitCode) {
t.Fatalf("bad")
}
key := "_rexec/" + event.Session + "/" + agent.config.NodeName + "/ack"
d := getKV(t, agent, key)
key := "_rexec/" + event.Session + "/" + a.Config.NodeName + "/ack"
d := getKV(t, a.Agent, key)
if d == nil || d.Session != event.Session {
t.Fatalf("bad ack: %#v", d)
}
key = "_rexec/" + event.Session + "/" + agent.config.NodeName + "/out/00000"
d = getKV(t, agent, key)
key = "_rexec/" + event.Session + "/" + a.Config.NodeName + "/out/00000"
d = getKV(t, a.Agent, key)
if d == nil || d.Session != event.Session || !bytes.Equal(d.Value, output) {
t.Fatalf("bad output: %#v", d)
}
key = "_rexec/" + event.Session + "/" + agent.config.NodeName + "/out/0000a"
d = getKV(t, agent, key)
key = "_rexec/" + event.Session + "/" + a.Config.NodeName + "/out/0000a"
d = getKV(t, a.Agent, key)
if d == nil || d.Session != event.Session || !bytes.Equal(d.Value, output) {
t.Fatalf("bad output: %#v", d)
}
key = "_rexec/" + event.Session + "/" + agent.config.NodeName + "/exit"
d = getKV(t, agent, key)
key = "_rexec/" + event.Session + "/" + a.Config.NodeName + "/exit"
d = getKV(t, a.Agent, key)
if d == nil || d.Session != event.Session || string(d.Value) != "1" {
t.Fatalf("bad output: %#v", d)
}
}
func testHandleRemoteExec(t *testing.T, command string, expectedSubstring string, expectedReturnCode string) {
dir, agent := makeAgent(t, nextConfig())
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
event := &remoteExecEvent{
Prefix: "_rexec",
Session: makeRexecSession(t, agent),
Session: makeRexecSession(t, a.Agent),
}
defer destroySession(t, agent, event.Session)
defer destroySession(t, a.Agent, event.Session)
spec := &remoteExecSpec{
Command: command,
@ -228,7 +220,7 @@ func testHandleRemoteExec(t *testing.T, command string, expectedSubstring string
t.Fatalf("err: %v", err)
}
key := "_rexec/" + event.Session + "/job"
setKV(t, agent, key, buf)
setKV(t, a.Agent, key, buf)
buf, err = json.Marshal(event)
if err != nil {
@ -240,26 +232,26 @@ func testHandleRemoteExec(t *testing.T, command string, expectedSubstring string
}
// Handle the event...
agent.handleRemoteExec(msg)
a.handleRemoteExec(msg)
// Verify we have an ack
key = "_rexec/" + event.Session + "/" + agent.config.NodeName + "/ack"
d := getKV(t, agent, key)
key = "_rexec/" + event.Session + "/" + a.Config.NodeName + "/ack"
d := getKV(t, a.Agent, key)
if d == nil || d.Session != event.Session {
t.Fatalf("bad ack: %#v", d)
}
// Verify we have output
key = "_rexec/" + event.Session + "/" + agent.config.NodeName + "/out/00000"
d = getKV(t, agent, key)
key = "_rexec/" + event.Session + "/" + a.Config.NodeName + "/out/00000"
d = getKV(t, a.Agent, key)
if d == nil || d.Session != event.Session ||
!bytes.Contains(d.Value, []byte(expectedSubstring)) {
t.Fatalf("bad output: %#v", d)
}
// Verify we have an exit code
key = "_rexec/" + event.Session + "/" + agent.config.NodeName + "/exit"
d = getKV(t, agent, key)
key = "_rexec/" + event.Session + "/" + a.Config.NodeName + "/exit"
d = getKV(t, a.Agent, key)
if d == nil || d.Session != event.Session || string(d.Value) != expectedReturnCode {
t.Fatalf("bad output: %#v", d)
}
@ -273,60 +265,60 @@ func TestHandleRemoteExecFailed(t *testing.T) {
testHandleRemoteExec(t, "echo failing;exit 2", "failing", "2")
}
func makeRexecSession(t *testing.T, agent *Agent) string {
func makeRexecSession(t *testing.T, a *Agent) string {
args := structs.SessionRequest{
Datacenter: agent.config.Datacenter,
Datacenter: a.config.Datacenter,
Op: structs.SessionCreate,
Session: structs.Session{
Node: agent.config.NodeName,
Node: a.config.NodeName,
LockDelay: 15 * time.Second,
},
}
var out string
if err := agent.RPC("Session.Apply", &args, &out); err != nil {
if err := a.RPC("Session.Apply", &args, &out); err != nil {
t.Fatalf("err: %v", err)
}
return out
}
func destroySession(t *testing.T, agent *Agent, session string) {
func destroySession(t *testing.T, a *Agent, session string) {
args := structs.SessionRequest{
Datacenter: agent.config.Datacenter,
Datacenter: a.config.Datacenter,
Op: structs.SessionDestroy,
Session: structs.Session{
ID: session,
},
}
var out string
if err := agent.RPC("Session.Apply", &args, &out); err != nil {
if err := a.RPC("Session.Apply", &args, &out); err != nil {
t.Fatalf("err: %v", err)
}
}
func setKV(t *testing.T, agent *Agent, key string, val []byte) {
func setKV(t *testing.T, a *Agent, key string, val []byte) {
write := structs.KVSRequest{
Datacenter: agent.config.Datacenter,
Datacenter: a.config.Datacenter,
Op: api.KVSet,
DirEnt: structs.DirEntry{
Key: key,
Value: val,
},
}
write.Token = agent.config.ACLToken
write.Token = a.config.ACLToken
var success bool
if err := agent.RPC("KVS.Apply", &write, &success); err != nil {
if err := a.RPC("KVS.Apply", &write, &success); err != nil {
t.Fatalf("err: %v", err)
}
}
func getKV(t *testing.T, agent *Agent, key string) *structs.DirEntry {
func getKV(t *testing.T, a *Agent, key string) *structs.DirEntry {
req := structs.KeyRequest{
Datacenter: agent.config.Datacenter,
Datacenter: a.config.Datacenter,
Key: key,
}
req.Token = agent.config.ACLToken
req.Token = a.config.ACLToken
var out structs.IndexedDirEntries
if err := agent.RPC("KVS.Get", &req, &out); err != nil {
if err := a.RPC("KVS.Get", &req, &out); err != nil {
t.Fatalf("err: %v", err)
}
if len(out.Entries) > 0 {

View File

@ -1,20 +1,14 @@
package agent
import (
"os"
"testing"
"github.com/hashicorp/consul/testrpc"
)
func TestStatusLeader(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
obj, err := srv.StatusLeader(nil, nil)
obj, err := a.srv.StatusLeader(nil, nil)
if err != nil {
t.Fatalf("Err: %v", err)
}
@ -25,11 +19,10 @@ func TestStatusLeader(t *testing.T) {
}
func TestStatusPeers(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
obj, err := srv.StatusPeers(nil, nil)
obj, err := a.srv.StatusPeers(nil, nil)
if err != nil {
t.Fatalf("Err: %v", err)
}

View File

@ -14,7 +14,6 @@ import (
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/testutil"
"github.com/hashicorp/go-cleanhttp"
)
@ -25,14 +24,13 @@ func TestUiIndex(t *testing.T) {
defer os.RemoveAll(uiDir)
// Make the server
dir, srv := makeHTTPServerWithConfig(t, func(c *Config) {
c.UIDir = uiDir
})
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
c := TestConfig()
c.UIDir = uiDir
a := NewTestAgent(t.Name(), c)
defer a.Shutdown()
// Create file
path := filepath.Join(srv.agent.config.UIDir, "my-file")
path := filepath.Join(a.Config.UIDir, "my-file")
if err := ioutil.WriteFile(path, []byte("test"), 777); err != nil {
t.Fatalf("err: %v", err)
}
@ -40,7 +38,7 @@ func TestUiIndex(t *testing.T) {
// Register node
req, _ := http.NewRequest("GET", "/ui/my-file", nil)
req.URL.Scheme = "http"
req.URL.Host = srv.Addr
req.URL.Host = a.srv.Addr
// Make the request
client := cleanhttp.DefaultClient()
@ -63,11 +61,8 @@ func TestUiIndex(t *testing.T) {
}
func TestUiNodes(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
args := &structs.RegisterRequest{
Datacenter: "dc1",
@ -76,13 +71,13 @@ func TestUiNodes(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ := http.NewRequest("GET", "/v1/internal/ui/nodes/dc1", nil)
resp := httptest.NewRecorder()
obj, err := srv.UINodes(resp, req)
obj, err := a.srv.UINodes(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -91,7 +86,7 @@ func TestUiNodes(t *testing.T) {
// Should be 2 nodes, and all the empty lists should be non-nil
nodes := obj.(structs.NodeDump)
if len(nodes) != 2 ||
nodes[0].Node != srv.agent.config.NodeName ||
nodes[0].Node != a.Config.NodeName ||
nodes[0].Services == nil || len(nodes[0].Services) != 1 ||
nodes[0].Checks == nil || len(nodes[0].Checks) != 1 ||
nodes[1].Node != "test" ||
@ -102,15 +97,12 @@ func TestUiNodes(t *testing.T) {
}
func TestUiNodeInfo(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
testrpc.WaitForLeader(t, srv.agent.RPC, "dc1")
req, _ := http.NewRequest("GET", fmt.Sprintf("/v1/internal/ui/node/%s", srv.agent.config.NodeName), nil)
req, _ := http.NewRequest("GET", fmt.Sprintf("/v1/internal/ui/node/%s", a.Config.NodeName), nil)
resp := httptest.NewRecorder()
obj, err := srv.UINodeInfo(resp, req)
obj, err := a.srv.UINodeInfo(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}
@ -119,7 +111,7 @@ func TestUiNodeInfo(t *testing.T) {
// Should be 1 node for the server
node := obj.(*structs.NodeInfo)
if node.Node != srv.agent.config.NodeName {
if node.Node != a.Config.NodeName {
t.Fatalf("bad: %v", node)
}
@ -130,13 +122,13 @@ func TestUiNodeInfo(t *testing.T) {
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
if err := a.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
req, _ = http.NewRequest("GET", "/v1/internal/ui/node/test", nil)
resp = httptest.NewRecorder()
obj, err = srv.UINodeInfo(resp, req)
obj, err = a.srv.UINodeInfo(resp, req)
if err != nil {
t.Fatalf("err: %v", err)
}

View File

@ -1,12 +1,10 @@
package agent
import (
"os"
"strings"
"testing"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/testutil/retry"
)
@ -47,10 +45,8 @@ func TestValidateUserEventParams(t *testing.T) {
}
func TestShouldProcessUserEvent(t *testing.T) {
conf := nextConfig()
dir, agent := makeAgent(t, conf)
defer os.RemoveAll(dir)
defer agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
srv1 := &structs.NodeService{
ID: "mysql",
@ -58,10 +54,10 @@ func TestShouldProcessUserEvent(t *testing.T) {
Tags: []string{"test", "foo", "bar", "master"},
Port: 5000,
}
agent.state.AddService(srv1, "")
a.state.AddService(srv1, "")
p := &UserEvent{}
if !agent.shouldProcessUserEvent(p) {
if !a.shouldProcessUserEvent(p) {
t.Fatalf("bad")
}
@ -69,7 +65,7 @@ func TestShouldProcessUserEvent(t *testing.T) {
p = &UserEvent{
NodeFilter: "foobar",
}
if agent.shouldProcessUserEvent(p) {
if a.shouldProcessUserEvent(p) {
t.Fatalf("bad")
}
@ -77,7 +73,7 @@ func TestShouldProcessUserEvent(t *testing.T) {
p = &UserEvent{
NodeFilter: "^Node",
}
if !agent.shouldProcessUserEvent(p) {
if !a.shouldProcessUserEvent(p) {
t.Fatalf("bad")
}
@ -85,7 +81,7 @@ func TestShouldProcessUserEvent(t *testing.T) {
p = &UserEvent{
ServiceFilter: "foobar",
}
if agent.shouldProcessUserEvent(p) {
if a.shouldProcessUserEvent(p) {
t.Fatalf("bad")
}
@ -93,7 +89,7 @@ func TestShouldProcessUserEvent(t *testing.T) {
p = &UserEvent{
ServiceFilter: ".*sql",
}
if !agent.shouldProcessUserEvent(p) {
if !a.shouldProcessUserEvent(p) {
t.Fatalf("bad")
}
@ -102,7 +98,7 @@ func TestShouldProcessUserEvent(t *testing.T) {
ServiceFilter: ".*sql",
TagFilter: "slave",
}
if agent.shouldProcessUserEvent(p) {
if a.shouldProcessUserEvent(p) {
t.Fatalf("bad")
}
@ -111,24 +107,22 @@ func TestShouldProcessUserEvent(t *testing.T) {
ServiceFilter: ".*sql",
TagFilter: "master",
}
if !agent.shouldProcessUserEvent(p) {
if !a.shouldProcessUserEvent(p) {
t.Fatalf("bad")
}
}
func TestIngestUserEvent(t *testing.T) {
conf := nextConfig()
dir, agent := makeAgent(t, conf)
defer os.RemoveAll(dir)
defer agent.Shutdown()
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
for i := 0; i < 512; i++ {
msg := &UserEvent{LTime: uint64(i), Name: "test"}
agent.ingestUserEvent(msg)
if agent.LastUserEvent() != msg {
a.ingestUserEvent(msg)
if a.LastUserEvent() != msg {
t.Fatalf("bad: %#v", msg)
}
events := agent.UserEvents()
events := a.UserEvents()
expectLen := 256
if i < 256 {
@ -149,12 +143,8 @@ func TestIngestUserEvent(t *testing.T) {
}
func TestFireReceiveEvent(t *testing.T) {
conf := nextConfig()
dir, agent := makeAgent(t, conf)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
a := NewTestAgent(t.Name(), nil)
defer a.Shutdown()
srv1 := &structs.NodeService{
ID: "mysql",
@ -162,42 +152,36 @@ func TestFireReceiveEvent(t *testing.T) {
Tags: []string{"test", "foo", "bar", "master"},
Port: 5000,
}
agent.state.AddService(srv1, "")
a.state.AddService(srv1, "")
p1 := &UserEvent{Name: "deploy", ServiceFilter: "web"}
err := agent.UserEvent("dc1", "root", p1)
err := a.UserEvent("dc1", "root", p1)
if err != nil {
t.Fatalf("err: %v", err)
}
p2 := &UserEvent{Name: "deploy"}
err = agent.UserEvent("dc1", "root", p2)
err = a.UserEvent("dc1", "root", p2)
if err != nil {
t.Fatalf("err: %v", err)
}
retry.Run(t, func(r *retry.R) {
if got, want := len(agent.UserEvents()), 1; got != want {
if got, want := len(a.UserEvents()), 1; got != want {
r.Fatalf("got %d events want %d", got, want)
}
})
last := agent.LastUserEvent()
last := a.LastUserEvent()
if last.ID != p2.ID {
t.Fatalf("bad: %#v", last)
}
}
func TestUserEventToken(t *testing.T) {
conf := nextConfig()
// Set the default policies to deny
conf.ACLDefaultPolicy = "deny"
dir, agent := makeAgent(t, conf)
defer os.RemoveAll(dir)
defer agent.Shutdown()
testrpc.WaitForLeader(t, agent.RPC, "dc1")
conf := TestConfig()
conf.ACLDefaultPolicy = "deny" // Set the default policies to deny
a := NewTestAgent(t.Name(), conf)
defer a.Shutdown()
// Create an ACL token
args := structs.ACLRequest{
@ -211,7 +195,7 @@ func TestUserEventToken(t *testing.T) {
WriteRequest: structs.WriteRequest{Token: "root"},
}
var token string
if err := agent.RPC("ACL.Apply", &args, &token); err != nil {
if err := a.RPC("ACL.Apply", &args, &token); err != nil {
t.Fatalf("err: %v", err)
}
@ -227,7 +211,7 @@ func TestUserEventToken(t *testing.T) {
}
for _, c := range cases {
event := &UserEvent{Name: c.name}
err := agent.UserEvent("dc1", token, event)
err := a.UserEvent("dc1", token, event)
allowed := false
if err == nil || err.Error() != permissionDenied {
allowed = true