-
Notifications
You must be signed in to change notification settings - Fork 552
/
Copy pathinstrumentation.ts
339 lines (309 loc) · 10.1 KB
/
instrumentation.ts
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as path from 'path';
import {
InstrumentationBase,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
isWrapped,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import {
Context as OtelContext,
context as otelContext,
diag,
trace,
propagation,
Span,
SpanKind,
SpanStatusCode,
TextMapGetter,
TraceFlags,
TracerProvider,
} from '@opentelemetry/api';
import {
AWSXRAY_TRACE_ID_HEADER,
AWSXRayPropagator,
} from '@opentelemetry/propagator-aws-xray';
import {
SemanticAttributes,
ResourceAttributes,
} from '@opentelemetry/semantic-conventions';
import { BasicTracerProvider } from '@opentelemetry/tracing';
import {
APIGatewayProxyEventHeaders,
Callback,
Context,
Handler,
} from 'aws-lambda';
import { LambdaModule, AwsLambdaInstrumentationConfig } from './types';
import { VERSION } from './version';
const awsPropagator = new AWSXRayPropagator();
const headerGetter: TextMapGetter<APIGatewayProxyEventHeaders> = {
keys(carrier): string[] {
return Object.keys(carrier);
},
get(carrier, key: string) {
return carrier[key];
},
};
export const traceContextEnvironmentKey = '_X_AMZN_TRACE_ID';
export class AwsLambdaInstrumentation extends InstrumentationBase {
private _tracerProvider: TracerProvider | undefined;
constructor(protected _config: AwsLambdaInstrumentationConfig = {}) {
super('@opentelemetry/instrumentation-aws-lambda', VERSION, _config);
}
setConfig(config: AwsLambdaInstrumentationConfig = {}) {
this._config = config;
}
init() {
const taskRoot = process.env.LAMBDA_TASK_ROOT;
const handlerDef = process.env._HANDLER;
// _HANDLER and LAMBDA_TASK_ROOT are always defined in Lambda but guard bail out if in the future this changes.
if (!taskRoot || !handlerDef) {
return [];
}
const handler = path.basename(handlerDef);
const moduleRoot = handlerDef.substr(0, handlerDef.length - handler.length);
const [module, functionName] = handler.split('.', 2);
// Lambda loads user function using an absolute path.
let filename = path.resolve(taskRoot, moduleRoot, module);
if (!filename.endsWith('.js')) {
// Patching infrastructure currently requires a filename when requiring with an absolute path.
filename += '.js';
}
return [
new InstrumentationNodeModuleDefinition(
// NB: The patching infrastructure seems to match names backwards, this must be the filename, while
// InstrumentationNodeModuleFile must be the module name.
filename,
['*'],
undefined,
undefined,
[
new InstrumentationNodeModuleFile(
module,
['*'],
(moduleExports: LambdaModule) => {
diag.debug('Applying patch for lambda handler');
if (isWrapped(moduleExports[functionName])) {
this._unwrap(moduleExports, functionName);
}
this._wrap(moduleExports, functionName, this._getHandler());
return moduleExports;
},
(moduleExports?: LambdaModule) => {
if (moduleExports == undefined) return;
diag.debug('Removing patch for lambda handler');
this._unwrap(moduleExports, functionName);
}
),
]
),
];
}
private _getHandler() {
return (original: Handler) => {
return this._getPatchHandler(original);
};
}
private _getPatchHandler(original: Handler) {
diag.debug('patch handler function');
const plugin = this;
return function patchedHandler(
this: never,
// The event can be a user type, it truly is any.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
event: any,
context: Context,
callback: Callback
) {
const httpHeaders =
typeof event.headers === 'object' ? event.headers : {};
const parent = AwsLambdaInstrumentation._determineParent(httpHeaders);
const name = context.functionName;
const span = plugin.tracer.startSpan(
name,
{
kind: SpanKind.SERVER,
attributes: {
[SemanticAttributes.FAAS_EXECUTION]: context.awsRequestId,
[ResourceAttributes.FAAS_ID]: context.invokedFunctionArn,
[ResourceAttributes.CLOUD_ACCOUNT_ID]:
AwsLambdaInstrumentation._extractAccountId(
context.invokedFunctionArn
),
},
},
parent
);
if (plugin._config.requestHook) {
safeExecuteInTheMiddle(
() => plugin._config.requestHook!(span, { event, context }),
e => {
if (e)
diag.error('aws-lambda instrumentation: requestHook error', e);
},
true
);
}
return otelContext.with(trace.setSpan(otelContext.active(), span), () => {
// Lambda seems to pass a callback even if handler is of Promise form, so we wrap all the time before calling
// the handler and see if the result is a Promise or not. In such a case, the callback is usually ignored. If
// the handler happened to both call the callback and complete a returned Promise, whichever happens first will
// win and the latter will be ignored.
const wrappedCallback = plugin._wrapCallback(callback, span);
const maybePromise = safeExecuteInTheMiddle(
() => original.apply(this, [event, context, wrappedCallback]),
error => {
if (error != null) {
// Exception thrown synchronously before resolving callback / promise.
plugin._applyResponseHook(span, error);
plugin._endSpan(span, error, () => {});
}
}
) as Promise<{}> | undefined;
if (typeof maybePromise?.then === 'function') {
return maybePromise.then(
value => {
plugin._applyResponseHook(span, null, value);
return new Promise(resolve =>
plugin._endSpan(span, undefined, () => resolve(value))
);
},
(err: Error | string) => {
plugin._applyResponseHook(span, err);
return new Promise((resolve, reject) =>
plugin._endSpan(span, err, () => reject(err))
);
}
);
}
return maybePromise;
});
};
}
setTracerProvider(tracerProvider: TracerProvider) {
super.setTracerProvider(tracerProvider);
this._tracerProvider = tracerProvider;
}
private _wrapCallback(original: Callback, span: Span): Callback {
const plugin = this;
return function wrappedCallback(this: never, err, res) {
diag.debug('executing wrapped lookup callback function');
plugin._applyResponseHook(span, err, res);
plugin._endSpan(span, err, () => {
diag.debug('executing original lookup callback function');
return original.apply(this, [err, res]);
});
};
}
private _endSpan(
span: Span,
err: string | Error | null | undefined,
callback: () => void
) {
if (err) {
span.recordException(err);
}
let errMessage;
if (typeof err === 'string') {
errMessage = err;
} else if (err) {
errMessage = err.message;
}
if (errMessage) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: errMessage,
});
}
span.end();
if (this._tracerProvider instanceof BasicTracerProvider) {
this._tracerProvider
.getActiveSpanProcessor()
.forceFlush()
.then(
() => callback(),
() => callback()
);
} else {
callback();
}
}
private _applyResponseHook(
span: Span,
err?: Error | string | null,
res?: any
) {
if (this._config?.responseHook) {
safeExecuteInTheMiddle(
() => this._config.responseHook!(span, { err, res }),
e => {
if (e)
diag.error('aws-lambda instrumentation: responseHook error', e);
},
true
);
}
}
private static _extractAccountId(arn: string): string | undefined {
const parts = arn.split(':');
if (parts.length >= 5) {
return parts[4];
}
return undefined;
}
private static _determineParent(
httpHeaders: APIGatewayProxyEventHeaders
): OtelContext {
let parent: OtelContext | undefined = undefined;
const lambdaTraceHeader = process.env[traceContextEnvironmentKey];
if (lambdaTraceHeader) {
parent = awsPropagator.extract(
otelContext.active(),
{ [AWSXRAY_TRACE_ID_HEADER]: lambdaTraceHeader },
headerGetter
);
}
if (parent) {
const spanContext = trace.getSpan(parent)?.spanContext();
if (
spanContext &&
(spanContext.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED
) {
// Trace header provided by Lambda only sampled if a sampled context was propagated from
// an upstream cloud service such as S3, or the user is using X-Ray. In these cases, we
// need to use it as the parent.
return parent;
}
}
// There was not a sampled trace header from Lambda so try from HTTP headers.
const httpContext = propagation.extract(
otelContext.active(),
httpHeaders,
headerGetter
);
if (trace.getSpan(httpContext)?.spanContext()) {
return httpContext;
}
if (!parent) {
// No context in Lambda environment or HTTP headers.
return otelContext.active();
}
return parent;
}
}