-
Notifications
You must be signed in to change notification settings - Fork 39
/
ddlambda.go
231 lines (197 loc) · 8.06 KB
/
ddlambda.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*
* Unless explicitly stated otherwise all files in this repository are licensed
* under the Apache License Version 2.0.
*
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019 Datadog, Inc.
*/
package ddlambda
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/DataDog/datadog-lambda-go/internal/logger"
"github.com/DataDog/datadog-lambda-go/internal/metrics"
"github.com/DataDog/datadog-lambda-go/internal/trace"
"github.com/DataDog/datadog-lambda-go/internal/wrapper"
)
type (
// Config gives options for how ddlambda should behave
Config struct {
// APIKey is your Datadog API key. This is used for sending metrics.
APIKey string
// KMSAPIKey is your Datadog API key, encrypted using the AWS KMS service. This is used for sending metrics.
KMSAPIKey string
// ShouldRetryOnFailure is used to turn on retry logic when sending metrics via the API. This can negatively effect the performance of your lambda,
// and should only be turned on if you can't afford to lose metrics data under poor network conditions.
ShouldRetryOnFailure bool
// ShouldUseLogForwarder enabled the log forwarding method for sending metrics to Datadog. This approach requires the user to set up a custom lambda
// function that forwards metrics from cloudwatch to the Datadog api. This approach doesn't have any impact on the performance of your lambda function.
ShouldUseLogForwarder bool
// BatchInterval is the period of time which metrics are grouped together for processing to be sent to the API or written to logs.
// Any pending metrics are flushed at the end of the lambda.
BatchInterval time.Duration
// Site is the host to send metrics to. If empty, this value is read from the 'DD_SITE' environment variable, or if that is empty
// will default to 'datadoghq.com'.
Site string
// DebugLogging will turn on extended debug logging.
DebugLogging bool
// EnhancedMetrics enables the reporting of enhanced metrics under `aws.lambda.enhanced*` and adds enhanced metric tags
EnhancedMetrics bool
// DDTraceEnabled enables the Datadog tracer.
DDTraceEnabled bool
// MergeXrayTraces will cause Datadog traces to be merged with traces from AWS X-Ray.
MergeXrayTraces bool
}
)
const (
// DatadogAPIKeyEnvVar is the environment variable that will be used to set the API key.
DatadogAPIKeyEnvVar = "DD_API_KEY"
// DatadogKMSAPIKeyEnvVar is the environment variable that will be sent to KMS for decryption, then used as an API key.
DatadogKMSAPIKeyEnvVar = "DD_KMS_API_KEY"
// DatadogSiteEnvVar is the environment variable that will be used as the API host.
DatadogSiteEnvVar = "DD_SITE"
// LogLevelEnvVar is the environment variable that will be used to set the log level.
LogLevelEnvVar = "DD_LOG_LEVEL"
// ShouldUseLogForwarderEnvVar is the environment variable that enables log forwarding of metrics.
ShouldUseLogForwarderEnvVar = "DD_FLUSH_TO_LOG"
// DatadogTraceEnabledEnvVar is the environment variable that enables Datadog tracing.
DatadogTraceEnabledEnvVar = "DD_TRACE_ENABLED"
// MergeXrayTracesEnvVar is the environment variable that enables the merging of X-Ray and Datadog traces.
MergeXrayTracesEnvVar = "DD_MERGE_XRAY_TRACES"
// DefaultSite to send API messages to.
DefaultSite = "datadoghq.com"
// DefaultEnhancedMetrics enables enhanced metrics by default.
DefaultEnhancedMetrics = true
)
// WrapHandler is used to instrument your lambda functions.
// It returns a modified handler that can be passed directly to the lambda. Start function.
func WrapHandler(handler interface{}, cfg *Config) interface{} {
logLevel := os.Getenv(LogLevelEnvVar)
if strings.EqualFold(logLevel, "debug") || (cfg != nil && cfg.DebugLogging) {
logger.SetLogLevel(logger.LevelDebug)
}
// Wrap the handler with listeners that add instrumentation for traces and metrics.
tl := trace.MakeListener(cfg.toTraceConfig())
ml := metrics.MakeListener(cfg.toMetricsConfig())
return wrapper.WrapHandlerWithListeners(handler, &tl, &ml)
}
// GetTraceHeaders reads a map containing the Datadog trace headers from a context object.
// Deprecated: Use dd-trace-go to extract the current span from the context instead
func GetTraceHeaders(ctx context.Context) map[string]string {
result := trace.GetTraceHeaders(ctx, true)
return result
}
// AddTraceHeaders adds Datadog trace headers to a HTTP Request
// Deprecated: Use dd-trace-go to extract the current span from the context instead
func AddTraceHeaders(ctx context.Context, req *http.Request) {
headers := GetTraceHeaders(ctx)
for key, value := range headers {
req.Header.Add(key, value)
}
}
// GetContext retrieves the last created lambda context.
// Only use this if you aren't manually passing context through your call hierarchy.
func GetContext() context.Context {
return wrapper.CurrentContext
}
// Distribution sends a distribution metric to Datadog
// Deprecated: Use Metric method instead
func Distribution(metric string, value float64, tags ...string) {
Metric(metric, value, tags...)
}
// Metric sends a distribution metric to DataDog
func Metric(metric string, value float64, tags ...string) {
MetricWithTimestamp(metric, value, time.Now(), tags...)
}
// MetricWithTimestamp sends a distribution metric to DataDog with a custom timestamp
func MetricWithTimestamp(metric string, value float64, timestamp time.Time, tags ...string) {
ctx := GetContext()
if ctx == nil {
logger.Debug("no context available, did you wrap your handler?")
return
}
listener := metrics.GetListener(ctx)
if listener == nil {
logger.Error(fmt.Errorf("couldn't get metrics listener from current context"))
return
}
listener.AddDistributionMetric(metric, value, timestamp, false, tags...)
}
// InvokeDryRun is a utility to easily run your lambda for testing
func InvokeDryRun(callback func(ctx context.Context), cfg *Config) (interface{}, error) {
wrapped := WrapHandler(callback, cfg)
// Convert the wrapped handler to it's underlying raw handler type
handler, ok := wrapped.(func(ctx context.Context, msg json.RawMessage) (interface{}, error))
if !ok {
logger.Debug("Could not unwrap lambda during dry run")
}
return handler(context.Background(), json.RawMessage("{}"))
}
func (cfg *Config) toTraceConfig() trace.Config {
traceConfig := trace.Config{
DDTraceEnabled: false,
MergeXrayTraces: false,
}
if cfg != nil {
traceConfig.DDTraceEnabled = cfg.DDTraceEnabled
traceConfig.MergeXrayTraces = cfg.MergeXrayTraces
}
if !traceConfig.DDTraceEnabled {
traceConfig.DDTraceEnabled, _ = strconv.ParseBool(os.Getenv(DatadogTraceEnabledEnvVar))
}
if !traceConfig.MergeXrayTraces {
traceConfig.MergeXrayTraces, _ = strconv.ParseBool(os.Getenv(MergeXrayTracesEnvVar))
}
return traceConfig
}
func (cfg *Config) toMetricsConfig() metrics.Config {
mc := metrics.Config{
ShouldRetryOnFailure: false,
}
if cfg != nil {
mc.BatchInterval = cfg.BatchInterval
mc.ShouldRetryOnFailure = cfg.ShouldRetryOnFailure
mc.APIKey = cfg.APIKey
mc.KMSAPIKey = cfg.KMSAPIKey
mc.Site = cfg.Site
mc.ShouldUseLogForwarder = cfg.ShouldUseLogForwarder
}
if mc.Site == "" {
mc.Site = os.Getenv(DatadogSiteEnvVar)
}
if mc.Site == "" {
mc.Site = DefaultSite
}
if strings.HasPrefix(mc.Site, "https://") || strings.HasPrefix(mc.Site, "http://") {
mc.Site = fmt.Sprintf("%s/api/v1", mc.Site)
} else {
mc.Site = fmt.Sprintf("https://api.%s/api/v1", mc.Site)
}
if !mc.ShouldUseLogForwarder {
shouldUseLogForwarder := os.Getenv(ShouldUseLogForwarderEnvVar)
mc.ShouldUseLogForwarder = strings.EqualFold(shouldUseLogForwarder, "true")
}
if mc.APIKey == "" {
mc.APIKey = os.Getenv(DatadogAPIKeyEnvVar)
}
if mc.KMSAPIKey == "" {
mc.KMSAPIKey = os.Getenv(DatadogKMSAPIKeyEnvVar)
}
if mc.APIKey == "" && mc.KMSAPIKey == "" && !mc.ShouldUseLogForwarder {
logger.Error(fmt.Errorf("couldn't read DD_API_KEY or DD_KMS_API_KEY from environment"))
}
enhancedMetrics := os.Getenv("DD_ENHANCED_METRICS")
if enhancedMetrics == "" {
mc.EnhancedMetrics = DefaultEnhancedMetrics
}
if !mc.EnhancedMetrics {
mc.EnhancedMetrics = strings.EqualFold(enhancedMetrics, "true")
}
return mc
}