Skip to content

Commit 3924d8e

Browse files
committed
Inject trace context via Propagators into from AWS SDK Instrumentation
1 parent bbfd7d1 commit 3924d8e

File tree

11 files changed

+324
-14
lines changed

11 files changed

+324
-14
lines changed
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
build
22
node_modules
33
.eslintrc.js
4-
version.ts
4+
version.ts
5+
src/third-party

aws-distro-opentelemetry-node-autoinstrumentation/package.json

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,18 @@
3131
"prepublishOnly": "npm run compile",
3232
"tdd": "yarn test -- --watch-extensions ts --watch",
3333
"test": "nyc ts-mocha --timeout 10000 -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/*.ts'",
34-
"test:coverage": "nyc --all --check-coverage --functions 95 --lines 95 ts-mocha --timeout 10000 -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/*.ts'",
34+
"test:coverage": "nyc --check-coverage --functions 95 --lines 95 ts-mocha --timeout 10000 -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/*.ts'",
3535
"watch": "tsc -w"
3636
},
37+
"nyc": {
38+
"all": true,
39+
"include": [
40+
"src/**/*.ts"
41+
],
42+
"exclude": [
43+
"src/third-party/**/*"
44+
]
45+
},
3746
"bugs": {
3847
"url": "https://github.com/aws-observability/aws-otel-js-instrumentation/issues"
3948
},
@@ -65,6 +74,7 @@
6574
"@aws-sdk/client-bedrock-runtime": "3.632.0",
6675
"@aws-sdk/client-kinesis": "3.632.0",
6776
"@aws-sdk/client-s3": "3.632.0",
77+
"@smithy/protocol-http": "4.1.8",
6878
"@opentelemetry/contrib-test-utils": "0.41.0",
6979
"@types/mocha": "7.0.2",
7080
"@types/node": "18.6.5",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';
5+
import { InstrumentationModuleDefinition, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
6+
import { context, defaultTextMapSetter } from '@opentelemetry/api';
7+
import { propwrap } from './../../third-party/otel/aws/propwrap';
8+
import { AWSXRayPropagator } from '@opentelemetry/propagator-aws-xray';
9+
10+
const awsXrayPropagator = new AWSXRayPropagator();
11+
12+
// This class extends the upstream AwsInstrumentation to add an additional
13+
// module instrumentation to patch `HttpRequest` of the `@smithy/protocol-http` module.
14+
// This additional module instrumentation will replace HttpRequest with an extended version
15+
// that injects the `X-Amzn-Trace-Id` HTTP header in the constructor so that aws-sdk-js-v3
16+
// client calls can propagate the X-Ray trace context
17+
export class AwsSdkInstrumentationExtended extends AwsInstrumentation {
18+
protected override init(): InstrumentationModuleDefinition[] {
19+
const instrumentationModuleDefinitions = super.init();
20+
21+
const v3SmithyProtocolHttp = new InstrumentationNodeModuleDefinition(
22+
'@smithy/protocol-http',
23+
['>=2.0.0'],
24+
(moduleExports: any) => {
25+
const newExports = propwrap(moduleExports, 'HttpRequest', (origHttpRequest: any) => {
26+
class ExtendedHttpRequest extends origHttpRequest {
27+
constructor(...args: any[]) {
28+
super(...args);
29+
awsXrayPropagator.inject(context.active(), this.headers, defaultTextMapSetter);
30+
}
31+
}
32+
33+
return ExtendedHttpRequest;
34+
});
35+
36+
return newExports;
37+
}
38+
);
39+
40+
return [...instrumentationModuleDefinitions, v3SmithyProtocolHttp];
41+
}
42+
}

aws-distro-opentelemetry-node-autoinstrumentation/src/patches/instrumentation-patch.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ import {
2525
} from './aws/services/bedrock';
2626
import { KinesisServiceExtension } from './aws/services/kinesis';
2727
import { S3ServiceExtension } from './aws/services/s3';
28-
import { AwsLambdaInstrumentationPatch } from './aws/services/aws-lambda';
28+
import { AwsLambdaInstrumentationPatch } from './extended-instrumentations/aws-lambda';
29+
import { InstrumentationConfigMap } from '@opentelemetry/auto-instrumentations-node';
30+
import { AwsSdkInstrumentationExtended } from './extended-instrumentations/aws-sdk-instrumentation-extended';
2931

3032
export const traceContextEnvironmentKey = '_X_AMZN_TRACE_ID';
3133
const awsPropagator = new AWSXRayPropagator();
@@ -38,7 +40,10 @@ export const headerGetter: TextMapGetter<APIGatewayProxyEventHeaders> = {
3840
},
3941
};
4042

41-
export function applyInstrumentationPatches(instrumentations: Instrumentation[]): void {
43+
export function applyInstrumentationPatches(
44+
instrumentations: Instrumentation[],
45+
instrumentationConfigs?: InstrumentationConfigMap
46+
): void {
4247
/*
4348
Apply patches to upstream instrumentation libraries.
4449
@@ -50,10 +55,16 @@ export function applyInstrumentationPatches(instrumentations: Instrumentation[])
5055
*/
5156
instrumentations.forEach((instrumentation, index) => {
5257
if (instrumentation.instrumentationName === '@opentelemetry/instrumentation-aws-sdk') {
58+
diag.debug('Overriding aws sdk instrumentation');
59+
instrumentations[index] = new AwsSdkInstrumentationExtended(
60+
instrumentationConfigs ? instrumentationConfigs['@opentelemetry/instrumentation-aws-sdk'] : undefined
61+
);
62+
5363
// Access private property servicesExtensions of AwsInstrumentation
5464
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
5565
// @ts-ignore
56-
const services: Map<string, ServiceExtension> | undefined = (instrumentation as any).servicesExtensions?.services;
66+
const services: Map<string, ServiceExtension> | undefined = (instrumentations[index] as any).servicesExtensions
67+
?.services;
5768
if (services) {
5869
services.set('S3', new S3ServiceExtension());
5970
services.set('Kinesis', new KinesisServiceExtension());

aws-distro-opentelemetry-node-autoinstrumentation/src/register.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ const instrumentationConfigs: InstrumentationConfigMap = {
6262
const instrumentations: Instrumentation[] = getNodeAutoInstrumentations(instrumentationConfigs);
6363

6464
// Apply instrumentation patches
65-
applyInstrumentationPatches(instrumentations);
65+
applyInstrumentationPatches(instrumentations, instrumentationConfigs);
6666

6767
const configurator: AwsOpentelemetryConfigurator = new AwsOpentelemetryConfigurator(instrumentations, useXraySampler);
6868
const configuration: Partial<opentelemetry.NodeSDKConfiguration> = configurator.configure();
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
/*
2+
* Copyright The OpenTelemetry Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
/*
18+
* This block is derived from esbuild's bundling support.
19+
* https://github.com/evanw/esbuild/blob/v0.14.42/internal/runtime/runtime.go#L22
20+
*
21+
* License:
22+
* MIT License
23+
*
24+
* Copyright (c) 2020 Evan Wallace
25+
*
26+
* Permission is hereby granted, free of charge, to any person obtaining a copy
27+
* of this software and associated documentation files (the "Software"), to deal
28+
* in the Software without restriction, including without limitation the rights
29+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30+
* copies of the Software, and to permit persons to whom the Software is
31+
* furnished to do so, subject to the following conditions:
32+
*
33+
* The above copyright notice and this permission notice shall be included in all
34+
* copies or substantial portions of the Software.
35+
*
36+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
42+
* SOFTWARE.
43+
*/
44+
const __defProp = Object.defineProperty;
45+
const __getOwnPropDesc = Object.getOwnPropertyDescriptor;
46+
const __hasOwnProp = Object.prototype.hasOwnProperty;
47+
const __getOwnPropNames = Object.getOwnPropertyNames;
48+
const __copyProps = (
49+
to: any,
50+
from: any,
51+
except: string,
52+
desc?: PropertyDescriptor | undefined
53+
) => {
54+
if ((from && typeof from === 'object') || typeof from === 'function') {
55+
for (const key of __getOwnPropNames(from)) {
56+
if (!__hasOwnProp.call(to, key) && key !== except) {
57+
__defProp(to, key, {
58+
get: () => from[key] as any,
59+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable,
60+
});
61+
}
62+
}
63+
}
64+
return to;
65+
};
66+
67+
/**
68+
* Return a new object that is a copy of `obj`, with its `subpath` property
69+
* replaced with the return value of `wrapper(original)`.
70+
*
71+
* This is similar to shimmer (i.e. `InstrumentationBase.prototype._wrap`).
72+
* However, it uses a different technique to support wrapping properties that
73+
* are only available via a getter (i.e. their property descriptor is `.writable
74+
* === false`).
75+
*
76+
* For example:
77+
* var os = propwrap(require('os'), 'platform', (orig) => {
78+
* return function wrappedPlatform () {
79+
* return orig().toUpperCase()
80+
* }
81+
* })
82+
* console.log(os.platform()) // => DARWIN
83+
*
84+
* The subpath can indicate a nested property. Each property in that subpath,
85+
* except the last, must identify an *Object*.
86+
*
87+
* Limitations:
88+
* - This doesn't handle possible Symbol properties on the copied object(s).
89+
* - This cannot wrap a property of a function, because we cannot create a
90+
* copy of the function.
91+
*
92+
* @param {object} obj
93+
* @param {string} subpath - The property subpath on `obj` to wrap. This may
94+
* point to a nested property by using a '.' to separate levels. For example:
95+
* var fs = wrap(fs, 'promises.sync', (orig) => { ... })
96+
* @param {Function} wrapper - A function of the form `function (orig)`, where
97+
* `orig` is the original property value. This must synchronously return the
98+
* new property value.
99+
* @returns {object} A new object with the wrapped property.
100+
* @throws {TypeError} if the subpath points to a non-existent property, or if
101+
* any but the last subpath part points to a non-Object.
102+
*/
103+
export const propwrap = (obj: any, subpath: string, wrapper: Function): any => {
104+
const parts = subpath.split('.');
105+
const namespaces = [obj];
106+
let namespace = obj;
107+
let key;
108+
let val;
109+
110+
// 1. Traverse the subpath parts to sanity check and get references to the
111+
// Objects that we will be copying.
112+
for (let i = 0; i < parts.length; i++) {
113+
key = parts[i];
114+
val = namespace[key];
115+
if (!val) {
116+
throw new TypeError(
117+
`cannot wrap "${subpath}": "<obj>.${parts
118+
.slice(0, i)
119+
.join('.')}" is ${typeof val}`
120+
);
121+
} else if (i < parts.length - 1) {
122+
if (typeof val !== 'object') {
123+
throw new TypeError(
124+
`cannot wrap "${subpath}": "<obj>.${parts
125+
.slice(0, i)
126+
.join('.')}" is not an Object`
127+
);
128+
}
129+
namespace = val;
130+
namespaces.push(namespace);
131+
}
132+
}
133+
134+
// 2. Now work backwards, wrapping each namespace with a new object that has a
135+
// copy of all the properties, except the one that we've wrapped.
136+
for (let i = parts.length - 1; i >= 0; i--) {
137+
key = parts[i];
138+
namespace = namespaces[i];
139+
if (i === parts.length - 1) {
140+
const orig = namespace[key];
141+
val = wrapper(orig);
142+
} else {
143+
val = namespaces[i + 1];
144+
}
145+
const desc = __getOwnPropDesc(namespace, key);
146+
const wrappedNamespace = __defProp({}, key, {
147+
value: val,
148+
enumerable: !desc || desc.enumerable,
149+
});
150+
__copyProps(wrappedNamespace, namespace, key);
151+
namespaces[i] = wrappedNamespace;
152+
}
153+
154+
return namespaces[0];
155+
};

aws-distro-opentelemetry-node-autoinstrumentation/test/patches/aws/services/aws-lambda.test.ts renamed to aws-distro-opentelemetry-node-autoinstrumentation/test/patches/extended-instrumentations/aws-lambda.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import * as path from 'path';
66
import * as fs from 'fs';
77
import { diag } from '@opentelemetry/api';
88
import { InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
9-
import { AwsLambdaInstrumentationPatch } from '../../../../src/patches/aws/services/aws-lambda';
9+
import { AwsLambdaInstrumentationPatch } from '../../../src/patches/extended-instrumentations/aws-lambda';
1010

1111
describe('AwsLambdaInstrumentationPatch', () => {
1212
let instrumentation: AwsLambdaInstrumentationPatch;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
import * as sinon from 'sinon';
4+
import { AwsSdkInstrumentationExtended } from '../../../src/patches/extended-instrumentations/aws-sdk-instrumentation-extended';
5+
import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';
6+
import expect from 'expect';
7+
import { AWSXRayPropagator } from '@opentelemetry/propagator-aws-xray';
8+
import { Context, TextMapSetter } from '@opentelemetry/api';
9+
import { HttpRequest } from '@smithy/protocol-http';
10+
11+
describe('AwsSdkInstrumentationExtended', () => {
12+
let instrumentation: AwsSdkInstrumentationExtended;
13+
14+
beforeEach(() => {
15+
instrumentation = new AwsSdkInstrumentationExtended({});
16+
});
17+
18+
afterEach(() => {
19+
sinon.restore();
20+
});
21+
22+
it('overridden init patches smithy HttpRequest', () => {
23+
sinon.stub(AwsInstrumentation.prototype as any, 'init').returns([]);
24+
sinon
25+
.stub(AWSXRayPropagator.prototype, 'inject')
26+
.callsFake((context: Context, carrier: unknown, setter: TextMapSetter) => {
27+
(carrier as any)['isCarrierModified'] = 'carrierIsModified';
28+
});
29+
const result = (instrumentation as any).init();
30+
expect(result.length).toEqual(1);
31+
32+
const patchedHttpRequestObject = new HttpRequest({});
33+
expect(patchedHttpRequestObject.headers['isCarrierModified']).toEqual('carrierIsModified');
34+
});
35+
});

0 commit comments

Comments
 (0)