From 8937ed31d9fd83dca4c9b6a0b4d6ef7e596f3426 Mon Sep 17 00:00:00 2001 From: Jaime Soriano Pastor Date: Wed, 15 Jan 2020 19:10:08 +0100 Subject: [PATCH] Listen explicitly on localhost on heartbeat TCP tests (#15583) Some tests were requiring localhost to resolve to 127.0.0.1, but this is not always the case. In some machines localhost resolve to other local addresses as 127.0.1.1, or to [::1] if ipv4 is not available. --- NOTICE.txt | 2 +- heartbeat/monitors/active/tcp/tcp_test.go | 27 ++++++++++++++++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/NOTICE.txt b/NOTICE.txt index e8412d03955..14bcd6878c4 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,5 +1,5 @@ Elastic Beats -Copyright 2014-2019 Elasticsearch BV +Copyright 2014-2020 Elasticsearch BV This product includes software developed by The Apache Software Foundation (http://www.apache.org/). diff --git a/heartbeat/monitors/active/tcp/tcp_test.go b/heartbeat/monitors/active/tcp/tcp_test.go index 22d42b0173f..2f3e915d53f 100644 --- a/heartbeat/monitors/active/tcp/tcp_test.go +++ b/heartbeat/monitors/active/tcp/tcp_test.go @@ -103,22 +103,43 @@ func setupServer(t *testing.T, serverCreator func(http.Handler) *httptest.Server return server, port } +// newLocalhostTestServer starts a server listening on the IP resolved from `localhost` +// httptest.NewServer() binds explicitly on 127.0.0.1 (or [::1] if ipv4 is not available). +// The IP resolved from `localhost` can be a different one, like 127.0.1.1. +func newLocalhostTestServer(handler http.Handler) *httptest.Server { + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + panic("failed to listen on localhost: " + err.Error()) + } + + server := &httptest.Server{ + Listener: listener, + Config: &http.Server{Handler: handler}, + } + server.Start() + + return server +} + func TestUpEndpointJob(t *testing.T) { - server, port := setupServer(t, httptest.NewServer) + server, port := setupServer(t, newLocalhostTestServer) defer server.Close() + serverURL, err := url.Parse(server.URL) + require.NoError(t, err) + event := testTCPCheck(t, "localhost", port) testslike.Test( t, lookslike.Strict(lookslike.Compose( - hbtest.BaseChecks("127.0.0.1", "up", "tcp"), + hbtest.BaseChecks(serverURL.Hostname(), "up", "tcp"), hbtest.SummaryChecks(1, 0), hbtest.SimpleURLChecks(t, "tcp", "localhost", port), hbtest.RespondingTCPChecks(), lookslike.MustCompile(map[string]interface{}{ "resolve": map[string]interface{}{ - "ip": "127.0.0.1", + "ip": serverURL.Hostname(), "rtt.us": isdef.IsDuration, }, }),