From 322f0be30192b87b800f04a10594c060289c3b7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Jagodzi=C5=84ski?= Date: Tue, 1 Dec 2020 09:06:17 +0100 Subject: [PATCH] Use only healthy instances from Consul (#141) --- xnet/writer.go | 4 ++-- xnet/writer_test.go | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/xnet/writer.go b/xnet/writer.go index 9db471e6..739f4353 100644 --- a/xnet/writer.go +++ b/xnet/writer.go @@ -128,7 +128,7 @@ type consulDiscoveryServiceClient struct { func (c *consulDiscoveryServiceClient) GetAddrsByName(serviceName string) ([]Address, error) { //TODO(janisz): Add fallback to other datacenters with query - services, _, err := c.client.Catalog().Service(serviceName, "", nil) + services, _, err := c.client.Health().Service(serviceName, "", true, nil) if err != nil { return nil, fmt.Errorf("could NOT find service in Consul: %s", err) @@ -136,7 +136,7 @@ func (c *consulDiscoveryServiceClient) GetAddrsByName(serviceName string) ([]Add instances := make([]Address, len(services)) for i, instance := range services { - instances[i] = Address(net.JoinHostPort(instance.ServiceAddress, strconv.Itoa(instance.ServicePort))) + instances[i] = Address(net.JoinHostPort(instance.Service.Address, strconv.Itoa(instance.Service.Port))) } return instances, nil diff --git a/xnet/writer_test.go b/xnet/writer_test.go index 12790121..d0986e63 100644 --- a/xnet/writer_test.go +++ b/xnet/writer_test.go @@ -244,6 +244,29 @@ func TestIfGetAddrsByNameReturnsErrorIfNoConsulConnection(t *testing.T) { assert.Empty(t, addr) } +func TestIfGetAddrsByNameReturnsOnlyHealthyInstancesFromConsul(t *testing.T) { + config, server := createTestConsulServer(t) + consulApiClient, err := api.NewClient(config) + defer stopConsul(server) + + require.NoError(t, err) + + agent := consulApiClient.Agent() + // given + for id, name := range []string{"A", "A"} { + err = agent.ServiceRegister(registration(id, name)) + require.NoError(t, err) + } + // when + server.AddCheck(t, "check", "0", "critical") + + client := consulDiscoveryServiceClient{client: consulApiClient} + // then + addr, err := client.GetAddrsByName("A") + assert.NoError(t, err) + assert.Equal(t, 1, len(addr)) +} + func registration(id int, name string) *api.AgentServiceRegistration { return &api.AgentServiceRegistration{ ID: fmt.Sprint(id),