open-consul/api/health_test.go

482 lines
9.9 KiB
Go
Raw Normal View History

package api
import (
"fmt"
"testing"
"github.com/hashicorp/consul/testutil"
"github.com/hashicorp/consul/testutil/retry"
"github.com/pascaldekloe/goe/verify"
2018-06-07 09:17:44 +00:00
"github.com/stretchr/testify/require"
)
func TestAPI_HealthNode(t *testing.T) {
2015-05-08 17:27:24 +00:00
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
agent := c.Agent()
health := c.Health()
info, err := agent.Self()
if err != nil {
t.Fatalf("err: %v", err)
}
name := info["Config"]["NodeName"].(string)
retry.Run(t, func(r *retry.R) {
checks, meta, err := health.Node(name, nil)
if err != nil {
r.Fatal(err)
}
if meta.LastIndex == 0 {
r.Fatalf("bad: %v", meta)
}
if len(checks) == 0 {
r.Fatalf("bad: %v", checks)
}
})
}
func TestAPI_HealthChecks_AggregatedStatus(t *testing.T) {
t.Parallel()
cases := []struct {
name string
checks HealthChecks
exp string
}{
{
"empty",
nil,
HealthPassing,
},
{
"passing",
HealthChecks{
&HealthCheck{
Status: HealthPassing,
},
},
HealthPassing,
},
{
"warning",
HealthChecks{
&HealthCheck{
Status: HealthWarning,
},
},
HealthWarning,
},
{
"critical",
HealthChecks{
&HealthCheck{
Status: HealthCritical,
},
},
HealthCritical,
},
{
"node_maintenance",
HealthChecks{
&HealthCheck{
CheckID: NodeMaint,
},
},
HealthMaint,
},
{
"service_maintenance",
HealthChecks{
&HealthCheck{
CheckID: ServiceMaintPrefix + "service",
},
},
HealthMaint,
},
{
"unknown",
HealthChecks{
&HealthCheck{
Status: "nope-nope-noper",
},
},
"",
},
{
"maintenance_over_critical",
HealthChecks{
&HealthCheck{
CheckID: NodeMaint,
},
&HealthCheck{
Status: HealthCritical,
},
},
HealthMaint,
},
{
"critical_over_warning",
HealthChecks{
&HealthCheck{
Status: HealthCritical,
},
&HealthCheck{
Status: HealthWarning,
},
},
HealthCritical,
},
{
"warning_over_passing",
HealthChecks{
&HealthCheck{
Status: HealthWarning,
},
&HealthCheck{
Status: HealthPassing,
},
},
HealthWarning,
},
{
"lots",
HealthChecks{
&HealthCheck{
Status: HealthPassing,
},
&HealthCheck{
Status: HealthPassing,
},
&HealthCheck{
Status: HealthPassing,
},
&HealthCheck{
Status: HealthWarning,
},
},
HealthWarning,
},
}
for i, tc := range cases {
t.Run(fmt.Sprintf("%d_%s", i, tc.name), func(t *testing.T) {
act := tc.checks.AggregatedStatus()
if tc.exp != act {
t.Errorf("\nexp: %#v\nact: %#v", tc.exp, act)
}
})
}
}
func TestAPI_HealthChecks(t *testing.T) {
2015-05-08 17:27:24 +00:00
t.Parallel()
c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) {
conf.NodeName = "node123"
})
defer s.Stop()
agent := c.Agent()
health := c.Health()
// Make a service with a check
reg := &AgentServiceRegistration{
Name: "foo",
Tags: []string{"bar"},
Check: &AgentServiceCheck{
TTL: "15s",
},
}
if err := agent.ServiceRegister(reg); err != nil {
t.Fatalf("err: %v", err)
}
defer agent.ServiceDeregister("foo")
retry.Run(t, func(r *retry.R) {
checks := HealthChecks{
&HealthCheck{
Node: "node123",
CheckID: "service:foo",
Name: "Service 'foo' check",
Status: "critical",
ServiceID: "foo",
ServiceName: "foo",
ServiceTags: []string{"bar"},
},
}
out, meta, err := health.Checks("foo", nil)
if err != nil {
r.Fatal(err)
}
if meta.LastIndex == 0 {
r.Fatalf("bad: %v", meta)
}
checks[0].CreateIndex = out[0].CreateIndex
checks[0].ModifyIndex = out[0].ModifyIndex
verify.Values(r, "checks", out, checks)
})
}
func TestAPI_HealthChecks_NodeMetaFilter(t *testing.T) {
t.Parallel()
meta := map[string]string{"somekey": "somevalue"}
c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) {
conf.NodeMeta = meta
})
defer s.Stop()
agent := c.Agent()
health := c.Health()
// Make a service with a check
reg := &AgentServiceRegistration{
Name: "foo",
Check: &AgentServiceCheck{
TTL: "15s",
},
}
if err := agent.ServiceRegister(reg); err != nil {
t.Fatalf("err: %v", err)
}
defer agent.ServiceDeregister("foo")
retry.Run(t, func(r *retry.R) {
checks, meta, err := health.Checks("foo", &QueryOptions{NodeMeta: meta})
if err != nil {
r.Fatal(err)
}
if meta.LastIndex == 0 {
r.Fatalf("bad: %v", meta)
}
if len(checks) == 0 {
r.Fatalf("Bad: %v", checks)
}
})
}
func TestAPI_HealthService(t *testing.T) {
New config parser, HCL support, multiple bind addrs (#3480) * new config parser for agent This patch implements a new config parser for the consul agent which makes the following changes to the previous implementation: * add HCL support * all configuration fragments in tests and for default config are expressed as HCL fragments * HCL fragments can be provided on the command line so that they can eventually replace the command line flags. * HCL/JSON fragments are parsed into a temporary Config structure which can be merged using reflection (all values are pointers). The existing merge logic of overwrite for values and append for slices has been preserved. * A single builder process generates a typed runtime configuration for the agent. The new implementation is more strict and fails in the builder process if no valid runtime configuration can be generated. Therefore, additional validations in other parts of the code should be removed. The builder also pre-computes all required network addresses so that no address/port magic should be required where the configuration is used and should therefore be removed. * Upgrade github.com/hashicorp/hcl to support int64 * improve error messages * fix directory permission test * Fix rtt test * Fix ForceLeave test * Skip performance test for now until we know what to do * Update github.com/hashicorp/memberlist to update log prefix * Make memberlist use the default logger * improve config error handling * do not fail on non-existing data-dir * experiment with non-uniform timeouts to get a handle on stalled leader elections * Run tests for packages separately to eliminate the spurious port conflicts * refactor private address detection and unify approach for ipv4 and ipv6. Fixes #2825 * do not allow unix sockets for DNS * improve bind and advertise addr error handling * go through builder using test coverage * minimal update to the docs * more coverage tests fixed * more tests * fix makefile * cleanup * fix port conflicts with external port server 'porter' * stop test server on error * do not run api test that change global ENV concurrently with the other tests * Run remaining api tests concurrently * no need for retry with the port number service * monkey patch race condition in go-sockaddr until we understand why that fails * monkey patch hcl decoder race condidtion until we understand why that fails * monkey patch spurious errors in strings.EqualFold from here * add test for hcl decoder race condition. Run with go test -parallel 128 * Increase timeout again * cleanup * don't log port allocations by default * use base command arg parsing to format help output properly * handle -dc deprecation case in Build * switch autopilot.max_trailing_logs to int * remove duplicate test case * remove unused methods * remove comments about flag/config value inconsistencies * switch got and want around since the error message was misleading. * Removes a stray debug log. * Removes a stray newline in imports. * Fixes TestACL_Version8. * Runs go fmt. * Adds a default case for unknown address types. * Reoders and reformats some imports. * Adds some comments and fixes typos. * Reorders imports. * add unix socket support for dns later * drop all deprecated flags and arguments * fix wrong field name * remove stray node-id file * drop unnecessary patch section in test * drop duplicate test * add test for LeaveOnTerm and SkipLeaveOnInt in client mode * drop "bla" and add clarifying comment for the test * split up tests to support enterprise/non-enterprise tests * drop raft multiplier and derive values during build phase * sanitize runtime config reflectively and add test * detect invalid config fields * fix tests with invalid config fields * use different values for wan sanitiziation test * drop recursor in favor of recursors * allow dns_config.udp_answer_limit to be zero * make sure tests run on machines with multiple ips * Fix failing tests in a few more places by providing a bind address in the test * Gets rid of skipped TestAgent_CheckPerformanceSettings and adds case for builder. * Add porter to server_test.go to make tests there less flaky * go fmt
2017-09-25 18:40:42 +00:00
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
health := c.Health()
retry.Run(t, func(r *retry.R) {
2015-01-07 00:48:54 +00:00
// consul service should always exist...
checks, meta, err := health.Service("consul", "", true, nil)
if err != nil {
r.Fatal(err)
2015-01-07 00:48:54 +00:00
}
if meta.LastIndex == 0 {
r.Fatalf("bad: %v", meta)
2015-01-07 00:48:54 +00:00
}
if len(checks) == 0 {
r.Fatalf("Bad: %v", checks)
2015-01-07 00:48:54 +00:00
}
if _, ok := checks[0].Node.TaggedAddresses["wan"]; !ok {
r.Fatalf("Bad: %v", checks[0].Node)
}
if checks[0].Node.Datacenter != "dc1" {
r.Fatalf("Bad datacenter: %v", checks[0].Node)
}
})
}
func TestAPI_HealthService_SingleTag(t *testing.T) {
t.Parallel()
c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) {
conf.NodeName = "node123"
})
defer s.Stop()
agent := c.Agent()
health := c.Health()
reg := &AgentServiceRegistration{
Name: "foo",
ID: "foo1",
Tags: []string{"bar"},
Check: &AgentServiceCheck{
Status: HealthPassing,
TTL: "15s",
},
}
require.NoError(t, agent.ServiceRegister(reg))
defer agent.ServiceDeregister("foo1")
retry.Run(t, func(r *retry.R) {
services, meta, err := health.Service("foo", "bar", true, nil)
require.NoError(t, err)
require.NotEqual(t, meta.LastIndex, 0)
require.Len(t, services, 1)
require.Equal(t, services[0].Service.ID, "foo1")
})
}
func TestAPI_HealthService_MultipleTags(t *testing.T) {
t.Parallel()
c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) {
conf.NodeName = "node123"
})
defer s.Stop()
agent := c.Agent()
health := c.Health()
// Make two services with a check
reg := &AgentServiceRegistration{
Name: "foo",
ID: "foo1",
Tags: []string{"bar"},
Check: &AgentServiceCheck{
Status: HealthPassing,
TTL: "15s",
},
}
require.NoError(t, agent.ServiceRegister(reg))
defer agent.ServiceDeregister("foo1")
reg2 := &AgentServiceRegistration{
Name: "foo",
ID: "foo2",
Tags: []string{"bar", "v2"},
Check: &AgentServiceCheck{
Status: HealthPassing,
TTL: "15s",
},
}
require.NoError(t, agent.ServiceRegister(reg2))
defer agent.ServiceDeregister("foo2")
// Test searching with one tag (two results)
retry.Run(t, func(r *retry.R) {
services, meta, err := health.ServiceMultipleTags("foo", []string{"bar"}, true, nil)
require.NoError(t, err)
require.NotEqual(t, meta.LastIndex, 0)
require.Len(t, services, 2)
})
// Test searching with two tags (one result)
retry.Run(t, func(r *retry.R) {
services, meta, err := health.ServiceMultipleTags("foo", []string{"bar", "v2"}, true, nil)
require.NoError(t, err)
require.NotEqual(t, meta.LastIndex, 0)
require.Len(t, services, 1)
require.Equal(t, services[0].Service.ID, "foo2")
})
}
func TestAPI_HealthService_NodeMetaFilter(t *testing.T) {
t.Parallel()
meta := map[string]string{"somekey": "somevalue"}
c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) {
conf.NodeMeta = meta
})
defer s.Stop()
health := c.Health()
retry.Run(t, func(r *retry.R) {
// consul service should always exist...
checks, meta, err := health.Service("consul", "", true, &QueryOptions{NodeMeta: meta})
require.NoError(t, err)
require.NotEqual(t, meta.LastIndex, 0)
require.NotEqual(t, len(checks), 0)
require.Equal(t, checks[0].Node.Datacenter, "dc1")
require.Contains(t, checks[0].Node.TaggedAddresses, "wan")
})
}
func TestAPI_HealthConnect(t *testing.T) {
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
agent := c.Agent()
health := c.Health()
// Make a service with a proxy
reg := &AgentServiceRegistration{
Name: "foo",
Port: 8000,
}
err := agent.ServiceRegister(reg)
2018-06-07 09:17:44 +00:00
require.NoError(t, err)
defer agent.ServiceDeregister("foo")
// Register the proxy
proxyReg := &AgentServiceRegistration{
Add Proxy Upstreams to Service Definition (#4639) * Refactor Service Definition ProxyDestination. This includes: - Refactoring all internal structs used - Updated tests for both deprecated and new input for: - Agent Services endpoint response - Agent Service endpoint response - Agent Register endpoint - Unmanaged deprecated field - Unmanaged new fields - Managed deprecated upstreams - Managed new - Catalog Register - Unmanaged deprecated field - Unmanaged new fields - Managed deprecated upstreams - Managed new - Catalog Services endpoint response - Catalog Node endpoint response - Catalog Service endpoint response - Updated API tests for all of the above too (both deprecated and new forms of register) TODO: - config package changes for on-disk service definitions - proxy config endpoint - built-in proxy support for new fields * Agent proxy config endpoint updated with upstreams * Config file changes for upstreams. * Add upstream opaque config and update all tests to ensure it works everywhere. * Built in proxy working with new Upstreams config * Command fixes and deprecations * Fix key translation, upstream type defaults and a spate of other subtele bugs found with ned to end test scripts... TODO: tests still failing on one case that needs a fix. I think it's key translation for upstreams nested in Managed proxy struct. * Fix translated keys in API registration. ≈ * Fixes from docs - omit some empty undocumented fields in API - Bring back ServiceProxyDestination in Catalog responses to not break backwards compat - this was removed assuming it was only used internally. * Documentation updates for Upstreams in service definition * Fixes for tests broken by many refactors. * Enable travis on f-connect branch in this branch too. * Add consistent Deprecation comments to ProxyDestination uses * Update version number on deprecation notices, and correct upstream datacenter field with explanation in docs
2018-09-12 16:07:47 +00:00
Name: "foo-proxy",
Port: 8001,
Kind: ServiceKindConnectProxy,
Proxy: &AgentServiceConnectProxyConfig{
DestinationServiceName: "foo",
},
}
err = agent.ServiceRegister(proxyReg)
2018-06-07 09:17:44 +00:00
require.NoError(t, err)
defer agent.ServiceDeregister("foo-proxy")
retry.Run(t, func(r *retry.R) {
services, meta, err := health.Connect("foo", "", true, nil)
if err != nil {
r.Fatal(err)
}
if meta.LastIndex == 0 {
r.Fatalf("bad: %v", meta)
}
// Should be exactly 1 service - the original shouldn't show up as a connect
// endpoint, only it's proxy.
if len(services) != 1 {
r.Fatalf("Bad: %v", services)
}
if services[0].Node.Datacenter != "dc1" {
r.Fatalf("Bad datacenter: %v", services[0].Node)
}
if services[0].Service.Port != proxyReg.Port {
r.Fatalf("Bad port: %v", services[0])
}
})
}
func TestAPI_HealthState(t *testing.T) {
2015-05-08 17:27:24 +00:00
t.Parallel()
c, s := makeClient(t)
defer s.Stop()
health := c.Health()
retry.Run(t, func(r *retry.R) {
2015-01-07 00:48:54 +00:00
checks, meta, err := health.State("any", nil)
if err != nil {
r.Fatal(err)
2015-01-07 00:48:54 +00:00
}
if meta.LastIndex == 0 {
r.Fatalf("bad: %v", meta)
2015-01-07 00:48:54 +00:00
}
if len(checks) == 0 {
r.Fatalf("Bad: %v", checks)
2015-01-07 00:48:54 +00:00
}
})
}
func TestAPI_HealthState_NodeMetaFilter(t *testing.T) {
t.Parallel()
meta := map[string]string{"somekey": "somevalue"}
c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) {
conf.NodeMeta = meta
})
defer s.Stop()
health := c.Health()
retry.Run(t, func(r *retry.R) {
checks, meta, err := health.State("any", &QueryOptions{NodeMeta: meta})
if err != nil {
r.Fatal(err)
}
if meta.LastIndex == 0 {
r.Fatalf("bad: %v", meta)
}
if len(checks) == 0 {
r.Fatalf("Bad: %v", checks)
}
})
}