-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathredirect.ts
More file actions
80 lines (71 loc) · 2.47 KB
/
Copy pathredirect.ts
File metadata and controls
80 lines (71 loc) · 2.47 KB
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
/*
* 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 2020-2026 Datadog, Inc.
*/
import * as lambda from "aws-cdk-lib/aws-lambda";
import log from "loglevel";
import {
RuntimeType,
runtimeLookup,
DD_HANDLER_ENV_VAR,
AWS_LAMBDA_EXEC_WRAPPER_ENV_VAR,
AWS_LAMBDA_EXEC_WRAPPER,
JS_HANDLER_WITH_LAYERS,
JS_HANDLER,
PYTHON_HANDLER,
} from "./constants";
import { LambdaFunction } from "./interfaces";
/**
* To avoid modifying code in the user's lambda handler, redirect the handler to a Datadog
* handler that initializes the Lambda Layers and then calls the original handler.
* 'DD_LAMBDA_HANDLER' is set to the original handler in the lambda's environment for the
* replacement handler to find.
*
* Unchanged aside from parameter type
*/
export function redirectHandlers(lam: LambdaFunction, addLayers: boolean, useExtension: boolean): void {
log.debug(`Wrapping Lambda function handlers with Datadog handler...`);
const runtime: string = lam.runtime.name;
const runtimeType: RuntimeType = runtimeLookup[runtime];
if (runtimeType === RuntimeType.JAVA || runtimeType === RuntimeType.DOTNET) {
if (useExtension) {
lam.addEnvironment(AWS_LAMBDA_EXEC_WRAPPER_ENV_VAR, AWS_LAMBDA_EXEC_WRAPPER);
}
return;
}
const cfnFuntion = (lam instanceof lambda.SingletonFunction ? lam.permissionsNode : lam.node)
.defaultChild as lambda.CfnFunction;
if (cfnFuntion === undefined) {
log.debug("Unable to get Lambda Function handler");
return;
}
const originalHandler = cfnFuntion.handler as string;
lam.addEnvironment(DD_HANDLER_ENV_VAR, originalHandler);
const handler = getDDHandler(runtimeType, addLayers);
if (handler === null) {
log.debug("Unable to get Datadog handler");
return;
}
cfnFuntion.handler = handler;
}
function getDDHandler(runtimeType: RuntimeType, addLayers: boolean): string | null {
if (runtimeType === undefined || runtimeType === RuntimeType.UNSUPPORTED) {
log.debug("Unsupported/undefined Lambda runtime");
return null;
}
switch (runtimeType) {
case RuntimeType.NODE:
return addLayers ? JS_HANDLER_WITH_LAYERS : JS_HANDLER;
case RuntimeType.PYTHON:
return PYTHON_HANDLER;
case RuntimeType.CUSTOM:
case RuntimeType.JAVA:
case RuntimeType.DOTNET:
case RuntimeType.RUBY:
default:
return null;
}
}