Skip to content

Commit

Permalink
fix(metrics-operator): normalize Dynatrace URL (#1145)
Browse files Browse the repository at this point in the history
  • Loading branch information
thisthat committed Mar 29, 2023
1 parent e118851 commit b33b4f4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
"strings"
"time"

"github.com/go-logr/logr"
Expand Down Expand Up @@ -37,7 +38,8 @@ type DynatraceData struct {

// EvaluateQuery fetches the SLI values from dynatrace provider
func (d *KeptnDynatraceProvider) EvaluateQuery(ctx context.Context, metric metricsapi.KeptnMetric, provider metricsapi.KeptnMetricsProvider) (string, []byte, error) {
qURL := provider.Spec.TargetServer + "/api/v2/metrics/query?metricSelector=" + metric.Spec.Query
baseURL := d.normalizeAPIURL(provider.Spec.TargetServer)
qURL := baseURL + "v2/metrics/query?metricSelector=" + metric.Spec.Query

d.Log.Info("Running query: " + qURL)
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
Expand Down Expand Up @@ -79,6 +81,17 @@ func (d *KeptnDynatraceProvider) EvaluateQuery(ctx context.Context, metric metri
return r, b, nil
}

func (d *KeptnDynatraceProvider) normalizeAPIURL(url string) string {
out := url
if !strings.HasSuffix(out, "/") {
out = out + "/"
}
if !strings.HasSuffix(out, "api/") {
out = out + "api/"
}
return out
}

func (d *KeptnDynatraceProvider) getSingleValue(result DynatraceResponse) float64 {
var sum float64 = 0
var count uint64 = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,44 @@ func TestGetSingleValue(t *testing.T) {
}
}

func TestNormalizeURL(t *testing.T) {
tests := []struct {
name string
input string
result string
}{
{
name: "happy path",
input: "http://mydttenant.com/api/",
result: "http://mydttenant.com/api/",
},
{
name: "missing final /",
input: "http://mydttenant.com/api",
result: "http://mydttenant.com/api/",
},
{
name: "missing final /api",
input: "http://mydttenant.com/",
result: "http://mydttenant.com/api/",
},
{
name: "base url",
input: "http://mydttenant.com",
result: "http://mydttenant.com/api/",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kdp := KeptnDynatraceProvider{}
r := kdp.normalizeAPIURL(tt.input)
require.Equal(t, tt.result, r)
})

}
}

func TestEvaluateQuery_CorrectHTTP(t *testing.T) {
const query = "my-query"
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down

0 comments on commit b33b4f4

Please sign in to comment.