From ba3a0d6cd6b15200ac422c00489647b4b799e487 Mon Sep 17 00:00:00 2001 From: Alex <33497058+bexsoft@users.noreply.github.com> Date: Tue, 17 Aug 2021 14:02:42 -0500 Subject: [PATCH] Added pre validation of prometheus URL (#956) Signed-off-by: Benjamin Perez --- restapi/admin_info.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/restapi/admin_info.go b/restapi/admin_info.go index a9e086c50..e7aebd4ed 100644 --- a/restapi/admin_info.go +++ b/restapi/admin_info.go @@ -19,7 +19,9 @@ package restapi import ( "context" "encoding/json" + "errors" "fmt" + "net/http" "net/url" "regexp" "strings" @@ -871,10 +873,38 @@ func unmarshalPrometheus(endpoint string, data interface{}) bool { return false } +func testPrometheusURL(url string) bool { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url+"/-/healthy", nil) + + if err != nil { + LogError("Error Building Request: (%v)", err) + return false + } + + response, err := GetConsoleHTTPClient().Do(req) + + if err != nil { + LogError("Non reachable Prometheus URL: %s (%v)", url, err) + return false + + } + + return response.StatusCode == http.StatusOK +} + func getAdminInfoWidgetResponse(params admin_api.DashboardWidgetDetailsParams) (*models.WidgetDetails, *models.Error) { prometheusURL := getPrometheusURL() prometheusJobID := getPrometheusJobID() + // We test if prometheus URL is reachable. this is meant to avoid unuseful calls and application hang. + if !testPrometheusURL(prometheusURL) { + error := errors.New("Prometheus URL is unreachable") + return nil, prepareError(error) + } + return getWidgetDetails(prometheusURL, prometheusJobID, params.WidgetID, params.Step, params.Start, params.End) }