From 1c948d4b5e1ae705828c7877e391821706055369 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 09:20:27 +0200 Subject: [PATCH 01/16] feat: net module instrumentation --- .../.eslintrc.js | 7 + .../package.json | 71 ++++++ .../src/index.ts | 1 + .../src/net.ts | 217 +++++++++++++++++ .../src/types.ts | 25 ++ .../src/version.ts | 18 ++ .../test/connect.test.ts | 221 ++++++++++++++++++ .../test/instrument.test.ts | 75 ++++++ .../tsconfig.json | 11 + 9 files changed, 646 insertions(+) create mode 100644 plugins/node/opentelemetry-instrumentation-net/.eslintrc.js create mode 100644 plugins/node/opentelemetry-instrumentation-net/package.json create mode 100644 plugins/node/opentelemetry-instrumentation-net/src/index.ts create mode 100644 plugins/node/opentelemetry-instrumentation-net/src/net.ts create mode 100644 plugins/node/opentelemetry-instrumentation-net/src/types.ts create mode 100644 plugins/node/opentelemetry-instrumentation-net/src/version.ts create mode 100644 plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-net/tsconfig.json diff --git a/plugins/node/opentelemetry-instrumentation-net/.eslintrc.js b/plugins/node/opentelemetry-instrumentation-net/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-instrumentation-net/package.json b/plugins/node/opentelemetry-instrumentation-net/package.json new file mode 100644 index 0000000000..90f43220c6 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/package.json @@ -0,0 +1,71 @@ +{ + "name": "@opentelemetry/instrumentation-net", + "version": "0.1.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.0.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/semver": "7.3.1", + "@types/shimmer": "1.0.1", + "@types/sinon": "9.0.4", + "codecov": "3.7.2", + "gts": "2.0.2", + "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", + "semver": "^7.3.2" + } +} diff --git a/plugins/node/opentelemetry-instrumentation-net/src/index.ts b/plugins/node/opentelemetry-instrumentation-net/src/index.ts new file mode 100644 index 0000000000..10324a2fce --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/src/index.ts @@ -0,0 +1 @@ +export * from './net'; diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts new file mode 100644 index 0000000000..fa6a746704 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -0,0 +1,217 @@ +/* + * 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, + InstrumentationNodeModuleDefinition, + isWrapped, + safeExecuteInTheMiddle, +} from '@opentelemetry/instrumentation'; +import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; +import { + ConnectCallback, + Net, + NetInstrumentationConfig, +} from './types'; +import { VERSION } from './version'; +import { platform } from 'os'; +import { Socket, TcpSocketConnectOpts, IpcSocketConnectOpts } from 'net'; + +const IPC_TRANSPORT = platform() == 'win32' ? 'pipe' : 'Unix'; + +export class NetInstrumentation extends InstrumentationBase { + constructor(protected _config: NetInstrumentationConfig = {}) { + super('@opentelemetry/instrumentation-net', VERSION, _config); + } + + init(): InstrumentationNodeModuleDefinition[] { + return [ + new InstrumentationNodeModuleDefinition( + 'net', + ['*'], + moduleExports => { + diag.debug('Applying patch for net module'); + if (isWrapped(moduleExports.Socket.prototype.connect)) { + this._unwrap(moduleExports.Socket.prototype.connect, 'connect'); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._wrap(moduleExports.Socket.prototype, 'connect', 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( + ...args: unknown[] + ) { + const options = normalizedArgs(args); + + if (!options) { + startGenericSpan(plugin, this); + return original.apply(this, args); + } + + const span = options.path ? startIpcSpan(plugin, options, this) : startTcpSpan(plugin, options, this); + + return safeExecuteInTheMiddle( + () => original.apply(this, [...args]), + error => { + if (error !== undefined) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message, + }); + span.end(); + } + } + ); + + }; + }; + } +} + +function normalizedArgs(args: unknown[]): TcpSocketConnectOpts | IpcSocketConnectOpts | undefined { + if (!args[0]) { + return; + } + + switch (typeof args[0]) { + case 'number': + return { + port: args[0], + host: typeof args[1] === 'string' ? args[1] : 'localhost', + }; + case 'object': + if (Array.isArray(args[0])) { + return normalizedArgs(args[0]); + } + return args[0]; + case 'string': + return { + path: args[0], + }; + } +} + +const SOCKET_EVENTS = ['connect', 'error', 'close', 'timeout']; + +function spanEndHandler(span: Span) { + return () => { + span.end(); + }; +} + +function spanErrorHandler(span: Span) { + return (e: Error) => { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: e.message, + }); + }; +} + +function registerListeners(socket: Socket, span: Span) { + const setSpanError = spanErrorHandler(span); + const onEnd = spanEndHandler(span); + + socket.once('error', setSpanError); + + const removeListeners = () => { + socket.removeListener('error', setSpanError); + for (const event of SOCKET_EVENTS) { + socket.removeListener(event, onEnd); + socket.removeListener(event, removeListeners); + } + }; + + for (const event of SOCKET_EVENTS) { + socket.once(event, onEnd); + socket.once(event, removeListeners); + } +} + +/* It might still be useful to pick up errors due to invalid connect arguments. */ +function startGenericSpan(plugin: NetInstrumentation, socket: Socket) { + const span = plugin.tracer.startSpan('connect', { + kind: SpanKind.CLIENT, + }); + registerListeners(socket, span); +} + +function startIpcSpan(plugin: NetInstrumentation, options: IpcNetConnectOpts, socket: Socket) { + const span = plugin.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(plugin: NetInstrumentation, options: TcpSocketConnectOpts, socket: Socket) { + const span = plugin.tracer.startSpan('tcp.connect', { + kind: SpanKind.CLIENT, + attributes: { + [GeneralAttribute.NET_TRANSPORT]: 'IP.TCP', + [GeneralAttribute.NET_PEER_NAME]: options.host, + [GeneralAttribute.NET_PEER_PORT]: options.port, + }, + }); + + const addHostAttributes = () => { + span.setAttributes({ + [GeneralAttribute.NET_PEER_IP]: socket.remoteAddress, + [GeneralAttribute.NET_HOST_IP]: socket.localAddress, + [GeneralAttribute.NET_HOST_PORT]: socket.localPort, + }); + }; + + const onError = spanEndHandler(span); + const onEnd = spanEndHandler(span); + + const removeListeners = () => { + socket.removeListener('connect', addHostAttributes); + socket.removeListener('error', onError); + for (const event of SOCKET_EVENTS) { + socket.removeListener(event, onEnd); + socket.removeListener(event, removeListeners); + } + }; + + socket.once('connect', addHostAttributes); + + for (const event of SOCKET_EVENTS) { + socket.once(event, onEnd); + socket.once(event, removeListeners); + } + + return span; +} diff --git a/plugins/node/opentelemetry-instrumentation-net/src/types.ts b/plugins/node/opentelemetry-instrumentation-net/src/types.ts new file mode 100644 index 0000000000..f89b88debb --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/src/types.ts @@ -0,0 +1,25 @@ +/* + * 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'; +import { InstrumentationConfig } from '@opentelemetry/instrumentation'; + +export type Net = typeof net; + +export interface NetInstrumentationConfig extends InstrumentationConfig { +} + +export type ConnectCallbackSignature = () => void; diff --git a/plugins/node/opentelemetry-instrumentation-net/src/version.ts b/plugins/node/opentelemetry-instrumentation-net/src/version.ts new file mode 100644 index 0000000000..d15dc5d9ea --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/src/version.ts @@ -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.1.0'; diff --git a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts new file mode 100644 index 0000000000..1c6c8e5045 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts @@ -0,0 +1,221 @@ +/* + * 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 { context, SpanKind, SpanStatusCode } from '@opentelemetry/api'; +import { + InMemorySpanExporter, + ReadableSpan, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; +import * as assert from 'assert'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { NetInstrumentation } from '../src/net'; +import * as net from 'net'; +import * as os from 'os'; +import * as path from 'path'; + +const memoryExporter = new InMemorySpanExporter(); +const provider = new NodeTracerProvider(); +const tracer = provider.getTracer('default'); +provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +function assertClientSpan(span: ReadableSpan) { + assert.strictEqual(span.kind, SpanKind.CLIENT); +} + +function assertAttrib(span: ReadableSpan, attrib: string, value: any) { + assert.strictEqual(span.attributes[attrib], value); +} + +describe('NetInstrumentation', () => { + const PORT = 42123; + const HOST = 'localhost'; + const IPC_PATH = path.join(os.tmpdir(), 'otel-js-net-test-ipc'); + + function assertTcpSpan(span: ReadableSpan, socket: net.Socket) { + assertClientSpan(span); + assertAttrib(span, GeneralAttribute.NET_TRANSPORT, 'IP.TCP'); + assertAttrib(span, GeneralAttribute.NET_PEER_NAME, HOST); + assertAttrib(span, GeneralAttribute.NET_PEER_PORT, PORT); + assertAttrib(span, GeneralAttribute.NET_HOST_IP, socket.localAddress); + assertAttrib(span, GeneralAttribute.NET_HOST_PORT, socket.localPort); + } + + function assertIpcSpan(span: ReadableSpan) { + assertClientSpan(span); + assertAttrib(span, GeneralAttribute.NET_TRANSPORT, os.platform() == 'win32' ? 'pipe' : 'Unix'); + assertAttrib(span, GeneralAttribute.NET_PEER_NAME, IPC_PATH); + } + + function getSpan() { + const spans = memoryExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1); + const [span] = spans; + return span; + } + + let instrumentation: NetInstrumentation; + let socket: net.Socket; + let tcpServer: net.Server; + let ipcServer: net.Server; + + before(() => { + instrumentation = new NetInstrumentation(); + instrumentation.setTracerProvider(provider); + require('net'); + }); + + before((done) => { + tcpServer = net.createServer(); + tcpServer.listen(PORT, done); + }); + + before((done) => { + ipcServer = net.createServer(); + ipcServer.listen(IPC_PATH, done); + }); + + beforeEach(() => { + socket = new net.Socket(); + }); + + afterEach(() => { + socket.destroy(); + memoryExporter.reset(); + }); + + after(() => { + instrumentation.disable(); + tcpServer.close(); + ipcServer.close(); + }); + + describe('successful net.connect produces a span', () => { + it('should produce a span given port and host', done => { + socket = net.connect(PORT, HOST, () => { + assertTcpSpan(getSpan(), socket); + done(); + }); + }); + + it('should produce a span for IPC', done => { + socket = net.connect(IPC_PATH, () => { + assertIpcSpan(getSpan()); + done(); + }); + }); + + it('should produce a span given options', done => { + socket = net.connect({ + port: PORT, + host: 'localhost' + }, () => { + assertTcpSpan(getSpan(), socket); + done(); + }); + }); + }); + + describe('successful net.createConnection produces a span', () => { + it('should produce a span given port and host', done => { + socket = net.createConnection(PORT, HOST, () => { + assertTcpSpan(getSpan(), socket); + done(); + }); + }); + + it('should produce a span for IPC', done => { + socket = net.createConnection(IPC_PATH, () => { + assertIpcSpan(getSpan()); + done(); + }); + }); + + it('should produce a span given options', done => { + socket = net.createConnection({ + port: PORT, + host: 'localhost' + }, () => { + assertTcpSpan(getSpan(), socket); + done(); + }); + }); + }); + + describe('successful Socket.connect produces a span', () => { + it('should produce a span given port and host', done => { + socket.connect(PORT, HOST, () => { + assertTcpSpan(getSpan(), socket); + done(); + }); + }); + + it('should produce a span for IPC', done => { + socket.connect(IPC_PATH, () => { + assertIpcSpan(getSpan()); + done(); + }); + }); + + it('should produce a span given options', done => { + socket.connect({ + port: PORT, + host: 'localhost' + }, () => { + assertTcpSpan(getSpan(), socket); + done(); + }); + }); + }); + + describe('invalid input', () => { + it('should produce an error span when connect throws', done => { + + assert.throws(() => { + socket.connect({ port: {} }); + }); + + done(); + + assert.strictEqual(getSpan().status.code, SpanStatusCode.ERROR); + }); + + it('should produce a generic span in case transport type can not be determined', done => { + socket.once('close', () => { + let span = getSpan(); + assert.strictEqual(span.attributes[GeneralAttribute.NET_TRANSPORT], undefined); + assert.strictEqual(span.status.code, SpanStatusCode.ERROR); + done(); + }); + socket.connect(); + }); + }); + + describe('cleanup', () => { + it('should clean up listeners', done => { + socket.connect(PORT); + socket.destroy(); + socket.once('close', () => { + const events = new Set(socket.eventNames()); + for (const event of ['connect', 'timeout', 'error', 'close']) { + assert.equal(events.has(event), false); + } + done(); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts new file mode 100644 index 0000000000..35745a9745 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts @@ -0,0 +1,75 @@ +/* + * 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 { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { NetInstrumentation } from '../src/net'; +import * as Sinon from 'sinon'; +import * as net from 'net'; + +const memoryExporter = new InMemorySpanExporter(); +const provider = new NodeTracerProvider(); +const tracer = provider.getTracer('default'); +provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('NetInstrumentation', () => { + const PORT = 42123; + let instrumentation: NetInstrumentation; + let socket: net.Socket; + let tcpServer: net.Server; + + before(() => { + instrumentation = new NetInstrumentation(); + instrumentation.setTracerProvider(provider); + require('net'); + assert.strictEqual(net.Socket.prototype.connect.__wrapped, true); + }); + + before(done => { + tcpServer = net.createServer(); + tcpServer.listen(PORT, done); + }); + + after(() => { + tcpServer.close(); + }); + + beforeEach(() => { + Sinon.spy(tracer, 'startSpan'); + }); + + afterEach(() => { + socket.destroy(); + Sinon.restore(); + }); + + describe('disabling instrumentation', () => { + it('should not call tracer methods for creating span', done => { + instrumentation.disable(); + socket = net.connect(PORT, () => { + const spans = memoryExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 0); + assert.strictEqual(net.Socket.prototype.connect.__wrapped, undefined); + assert.strictEqual((tracer.startSpan as sinon.SinonSpy).called, false); + done(); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-net/tsconfig.json b/plugins/node/opentelemetry-instrumentation-net/tsconfig.json new file mode 100644 index 0000000000..28be80d266 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} From e749ae12a61889456d57819485d2b7395e124b4b Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 09:38:32 +0200 Subject: [PATCH 02/16] chore: fix linting issues --- .../src/index.ts | 16 ++++ .../src/net.ts | 63 ++++++++++------ .../src/types.ts | 6 -- .../test/connect.test.ts | 75 +++++++++++-------- 4 files changed, 100 insertions(+), 60 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/src/index.ts b/plugins/node/opentelemetry-instrumentation-net/src/index.ts index 10324a2fce..73e6a33eb9 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/index.ts @@ -1 +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'; diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts index fa6a746704..b3eb688dd5 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/net.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -14,19 +14,22 @@ * limitations under the License. */ -import { diag, Tracer, Span, SpanKind, SpanStatusCode } from '@opentelemetry/api'; +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 { - ConnectCallback, - Net, - NetInstrumentationConfig, -} from './types'; +import { Net } from './types'; import { VERSION } from './version'; import { platform } from 'os'; import { Socket, TcpSocketConnectOpts, IpcSocketConnectOpts } from 'net'; @@ -34,7 +37,7 @@ import { Socket, TcpSocketConnectOpts, IpcSocketConnectOpts } from 'net'; const IPC_TRANSPORT = platform() == 'win32' ? 'pipe' : 'Unix'; export class NetInstrumentation extends InstrumentationBase { - constructor(protected _config: NetInstrumentationConfig = {}) { + constructor(protected _config: InstrumentationConfig = {}) { super('@opentelemetry/instrumentation-net', VERSION, _config); } @@ -48,8 +51,11 @@ export class NetInstrumentation extends InstrumentationBase { if (isWrapped(moduleExports.Socket.prototype.connect)) { this._unwrap(moduleExports.Socket.prototype.connect, 'connect'); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this._wrap(moduleExports.Socket.prototype, 'connect', this._getPatchedConnect() as any); + this._wrap( + moduleExports.Socket.prototype, + 'connect', + this._getPatchedConnect() + ); return moduleExports; }, moduleExports => { @@ -64,18 +70,18 @@ export class NetInstrumentation extends InstrumentationBase { private _getPatchedConnect() { return (original: (...args: unknown[]) => void) => { const plugin = this; - return function patchedConnect( - ...args: unknown[] - ) { + return function patchedConnect(...args: unknown[]) { const options = normalizedArgs(args); if (!options) { - startGenericSpan(plugin, this); + startGenericSpan(plugin.tracer, this); return original.apply(this, args); } - const span = options.path ? startIpcSpan(plugin, options, this) : startTcpSpan(plugin, options, this); - + const span = options.path + ? startIpcSpan(plugin.tracer, options, this) + : startTcpSpan(plugin.tracer, options, this); + return safeExecuteInTheMiddle( () => original.apply(this, [...args]), error => { @@ -88,13 +94,14 @@ export class NetInstrumentation extends InstrumentationBase { } } ); - }; }; } } -function normalizedArgs(args: unknown[]): TcpSocketConnectOpts | IpcSocketConnectOpts | undefined { +function normalizedArgs( + args: unknown[] +): TcpSocketConnectOpts | IpcSocketConnectOpts | undefined { if (!args[0]) { return; } @@ -155,15 +162,19 @@ function registerListeners(socket: Socket, span: Span) { } /* It might still be useful to pick up errors due to invalid connect arguments. */ -function startGenericSpan(plugin: NetInstrumentation, socket: Socket) { - const span = plugin.tracer.startSpan('connect', { +function startGenericSpan(tracer: Tracer, socket: Socket) { + const span = tracer.startSpan('connect', { kind: SpanKind.CLIENT, }); registerListeners(socket, span); } -function startIpcSpan(plugin: NetInstrumentation, options: IpcNetConnectOpts, socket: Socket) { - const span = plugin.tracer.startSpan('ipc.connect', { +function startIpcSpan( + tracer: Tracer, + options: IpcNetConnectOpts, + socket: Socket +) { + const span = tracer.startSpan('ipc.connect', { kind: SpanKind.CLIENT, attributes: { [GeneralAttribute.NET_TRANSPORT]: IPC_TRANSPORT, @@ -171,13 +182,17 @@ function startIpcSpan(plugin: NetInstrumentation, options: IpcNetConnectOpts, so }, }); - registerListeners(socket, span); + registerListeners(socket, span); return span; } -function startTcpSpan(plugin: NetInstrumentation, options: TcpSocketConnectOpts, socket: Socket) { - const span = plugin.tracer.startSpan('tcp.connect', { +function startTcpSpan( + tracer: Tracer, + options: TcpSocketConnectOpts, + socket: Socket +) { + const span = tracer.startSpan('tcp.connect', { kind: SpanKind.CLIENT, attributes: { [GeneralAttribute.NET_TRANSPORT]: 'IP.TCP', diff --git a/plugins/node/opentelemetry-instrumentation-net/src/types.ts b/plugins/node/opentelemetry-instrumentation-net/src/types.ts index f89b88debb..fc75470075 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/types.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/types.ts @@ -15,11 +15,5 @@ */ import type * as net from 'net'; -import { InstrumentationConfig } from '@opentelemetry/instrumentation'; export type Net = typeof net; - -export interface NetInstrumentationConfig extends InstrumentationConfig { -} - -export type ConnectCallbackSignature = () => void; diff --git a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts index 1c6c8e5045..9c8a28bb19 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { context, SpanKind, SpanStatusCode } from '@opentelemetry/api'; +import { SpanKind, SpanStatusCode } from '@opentelemetry/api'; import { InMemorySpanExporter, ReadableSpan, @@ -57,7 +57,11 @@ describe('NetInstrumentation', () => { function assertIpcSpan(span: ReadableSpan) { assertClientSpan(span); - assertAttrib(span, GeneralAttribute.NET_TRANSPORT, os.platform() == 'win32' ? 'pipe' : 'Unix'); + assertAttrib( + span, + GeneralAttribute.NET_TRANSPORT, + os.platform() == 'win32' ? 'pipe' : 'Unix' + ); assertAttrib(span, GeneralAttribute.NET_PEER_NAME, IPC_PATH); } @@ -79,12 +83,12 @@ describe('NetInstrumentation', () => { require('net'); }); - before((done) => { + before(done => { tcpServer = net.createServer(); tcpServer.listen(PORT, done); }); - before((done) => { + before(done => { ipcServer = net.createServer(); ipcServer.listen(IPC_PATH, done); }); @@ -120,13 +124,16 @@ describe('NetInstrumentation', () => { }); it('should produce a span given options', done => { - socket = net.connect({ - port: PORT, - host: 'localhost' - }, () => { - assertTcpSpan(getSpan(), socket); - done(); - }); + socket = net.connect( + { + port: PORT, + host: 'localhost', + }, + () => { + assertTcpSpan(getSpan(), socket); + done(); + } + ); }); }); @@ -146,13 +153,16 @@ describe('NetInstrumentation', () => { }); it('should produce a span given options', done => { - socket = net.createConnection({ - port: PORT, - host: 'localhost' - }, () => { - assertTcpSpan(getSpan(), socket); - done(); - }); + socket = net.createConnection( + { + port: PORT, + host: 'localhost', + }, + () => { + assertTcpSpan(getSpan(), socket); + done(); + } + ); }); }); @@ -172,32 +182,37 @@ describe('NetInstrumentation', () => { }); it('should produce a span given options', done => { - socket.connect({ - port: PORT, - host: 'localhost' - }, () => { - assertTcpSpan(getSpan(), socket); - done(); - }); + socket.connect( + { + port: PORT, + host: 'localhost', + }, + () => { + assertTcpSpan(getSpan(), socket); + done(); + } + ); }); }); describe('invalid input', () => { it('should produce an error span when connect throws', done => { - assert.throws(() => { socket.connect({ port: {} }); }); - done(); - assert.strictEqual(getSpan().status.code, SpanStatusCode.ERROR); + + done(); }); it('should produce a generic span in case transport type can not be determined', done => { socket.once('close', () => { - let span = getSpan(); - assert.strictEqual(span.attributes[GeneralAttribute.NET_TRANSPORT], undefined); + const span = getSpan(); + assert.strictEqual( + span.attributes[GeneralAttribute.NET_TRANSPORT], + undefined + ); assert.strictEqual(span.status.code, SpanStatusCode.ERROR); done(); }); From 690b2b092f7e852d20a06f2c04d82de5182ecf1c Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 09:38:55 +0200 Subject: [PATCH 03/16] chore: more dotfiles --- plugins/node/opentelemetry-instrumentation-net/.eslintignore | 1 + plugins/node/opentelemetry-instrumentation-net/.npmignore | 4 ++++ 2 files changed, 5 insertions(+) create mode 100644 plugins/node/opentelemetry-instrumentation-net/.eslintignore create mode 100644 plugins/node/opentelemetry-instrumentation-net/.npmignore diff --git a/plugins/node/opentelemetry-instrumentation-net/.eslintignore b/plugins/node/opentelemetry-instrumentation-net/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-instrumentation-net/.npmignore b/plugins/node/opentelemetry-instrumentation-net/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test From f1995ef160dda26b6a1779806777c0f47a7aa07a Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 09:51:04 +0200 Subject: [PATCH 04/16] refactor: simplify registering of socket listeners --- .../src/net.ts | 57 +++++++++---------- 1 file changed, 27 insertions(+), 30 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts index b3eb688dd5..972aa22e34 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/net.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -141,22 +141,43 @@ function spanErrorHandler(span: Span) { }; } -function registerListeners(socket: Socket, span: Span) { +interface ListenerOpts { + hostAttributes?: boolean; +} + +function registerListeners( + socket: Socket, + span: Span, + { hostAttributes = false }: ListenerOpts = {} +) { const setSpanError = spanErrorHandler(span); - const onEnd = spanEndHandler(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, onEnd); + socket.removeListener(event, setSpanEnd); socket.removeListener(event, removeListeners); } }; for (const event of SOCKET_EVENTS) { - socket.once(event, onEnd); + socket.once(event, setSpanEnd); socket.once(event, removeListeners); } } @@ -166,6 +187,7 @@ function startGenericSpan(tracer: Tracer, socket: Socket) { const span = tracer.startSpan('connect', { kind: SpanKind.CLIENT, }); + registerListeners(socket, span); } @@ -201,32 +223,7 @@ function startTcpSpan( }, }); - const addHostAttributes = () => { - span.setAttributes({ - [GeneralAttribute.NET_PEER_IP]: socket.remoteAddress, - [GeneralAttribute.NET_HOST_IP]: socket.localAddress, - [GeneralAttribute.NET_HOST_PORT]: socket.localPort, - }); - }; - - const onError = spanEndHandler(span); - const onEnd = spanEndHandler(span); - - const removeListeners = () => { - socket.removeListener('connect', addHostAttributes); - socket.removeListener('error', onError); - for (const event of SOCKET_EVENTS) { - socket.removeListener(event, onEnd); - socket.removeListener(event, removeListeners); - } - }; - - socket.once('connect', addHostAttributes); - - for (const event of SOCKET_EVENTS) { - socket.once(event, onEnd); - socket.once(event, removeListeners); - } + registerListeners(socket, span, { hostAttributes: true }); return span; } From 37e65ab514212dda4d83c2cf2faae6d5035203e7 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 10:12:26 +0200 Subject: [PATCH 05/16] fix: remove timeout from listened socket events, add cleanup tests --- .../src/net.ts | 2 +- .../test/connect.test.ts | 31 ++++++++++++++++--- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts index 972aa22e34..288b8274c0 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/net.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -124,7 +124,7 @@ function normalizedArgs( } } -const SOCKET_EVENTS = ['connect', 'error', 'close', 'timeout']; +const SOCKET_EVENTS = ['connect', 'error', 'close']; function spanEndHandler(span: Span) { return () => { diff --git a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts index 9c8a28bb19..a5cdac1f26 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts @@ -221,16 +221,37 @@ describe('NetInstrumentation', () => { }); describe('cleanup', () => { - it('should clean up listeners', done => { + function assertNoDanglingListeners() { + const events = new Set(socket.eventNames()); + for (const event of ['connect', 'error', 'close']) { + assert.equal(events.has(event), false); + } + } + + it('should clean up listeners when destroying the socket', done => { socket.connect(PORT); socket.destroy(); socket.once('close', () => { - const events = new Set(socket.eventNames()); - for (const event of ['connect', 'timeout', 'error', 'close']) { - assert.equal(events.has(event), false); - } + assertNoDanglingListeners(); + done(); + }); + }); + + it('should clean up listeners when successfully connecting', done => { + socket.connect(PORT, () => { + assertNoDanglingListeners(); done(); }); }); + + it('should finish previous span when connecting twice', done => { + socket.connect(PORT, () => { + socket.connect(PORT, () => { + const spans = memoryExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 2); + done(); + }); + }); + }); }); }); From 4b019238cc5a0a986c50dd9dbd77a73e90fcd065 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 10:56:18 +0200 Subject: [PATCH 06/16] fix: compile --- .../src/net.ts | 42 +++++++++++-------- .../test/connect.test.ts | 6 +-- .../test/instrument.test.ts | 2 +- 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts index 288b8274c0..7ae5f306ea 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/net.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -32,7 +32,7 @@ import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; import { Net } from './types'; import { VERSION } from './version'; import { platform } from 'os'; -import { Socket, TcpSocketConnectOpts, IpcSocketConnectOpts } from 'net'; +import { Socket } from 'net'; const IPC_TRANSPORT = platform() == 'win32' ? 'pipe' : 'Unix'; @@ -49,12 +49,13 @@ export class NetInstrumentation extends InstrumentationBase { moduleExports => { diag.debug('Applying patch for net module'); if (isWrapped(moduleExports.Socket.prototype.connect)) { - this._unwrap(moduleExports.Socket.prototype.connect, 'connect'); + this._unwrap(moduleExports.Socket.prototype, 'connect'); } this._wrap( moduleExports.Socket.prototype, 'connect', - this._getPatchedConnect() + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._getPatchedConnect() as any ); return moduleExports; }, @@ -70,7 +71,7 @@ export class NetInstrumentation extends InstrumentationBase { private _getPatchedConnect() { return (original: (...args: unknown[]) => void) => { const plugin = this; - return function patchedConnect(...args: unknown[]) { + return function patchedConnect(this: Socket, ...args: unknown[]) { const options = normalizedArgs(args); if (!options) { @@ -83,7 +84,7 @@ export class NetInstrumentation extends InstrumentationBase { : startTcpSpan(plugin.tracer, options, this); return safeExecuteInTheMiddle( - () => original.apply(this, [...args]), + () => original.apply(this, args), error => { if (error !== undefined) { span.setStatus({ @@ -99,28 +100,35 @@ export class NetInstrumentation extends InstrumentationBase { } } -function normalizedArgs( - args: unknown[] -): TcpSocketConnectOpts | IpcSocketConnectOpts | undefined { - if (!args[0]) { +interface NormalizedOptions { + host?: string; + port?: number; + path?: string; +} + +function normalizedArgs(args: unknown[]): NormalizedOptions | null | undefined { + const opt = args[0]; + if (!opt) { return; } - switch (typeof args[0]) { + switch (typeof opt) { case 'number': return { - port: args[0], + port: opt, host: typeof args[1] === 'string' ? args[1] : 'localhost', }; case 'object': - if (Array.isArray(args[0])) { - return normalizedArgs(args[0]); + if (Array.isArray(opt)) { + return normalizedArgs(opt); } - return args[0]; + return opt; case 'string': return { - path: args[0], + path: opt, }; + default: + return; } } @@ -193,7 +201,7 @@ function startGenericSpan(tracer: Tracer, socket: Socket) { function startIpcSpan( tracer: Tracer, - options: IpcNetConnectOpts, + options: NormalizedOptions, socket: Socket ) { const span = tracer.startSpan('ipc.connect', { @@ -211,7 +219,7 @@ function startIpcSpan( function startTcpSpan( tracer: Tracer, - options: TcpSocketConnectOpts, + options: NormalizedOptions, socket: Socket ) { const span = tracer.startSpan('tcp.connect', { diff --git a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts index a5cdac1f26..fc76c7b158 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts @@ -30,7 +30,6 @@ import * as path from 'path'; const memoryExporter = new InMemorySpanExporter(); const provider = new NodeTracerProvider(); -const tracer = provider.getTracer('default'); provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); function assertClientSpan(span: ReadableSpan) { @@ -198,7 +197,8 @@ describe('NetInstrumentation', () => { describe('invalid input', () => { it('should produce an error span when connect throws', done => { assert.throws(() => { - socket.connect({ port: {} }); + // Invalid cast on purpose to avoid compiler errors. + socket.connect({ port: {} } as { port: number }); }); assert.strictEqual(getSpan().status.code, SpanStatusCode.ERROR); @@ -216,7 +216,7 @@ describe('NetInstrumentation', () => { assert.strictEqual(span.status.code, SpanStatusCode.ERROR); done(); }); - socket.connect(); + socket.connect((undefined as unknown) as string); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts index 35745a9745..7689a55d2e 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts @@ -63,7 +63,7 @@ describe('NetInstrumentation', () => { describe('disabling instrumentation', () => { it('should not call tracer methods for creating span', done => { instrumentation.disable(); - socket = net.connect(PORT, () => { + socket = net.connect(PORT, 'localhost', () => { const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 0); assert.strictEqual(net.Socket.prototype.connect.__wrapped, undefined); From 11984026c484fc140a1b0bd38496080151e22405 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 11:02:48 +0200 Subject: [PATCH 07/16] chore: remove unnecessary dependency --- plugins/node/opentelemetry-instrumentation-net/package.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/package.json b/plugins/node/opentelemetry-instrumentation-net/package.json index 90f43220c6..39cb6ab285 100644 --- a/plugins/node/opentelemetry-instrumentation-net/package.json +++ b/plugins/node/opentelemetry-instrumentation-net/package.json @@ -47,7 +47,6 @@ "@opentelemetry/tracing": "0.18.0", "@types/mocha": "7.0.2", "@types/node": "14.0.27", - "@types/semver": "7.3.1", "@types/shimmer": "1.0.1", "@types/sinon": "9.0.4", "codecov": "3.7.2", @@ -65,7 +64,6 @@ "dependencies": { "@opentelemetry/api": "^0.18.0", "@opentelemetry/instrumentation": "^0.18.0", - "@opentelemetry/semantic-conventions": "^0.18.0", - "semver": "^7.3.2" + "@opentelemetry/semantic-conventions": "^0.18.0" } } From ab4301fe3f5c2a9901d792f40cb0b679f05f07ef Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 12:50:43 +0200 Subject: [PATCH 08/16] chore: update node version --- plugins/node/opentelemetry-instrumentation-net/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/package.json b/plugins/node/opentelemetry-instrumentation-net/package.json index 39cb6ab285..d677dc06d0 100644 --- a/plugins/node/opentelemetry-instrumentation-net/package.json +++ b/plugins/node/opentelemetry-instrumentation-net/package.json @@ -29,7 +29,7 @@ "author": "OpenTelemetry Authors", "license": "Apache-2.0", "engines": { - "node": ">=8.0.0" + "node": ">=8.5.0" }, "files": [ "build/src/**/*.js", From 230ec9592215650aa0f1a42aa76fac13e1ebe11c Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 12:57:48 +0200 Subject: [PATCH 09/16] refactor: use isWrapped for wrap checks --- .../test/instrument.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts index 7689a55d2e..f70e9a8f5c 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts @@ -18,6 +18,7 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/tracing'; +import { isWrapped } from '@opentelemetry/instrumentation'; import * as assert from 'assert'; import { NodeTracerProvider } from '@opentelemetry/node'; import { NetInstrumentation } from '../src/net'; @@ -39,7 +40,7 @@ describe('NetInstrumentation', () => { instrumentation = new NetInstrumentation(); instrumentation.setTracerProvider(provider); require('net'); - assert.strictEqual(net.Socket.prototype.connect.__wrapped, true); + assert.strictEqual(isWrapped(net.Socket.prototype.connect), true); }); before(done => { @@ -66,7 +67,7 @@ describe('NetInstrumentation', () => { socket = net.connect(PORT, 'localhost', () => { const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 0); - assert.strictEqual(net.Socket.prototype.connect.__wrapped, undefined); + assert.strictEqual(isWrapped(net.Socket.prototype.connect), false); assert.strictEqual((tracer.startSpan as sinon.SinonSpy).called, false); done(); }); From e7918a38591f709386d16d0df9944331c2b0a5ae Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Wed, 17 Mar 2021 12:58:04 +0200 Subject: [PATCH 10/16] chore: change version, remove unused types, upgrade gts --- plugins/node/opentelemetry-instrumentation-net/package.json | 5 ++--- .../node/opentelemetry-instrumentation-net/src/version.ts | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/package.json b/plugins/node/opentelemetry-instrumentation-net/package.json index d677dc06d0..8fbbd44b2a 100644 --- a/plugins/node/opentelemetry-instrumentation-net/package.json +++ b/plugins/node/opentelemetry-instrumentation-net/package.json @@ -1,6 +1,6 @@ { "name": "@opentelemetry/instrumentation-net", - "version": "0.1.0", + "version": "0.14.0", "description": "OpenTelemetry net module automatic instrumentation package.", "main": "build/src/index.js", "types": "build/src/index.d.ts", @@ -47,10 +47,9 @@ "@opentelemetry/tracing": "0.18.0", "@types/mocha": "7.0.2", "@types/node": "14.0.27", - "@types/shimmer": "1.0.1", "@types/sinon": "9.0.4", "codecov": "3.7.2", - "gts": "2.0.2", + "gts": "3.1.0", "mocha": "7.2.0", "nyc": "15.1.0", "rimraf": "3.0.2", diff --git a/plugins/node/opentelemetry-instrumentation-net/src/version.ts b/plugins/node/opentelemetry-instrumentation-net/src/version.ts index d15dc5d9ea..bc552fd543 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/version.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/version.ts @@ -15,4 +15,4 @@ */ // this is autogenerated file, see scripts/version-update.js -export const VERSION = '0.1.0'; +export const VERSION = '0.14.0'; From 6e36db63f399fc02698b7bb6e4b70feab911dd59 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Thu, 18 Mar 2021 16:58:26 +0200 Subject: [PATCH 11/16] fix: use safeExecuteInTheMiddle for generic spans --- .../opentelemetry-instrumentation-net/src/net.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts index 7ae5f306ea..a8929be010 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/net.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -74,14 +74,11 @@ export class NetInstrumentation extends InstrumentationBase { return function patchedConnect(this: Socket, ...args: unknown[]) { const options = normalizedArgs(args); - if (!options) { - startGenericSpan(plugin.tracer, this); - return original.apply(this, args); - } - - const span = options.path - ? startIpcSpan(plugin.tracer, options, this) - : startTcpSpan(plugin.tracer, options, this); + 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), @@ -197,6 +194,8 @@ function startGenericSpan(tracer: Tracer, socket: Socket) { }); registerListeners(socket, span); + + return span; } function startIpcSpan( From 3b9a403e248aca86afd72cd0d27c6e321e8f9dd3 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Thu, 18 Mar 2021 18:31:54 +0200 Subject: [PATCH 12/16] refactor: better encapsulation --- .../src/net.ts | 152 ++++++------------ .../src/types.ts | 12 ++ .../src/utils.ts | 50 ++++++ .../test/connect.test.ts | 68 +++----- .../test/instrument.test.ts | 4 +- .../test/utils.ts | 51 ++++++ 6 files changed, 187 insertions(+), 150 deletions(-) create mode 100644 plugins/node/opentelemetry-instrumentation-net/src/utils.ts create mode 100644 plugins/node/opentelemetry-instrumentation-net/test/utils.ts diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts index a8929be010..95de103ef6 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/net.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -14,13 +14,7 @@ * limitations under the License. */ -import { - diag, - Tracer, - Span, - SpanKind, - SpanStatusCode, -} from '@opentelemetry/api'; +import { diag, Span, SpanKind, SpanStatusCode } from '@opentelemetry/api'; import { InstrumentationBase, InstrumentationConfig, @@ -29,13 +23,11 @@ import { safeExecuteInTheMiddle, } from '@opentelemetry/instrumentation'; import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; -import { Net } from './types'; +import { Net, NormalizedOptions, SocketEvent } from './types'; +import { getNormalizedArgs, IPC_TRANSPORT } from './utils'; import { VERSION } from './version'; -import { platform } from 'os'; import { Socket } from 'net'; -const IPC_TRANSPORT = platform() == 'win32' ? 'pipe' : 'Unix'; - export class NetInstrumentation extends InstrumentationBase { constructor(protected _config: InstrumentationConfig = {}) { super('@opentelemetry/instrumentation-net', VERSION, _config); @@ -72,13 +64,13 @@ export class NetInstrumentation extends InstrumentationBase { return (original: (...args: unknown[]) => void) => { const plugin = this; return function patchedConnect(this: Socket, ...args: unknown[]) { - const options = normalizedArgs(args); + const options = getNormalizedArgs(args); const span = options ? options.path - ? startIpcSpan(plugin.tracer, options, this) - : startTcpSpan(plugin.tracer, options, this) - : startGenericSpan(plugin.tracer, this); + ? plugin._startIpcSpan(options, this) + : plugin._startTcpSpan(options, this) + : plugin._startGenericSpan(this); return safeExecuteInTheMiddle( () => original.apply(this, args), @@ -95,41 +87,53 @@ export class NetInstrumentation extends InstrumentationBase { }; }; } -} -interface NormalizedOptions { - host?: string; - port?: number; - path?: string; -} + /* It might still be useful to pick up errors due to invalid connect arguments. */ + private _startGenericSpan(socket: Socket) { + const span = this.tracer.startSpan('connect', { + kind: SpanKind.CLIENT, + }); + + registerListeners(socket, span); -function normalizedArgs(args: unknown[]): NormalizedOptions | null | undefined { - const opt = args[0]; - if (!opt) { - return; + return span; } - 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; + private _startIpcSpan(options: NormalizedOptions, socket: Socket) { + const span = this.tracer.startSpan('ipc.connect', { + kind: SpanKind.CLIENT, + attributes: { + [GeneralAttribute.NET_TRANSPORT]: IPC_TRANSPORT, + [GeneralAttribute.NET_PEER_NAME]: options.path, + }, + }); + + registerListeners(socket, span); + + return span; + } + + private _startTcpSpan(options: NormalizedOptions, socket: Socket) { + const span = this.tracer.startSpan('tcp.connect', { + kind: SpanKind.CLIENT, + attributes: { + [GeneralAttribute.NET_TRANSPORT]: GeneralAttribute.IP_TCP, + [GeneralAttribute.NET_PEER_NAME]: options.host, + [GeneralAttribute.NET_PEER_PORT]: options.port, + }, + }); + + registerListeners(socket, span, { hostAttributes: true }); + + return span; } } -const SOCKET_EVENTS = ['connect', 'error', 'close']; +const SOCKET_EVENTS = [ + SocketEvent.CLOSE, + SocketEvent.CONNECT, + SocketEvent.ERROR, +]; function spanEndHandler(span: Span) { return () => { @@ -146,14 +150,10 @@ function spanErrorHandler(span: Span) { }; } -interface ListenerOpts { - hostAttributes?: boolean; -} - function registerListeners( socket: Socket, span: Span, - { hostAttributes = false }: ListenerOpts = {} + { hostAttributes = false }: { hostAttributes?: boolean } = {} ) { const setSpanError = spanErrorHandler(span); const setSpanEnd = spanEndHandler(span); @@ -166,15 +166,15 @@ function registerListeners( }); }; - socket.once('error', setSpanError); + socket.once(SocketEvent.ERROR, setSpanError); if (hostAttributes) { - socket.once('connect', setHostAttributes); + socket.once(SocketEvent.CONNECT, setHostAttributes); } const removeListeners = () => { - socket.removeListener('error', setSpanError); - socket.removeListener('connect', setHostAttributes); + socket.removeListener(SocketEvent.ERROR, setSpanError); + socket.removeListener(SocketEvent.CONNECT, setHostAttributes); for (const event of SOCKET_EVENTS) { socket.removeListener(event, setSpanEnd); socket.removeListener(event, removeListeners); @@ -186,51 +186,3 @@ function registerListeners( 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', - [GeneralAttribute.NET_PEER_NAME]: options.host, - [GeneralAttribute.NET_PEER_PORT]: options.port, - }, - }); - - registerListeners(socket, span, { hostAttributes: true }); - - return span; -} diff --git a/plugins/node/opentelemetry-instrumentation-net/src/types.ts b/plugins/node/opentelemetry-instrumentation-net/src/types.ts index fc75470075..f767252dcf 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/types.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/types.ts @@ -17,3 +17,15 @@ import type * as net from 'net'; export type Net = typeof net; + +export interface NormalizedOptions { + host?: string; + port?: number; + path?: string; +} + +export enum SocketEvent { + CLOSE = 'close', + CONNECT = 'connect', + ERROR = 'error', +} diff --git a/plugins/node/opentelemetry-instrumentation-net/src/utils.ts b/plugins/node/opentelemetry-instrumentation-net/src/utils.ts new file mode 100644 index 0000000000..849184da2d --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/src/utils.ts @@ -0,0 +1,50 @@ +/* + * 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 { NormalizedOptions } from './types'; +import { platform } from 'os'; + +export const IPC_PIPE = 'pipe'; +export const IPC_UNIX = 'Unix'; +export const IPC_TRANSPORT = platform() === 'win32' ? IPC_PIPE : IPC_UNIX; + +export function getNormalizedArgs( + args: unknown[] +): NormalizedOptions | null | undefined { + 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 getNormalizedArgs(opt); + } + return opt; + case 'string': + return { + path: opt, + }; + default: + return; + } +} diff --git a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts index fc76c7b158..b97672c191 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts @@ -14,63 +14,31 @@ * limitations under the License. */ -import { SpanKind, SpanStatusCode } from '@opentelemetry/api'; +import { SpanStatusCode } from '@opentelemetry/api'; import { InMemorySpanExporter, - ReadableSpan, SimpleSpanProcessor, } from '@opentelemetry/tracing'; import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; -import * as assert from 'assert'; import { NodeTracerProvider } from '@opentelemetry/node'; -import { NetInstrumentation } from '../src/net'; import * as net from 'net'; -import * as os from 'os'; -import * as path from 'path'; +import * as assert from 'assert'; +import { NetInstrumentation } from '../src/net'; +import { SocketEvent } from '../src/types'; +import { assertIpcSpan, assertTcpSpan, IPC_PATH, HOST, PORT } from './utils'; const memoryExporter = new InMemorySpanExporter(); const provider = new NodeTracerProvider(); provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); -function assertClientSpan(span: ReadableSpan) { - assert.strictEqual(span.kind, SpanKind.CLIENT); -} - -function assertAttrib(span: ReadableSpan, attrib: string, value: any) { - assert.strictEqual(span.attributes[attrib], value); +function getSpan() { + const spans = memoryExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1); + const [span] = spans; + return span; } describe('NetInstrumentation', () => { - const PORT = 42123; - const HOST = 'localhost'; - const IPC_PATH = path.join(os.tmpdir(), 'otel-js-net-test-ipc'); - - function assertTcpSpan(span: ReadableSpan, socket: net.Socket) { - assertClientSpan(span); - assertAttrib(span, GeneralAttribute.NET_TRANSPORT, 'IP.TCP'); - assertAttrib(span, GeneralAttribute.NET_PEER_NAME, HOST); - assertAttrib(span, GeneralAttribute.NET_PEER_PORT, PORT); - assertAttrib(span, GeneralAttribute.NET_HOST_IP, socket.localAddress); - assertAttrib(span, GeneralAttribute.NET_HOST_PORT, socket.localPort); - } - - function assertIpcSpan(span: ReadableSpan) { - assertClientSpan(span); - assertAttrib( - span, - GeneralAttribute.NET_TRANSPORT, - os.platform() == 'win32' ? 'pipe' : 'Unix' - ); - assertAttrib(span, GeneralAttribute.NET_PEER_NAME, IPC_PATH); - } - - function getSpan() { - const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1); - const [span] = spans; - return span; - } - let instrumentation: NetInstrumentation; let socket: net.Socket; let tcpServer: net.Server; @@ -126,7 +94,7 @@ describe('NetInstrumentation', () => { socket = net.connect( { port: PORT, - host: 'localhost', + host: HOST, }, () => { assertTcpSpan(getSpan(), socket); @@ -155,7 +123,7 @@ describe('NetInstrumentation', () => { socket = net.createConnection( { port: PORT, - host: 'localhost', + host: HOST, }, () => { assertTcpSpan(getSpan(), socket); @@ -184,7 +152,7 @@ describe('NetInstrumentation', () => { socket.connect( { port: PORT, - host: 'localhost', + host: HOST, }, () => { assertTcpSpan(getSpan(), socket); @@ -207,7 +175,7 @@ describe('NetInstrumentation', () => { }); it('should produce a generic span in case transport type can not be determined', done => { - socket.once('close', () => { + socket.once(SocketEvent.CLOSE, () => { const span = getSpan(); assert.strictEqual( span.attributes[GeneralAttribute.NET_TRANSPORT], @@ -223,7 +191,11 @@ describe('NetInstrumentation', () => { describe('cleanup', () => { function assertNoDanglingListeners() { const events = new Set(socket.eventNames()); - for (const event of ['connect', 'error', 'close']) { + for (const event of [ + SocketEvent.CLOSE, + SocketEvent.CONNECT, + SocketEvent.ERROR, + ]) { assert.equal(events.has(event), false); } } @@ -231,7 +203,7 @@ describe('NetInstrumentation', () => { it('should clean up listeners when destroying the socket', done => { socket.connect(PORT); socket.destroy(); - socket.once('close', () => { + socket.once(SocketEvent.CLOSE, () => { assertNoDanglingListeners(); done(); }); diff --git a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts index f70e9a8f5c..53f3490582 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts @@ -24,6 +24,7 @@ import { NodeTracerProvider } from '@opentelemetry/node'; import { NetInstrumentation } from '../src/net'; import * as Sinon from 'sinon'; import * as net from 'net'; +import { HOST, PORT } from './utils'; const memoryExporter = new InMemorySpanExporter(); const provider = new NodeTracerProvider(); @@ -31,7 +32,6 @@ const tracer = provider.getTracer('default'); provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); describe('NetInstrumentation', () => { - const PORT = 42123; let instrumentation: NetInstrumentation; let socket: net.Socket; let tcpServer: net.Server; @@ -64,7 +64,7 @@ describe('NetInstrumentation', () => { describe('disabling instrumentation', () => { it('should not call tracer methods for creating span', done => { instrumentation.disable(); - socket = net.connect(PORT, 'localhost', () => { + socket = net.connect(PORT, HOST, () => { const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 0); assert.strictEqual(isWrapped(net.Socket.prototype.connect), false); diff --git a/plugins/node/opentelemetry-instrumentation-net/test/utils.ts b/plugins/node/opentelemetry-instrumentation-net/test/utils.ts new file mode 100644 index 0000000000..1da53a4a0d --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/test/utils.ts @@ -0,0 +1,51 @@ +/* + * 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 { SpanKind } from '@opentelemetry/api'; +import { ReadableSpan } from '@opentelemetry/tracing'; +import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; +import * as assert from 'assert'; +import * as path from 'path'; +import * as os from 'os'; +import { Socket } from 'net'; +import { IPC_TRANSPORT } from '../src/utils'; + +export const PORT = 42123; +export const HOST = 'localhost'; +export const IPC_PATH = path.join(os.tmpdir(), 'otel-js-net-test-ipc'); + +export function assertTcpSpan(span: ReadableSpan, socket: Socket) { + assertClientSpan(span); + assertAttrib(span, GeneralAttribute.NET_TRANSPORT, GeneralAttribute.IP_TCP); + assertAttrib(span, GeneralAttribute.NET_PEER_NAME, HOST); + assertAttrib(span, GeneralAttribute.NET_PEER_PORT, PORT); + assertAttrib(span, GeneralAttribute.NET_HOST_IP, socket.localAddress); + assertAttrib(span, GeneralAttribute.NET_HOST_PORT, socket.localPort); +} + +export function assertIpcSpan(span: ReadableSpan) { + assertClientSpan(span); + assertAttrib(span, GeneralAttribute.NET_TRANSPORT, IPC_TRANSPORT); + assertAttrib(span, GeneralAttribute.NET_PEER_NAME, IPC_PATH); +} + +export function assertClientSpan(span: ReadableSpan) { + assert.strictEqual(span.kind, SpanKind.CLIENT); +} + +export function assertAttrib(span: ReadableSpan, attrib: string, value: any) { + assert.strictEqual(span.attributes[attrib], value); +} From 56f7e95192c68be432d27bdc10e8564d9382c1f5 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Thu, 18 Mar 2021 18:35:59 +0200 Subject: [PATCH 13/16] feat: record exceptions for failed spans --- plugins/node/opentelemetry-instrumentation-net/src/net.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/node/opentelemetry-instrumentation-net/src/net.ts b/plugins/node/opentelemetry-instrumentation-net/src/net.ts index 95de103ef6..763d6e5142 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/net.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts @@ -80,6 +80,7 @@ export class NetInstrumentation extends InstrumentationBase { code: SpanStatusCode.ERROR, message: error.message, }); + span.recordException(error); span.end(); } } From ac287749eb686eb9aac8455866f87deb7c7487f1 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Thu, 18 Mar 2021 18:38:34 +0200 Subject: [PATCH 14/16] chore: add a TODO comment regarding IPC semantic convetions --- plugins/node/opentelemetry-instrumentation-net/src/utils.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/node/opentelemetry-instrumentation-net/src/utils.ts b/plugins/node/opentelemetry-instrumentation-net/src/utils.ts index 849184da2d..4f77d29a0e 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/utils.ts @@ -17,6 +17,7 @@ import { NormalizedOptions } from './types'; import { platform } from 'os'; +// @TODO Can be replaced with constants from the semantic conventions package once released. export const IPC_PIPE = 'pipe'; export const IPC_UNIX = 'Unix'; export const IPC_TRANSPORT = platform() === 'win32' ? IPC_PIPE : IPC_UNIX; From c0c238630ecb140b79d8ed183ebdfeb92389267a Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Fri, 19 Mar 2021 10:22:32 +0200 Subject: [PATCH 15/16] chore: add license --- .../opentelemetry-instrumentation-net/LICENSE | 201 ++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 plugins/node/opentelemetry-instrumentation-net/LICENSE diff --git a/plugins/node/opentelemetry-instrumentation-net/LICENSE b/plugins/node/opentelemetry-instrumentation-net/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. From 1b2b3a09f0cda907f0a3502819214f0e18a40cf4 Mon Sep 17 00:00:00 2001 From: Siim Kallas Date: Fri, 19 Mar 2021 10:44:51 +0200 Subject: [PATCH 16/16] chore: add README --- .../README.md | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 plugins/node/opentelemetry-instrumentation-net/README.md diff --git a/plugins/node/opentelemetry-instrumentation-net/README.md b/plugins/node/opentelemetry-instrumentation-net/README.md new file mode 100644 index 0000000000..73ed07c3f5 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-net/README.md @@ -0,0 +1,64 @@ +# OpenTelemetry Net module Instrumentation for Node.js + +[![Gitter chat][gitter-image]][gitter-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +This module provides instrumentation of outgoing connections for [`net`](http://nodejs.org/dist/latest/docs/api/net.html). +Supports both TCP and IPC connections. + +## Installation + +```bash +npm install --save @opentelemetry/instrumentation-net +``` + +## Usage + +```js +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { NetInstrumentation } = require('@opentelemetry/instrumentation-net'); +const { registerInstrumentations } = require('@opentelemetry/instrumentation'); + +const provider = new NodeTracerProvider(); +provider.register(); + +registerInstrumentations({ + instrumentations: [ + new NetInstrumentation(), + // other instrumentations + ], + tracerProvider: provider, +}); +``` + +### Attributes added to `connect` spans + +* `net.transport`: `IP.TCP`, `pipe` or `Unix` +* `net.peer.name`: host name or the IPC file path + +For TCP: +* `net.peer.ip` +* `net.peer.port` +* `net.host.ip` +* `net.host.port` + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us on [gitter][gitter-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js-contrib.svg +[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/status.svg?path=packages/opentelemetry-instrumentation-net +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-net +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=packages/opentelemetry-instrumentation-net +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-net&type=dev