Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: net module instrumentation #389

Merged
merged 17 commits into from
Mar 19, 2021
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build
7 changes: 7 additions & 0 deletions plugins/node/opentelemetry-instrumentation-net/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
"env": {
"mocha": true,
"node": true
},
...require('../../../eslint.config.js')
}
4 changes: 4 additions & 0 deletions plugins/node/opentelemetry-instrumentation-net/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/bin
/coverage
/doc
/test
68 changes: 68 additions & 0 deletions plugins/node/opentelemetry-instrumentation-net/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"name": "@opentelemetry/instrumentation-net",
"version": "0.14.0",
"description": "OpenTelemetry net module automatic instrumentation package.",
"main": "build/src/index.js",
"types": "build/src/index.d.ts",
"repository": "open-telemetry/opentelemetry-js-contrib",
"scripts": {
"test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'",
"tdd": "npm run test -- --watch-extensions ts --watch",
"clean": "rimraf build/*",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix",
"codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../",
"precompile": "tsc --version",
"prepare": "npm run compile",
"version:update": "node ../../../scripts/version-update.js",
"compile": "npm run version:update && tsc -p ."
},
"keywords": [
"opentelemetry",
"net",
"connect",
"nodejs",
"tracing",
"profiling",
"instrumentation"
],
"author": "OpenTelemetry Authors",
"license": "Apache-2.0",
"engines": {
"node": ">=8.5.0"
},
"files": [
"build/src/**/*.js",
"build/src/**/*.d.ts",
"doc",
"LICENSE",
"README.md"
],
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@opentelemetry/core": "0.18.0",
"@opentelemetry/node": "0.18.0",
"@opentelemetry/tracing": "0.18.0",
"@types/mocha": "7.0.2",
"@types/node": "14.0.27",
"@types/sinon": "9.0.4",
"codecov": "3.7.2",
"gts": "3.1.0",
"mocha": "7.2.0",
"nyc": "15.1.0",
"rimraf": "3.0.2",
"sinon": "9.0.2",
"ts-mocha": "8.0.0",
"ts-node": "9.0.0",
"tslint-consistent-codestyle": "1.16.0",
"tslint-microsoft-contrib": "6.2.0",
"typescript": "4.1.3"
},
"dependencies": {
"@opentelemetry/api": "^0.18.0",
"@opentelemetry/instrumentation": "^0.18.0",
"@opentelemetry/semantic-conventions": "^0.18.0"
}
}
17 changes: 17 additions & 0 deletions plugins/node/opentelemetry-instrumentation-net/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* 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.
*/

export * from './net';
236 changes: 236 additions & 0 deletions plugins/node/opentelemetry-instrumentation-net/src/net.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
/*
* 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 {
diag,
Tracer,
Span,
SpanKind,
SpanStatusCode,
} from '@opentelemetry/api';
import {
InstrumentationBase,
InstrumentationConfig,
InstrumentationNodeModuleDefinition,
isWrapped,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import { GeneralAttribute } from '@opentelemetry/semantic-conventions';
import { Net } from './types';
import { VERSION } from './version';
import { platform } from 'os';
import { Socket } from 'net';

const IPC_TRANSPORT = platform() == 'win32' ? 'pipe' : 'Unix';
obecny marked this conversation as resolved.
Show resolved Hide resolved

export class NetInstrumentation extends InstrumentationBase<Net> {
constructor(protected _config: InstrumentationConfig = {}) {
super('@opentelemetry/instrumentation-net', VERSION, _config);
}

init(): InstrumentationNodeModuleDefinition<Net>[] {
return [
new InstrumentationNodeModuleDefinition<Net>(
'net',
['*'],
moduleExports => {
diag.debug('Applying patch for net module');
if (isWrapped(moduleExports.Socket.prototype.connect)) {
this._unwrap(moduleExports.Socket.prototype, 'connect');
}
this._wrap(
moduleExports.Socket.prototype,
'connect',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._getPatchedConnect() as any
);
return moduleExports;
},
moduleExports => {
if (moduleExports === undefined) return;
diag.debug('Removing patch from net module');
this._unwrap(moduleExports.Socket.prototype, 'connect');
}
),
];
}

private _getPatchedConnect() {
return (original: (...args: unknown[]) => void) => {
const plugin = this;
return function patchedConnect(this: Socket, ...args: unknown[]) {
const options = normalizedArgs(args);

const span = options
? options.path
? startIpcSpan(plugin.tracer, options, this)
: startTcpSpan(plugin.tracer, options, this)
: startGenericSpan(plugin.tracer, this);

return safeExecuteInTheMiddle(
() => original.apply(this, args),
error => {
if (error !== undefined) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
});
span.end();
}
}
);
};
};
}
}

interface NormalizedOptions {
seemk marked this conversation as resolved.
Show resolved Hide resolved
host?: string;
port?: number;
path?: string;
}

function normalizedArgs(args: unknown[]): NormalizedOptions | null | undefined {
seemk marked this conversation as resolved.
Show resolved Hide resolved
const opt = args[0];
if (!opt) {
return;
}

switch (typeof opt) {
case 'number':
return {
port: opt,
host: typeof args[1] === 'string' ? args[1] : 'localhost',
};
case 'object':
if (Array.isArray(opt)) {
return normalizedArgs(opt);
}
return opt;
case 'string':
return {
path: opt,
};
default:
return;
}
}

const SOCKET_EVENTS = ['connect', 'error', 'close'];
seemk marked this conversation as resolved.
Show resolved Hide resolved

function spanEndHandler(span: Span) {
return () => {
span.end();
};
}

function spanErrorHandler(span: Span) {
return (e: Error) => {
span.setStatus({
seemk marked this conversation as resolved.
Show resolved Hide resolved
code: SpanStatusCode.ERROR,
message: e.message,
});
};
}

interface ListenerOpts {
hostAttributes?: boolean;
}

function registerListeners(
obecny marked this conversation as resolved.
Show resolved Hide resolved
socket: Socket,
span: Span,
{ hostAttributes = false }: ListenerOpts = {}
) {
const setSpanError = spanErrorHandler(span);
const setSpanEnd = spanEndHandler(span);

const setHostAttributes = () => {
span.setAttributes({
[GeneralAttribute.NET_PEER_IP]: socket.remoteAddress,
[GeneralAttribute.NET_HOST_IP]: socket.localAddress,
[GeneralAttribute.NET_HOST_PORT]: socket.localPort,
});
};

socket.once('error', setSpanError);

if (hostAttributes) {
socket.once('connect', setHostAttributes);
}

const removeListeners = () => {
socket.removeListener('error', setSpanError);
socket.removeListener('connect', setHostAttributes);
for (const event of SOCKET_EVENTS) {
socket.removeListener(event, setSpanEnd);
socket.removeListener(event, removeListeners);
}
};

for (const event of SOCKET_EVENTS) {
socket.once(event, setSpanEnd);
socket.once(event, removeListeners);
}
}

/* It might still be useful to pick up errors due to invalid connect arguments. */
function startGenericSpan(tracer: Tracer, socket: Socket) {
const span = tracer.startSpan('connect', {
kind: SpanKind.CLIENT,
});

registerListeners(socket, span);

return span;
}

function startIpcSpan(
tracer: Tracer,
options: NormalizedOptions,
socket: Socket
) {
const span = tracer.startSpan('ipc.connect', {
kind: SpanKind.CLIENT,
attributes: {
[GeneralAttribute.NET_TRANSPORT]: IPC_TRANSPORT,
[GeneralAttribute.NET_PEER_NAME]: options.path,
},
});

registerListeners(socket, span);

return span;
}

function startTcpSpan(
tracer: Tracer,
options: NormalizedOptions,
socket: Socket
) {
const span = tracer.startSpan('tcp.connect', {
kind: SpanKind.CLIENT,
attributes: {
[GeneralAttribute.NET_TRANSPORT]: 'IP.TCP',
seemk marked this conversation as resolved.
Show resolved Hide resolved
[GeneralAttribute.NET_PEER_NAME]: options.host,
[GeneralAttribute.NET_PEER_PORT]: options.port,
},
});

registerListeners(socket, span, { hostAttributes: true });

return span;
}
19 changes: 19 additions & 0 deletions plugins/node/opentelemetry-instrumentation-net/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* 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 type * as net from 'net';

export type Net = typeof net;
18 changes: 18 additions & 0 deletions plugins/node/opentelemetry-instrumentation-net/src/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* 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.
*/

// this is autogenerated file, see scripts/version-update.js
export const VERSION = '0.14.0';
Loading