From e34218af0d6582c1d6d4d53e761489828abdd603 Mon Sep 17 00:00:00 2001 From: Nelson Kopliku Date: Thu, 14 Nov 2024 14:37:25 +0100 Subject: [PATCH] Expose all host ips as prometheus targets --- .../controllers/v1/prometheus_json.ex | 3 +- .../v1/prometheus_controller_test.exs | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/trento_web/controllers/v1/prometheus_json.ex b/lib/trento_web/controllers/v1/prometheus_json.ex index 2218c2e4e7..fa67ed7596 100644 --- a/lib/trento_web/controllers/v1/prometheus_json.ex +++ b/lib/trento_web/controllers/v1/prometheus_json.ex @@ -8,7 +8,8 @@ defmodule TrentoWeb.V1.PrometheusJSON do def target(%{target: target}), do: %{ - targets: ["#{List.first(target.ip_addresses, target.hostname)}:#{@node_exporter_port}"], + targets: + Enum.map(target.ip_addresses ++ [target.hostname], &"#{&1}:#{@node_exporter_port}"), labels: %{ # TODO: in the future renaeme this label which also is used by node_exporter json agentID: "#{target.id}", diff --git a/test/trento_web/controllers/v1/prometheus_controller_test.exs b/test/trento_web/controllers/v1/prometheus_controller_test.exs index 83c45690eb..e95235f654 100644 --- a/test/trento_web/controllers/v1/prometheus_controller_test.exs +++ b/test/trento_web/controllers/v1/prometheus_controller_test.exs @@ -44,6 +44,34 @@ defmodule TrentoWeb.V1.PrometheusControllerTest do } in response end + test "should return the expected targets when host have multiple IP address", %{ + conn: conn + } do + ip1 = Faker.Internet.ip_v4_address() + ip2 = Faker.Internet.ip_v4_address() + %{id: id, hostname: hostname} = insert(:host, ip_addresses: [ip1, ip2]) + + response = + conn + |> get("/api/v1/prometheus/targets") + |> json_response(200) + + assert [ + %{ + "labels" => %{ + "agentID" => "#{id}", + "hostname" => "#{hostname}", + "exporter_name" => "Node Exporter" + }, + "targets" => [ + "#{ip1}:9100", + "#{ip2}:9100", + "#{hostname}:9100" + ] + } + ] == response + end + test "should return the exporters status", %{conn: conn} do expect(Trento.Infrastructure.Prometheus.Mock, :get_exporters_status, fn _ -> {:ok, %{"Node Exporter" => :passing}}