Skip to content

Commit

Permalink
Use only healthy instances from Consul (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
ojagodzinski committed Dec 1, 2020
1 parent e6c3fd2 commit 322f0be
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions xnet/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,15 @@ 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)
}

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
Expand Down
23 changes: 23 additions & 0 deletions xnet/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit 322f0be

Please sign in to comment.