diff --git a/operator/controllers/common/providers/datadog/datadog.go b/operator/controllers/common/providers/datadog/datadog.go index 9b114de025..8d008a7f31 100644 --- a/operator/controllers/common/providers/datadog/datadog.go +++ b/operator/controllers/common/providers/datadog/datadog.go @@ -2,12 +2,13 @@ package datadog import ( "context" - "encoding/json" + "fmt" "github.com/DataDog/datadog-api-client-go/v2/api/datadog" "github.com/DataDog/datadog-api-client-go/v2/api/datadogV1" "github.com/go-logr/logr" klcv1alpha2 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha2" "net/http" + "strconv" "time" ) @@ -17,21 +18,49 @@ type KeptnDataDogProvider struct { } func (k KeptnDataDogProvider) EvaluateQuery(ctx context.Context, objective klcv1alpha2.Objective, provider klcv1alpha2.KeptnEvaluationProvider) (string, []byte, error) { - - ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + ctx, cancel := context.WithTimeout(ctx, 60*time.Second) defer cancel() - k.Log.Info("Running query: " + provider.Spec.TargetServer + "/api/v1/slo") + // TODO: get DD_API_KEY and DD_APP_KEY from kubernetes secret + // TODO: patch the context with the keys + // Ref: https://github.com/DataDog/datadog-api-client-go#getting-started + + ctx = context.WithValue( + ctx, + datadog.ContextAPIKeys, + map[string]datadog.APIKey{ + "apiKeyAuth": { + Key: "DD_KEY", + }, + "appKeyAuth": { + Key: "DD_APP_KEY", + }, + }, + ) - cfg := datadog.NewConfiguration() - client := datadog.NewAPIClient(cfg) - api := datadogV1.NewServiceLevelObjectivesApi(client) - resp, _, err := api.ListSLOs(ctx, *datadogV1.NewListSLOsOptionalParameters()) + fromTime := time.Now().AddDate(0, 0, -1) + queryTime := time.Now() + configuration := datadog.NewConfiguration() + apiClient := datadog.NewAPIClient(configuration) + api := datadogV1.NewMetricsApi(apiClient) + + resp, _, err := api.QueryMetrics( + ctx, + fromTime.Unix(), + queryTime.Unix(), + objective.Query, + ) if err != nil { + k.Log.Error(err, "Error while creating request") return "", nil, err } + if len(resp.Series) == 0 { + k.Log.Info("No values in query result") + return "", nil, fmt.Errorf("no values in query result") + } + points := (resp.Series)[0].Pointlist + value := strconv.FormatFloat(*points[len(points)-1][1], 'g', 5, 64) + return value, []byte(value), nil - responseContent, _ := json.MarshalIndent(resp, "", " ") - return string(responseContent), responseContent, nil }