-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathdatadog.go
80 lines (71 loc) · 2.06 KB
/
datadog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package datadog
import (
"context"
"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"
metricsapi "github.com/keptn/lifecycle-toolkit/metrics-operator/api/v1alpha2"
"strconv"
"time"
//nolint:gci
"net/http" //nolint:gci
"sigs.k8s.io/controller-runtime/pkg/client"
)
type KeptnDataDogProvider struct {
Log logr.Logger
HttpClient http.Client
K8sClient client.Client
}
// EvaluateQuery fetches the SLI values from datadog provider
func (d *KeptnDataDogProvider) EvaluateQuery(ctx context.Context, metric metricsapi.KeptnMetric, provider metricsapi.KeptnMetricsProvider) (string, []byte, error) {
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
apiKey, err := getDDSecret(ctx, provider, d.K8sClient)
if err != nil {
return "", nil, err
}
// 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: apiKey,
},
"appKeyAuth": {
Key: "value", // TODO: get this value from kubernetes secret.
},
},
)
ctx = context.WithValue(ctx,
datadog.ContextServerVariables,
map[string]string{
"site": provider.Spec.TargetServer,
},
)
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(),
metric.Spec.Query,
)
if err != nil {
d.Log.Error(err, "Error while creating request")
return "", nil, err
}
if len(resp.Series) == 0 {
d.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
}