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/.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/.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
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.
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
diff --git a/plugins/node/opentelemetry-instrumentation-net/package.json b/plugins/node/opentelemetry-instrumentation-net/package.json
new file mode 100644
index 0000000000..8fbbd44b2a
--- /dev/null
+++ b/plugins/node/opentelemetry-instrumentation-net/package.json
@@ -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"
+ }
+}
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..73e6a33eb9
--- /dev/null
+++ b/plugins/node/opentelemetry-instrumentation-net/src/index.ts
@@ -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';
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..763d6e5142
--- /dev/null
+++ b/plugins/node/opentelemetry-instrumentation-net/src/net.ts
@@ -0,0 +1,189 @@
+/*
+ * 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, Span, SpanKind, SpanStatusCode } from '@opentelemetry/api';
+import {
+ InstrumentationBase,
+ InstrumentationConfig,
+ InstrumentationNodeModuleDefinition,
+ isWrapped,
+ safeExecuteInTheMiddle,
+} from '@opentelemetry/instrumentation';
+import { GeneralAttribute } from '@opentelemetry/semantic-conventions';
+import { Net, NormalizedOptions, SocketEvent } from './types';
+import { getNormalizedArgs, IPC_TRANSPORT } from './utils';
+import { VERSION } from './version';
+import { Socket } from 'net';
+
+export class NetInstrumentation extends InstrumentationBase {
+ constructor(protected _config: InstrumentationConfig = {}) {
+ 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');
+ }
+ 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 = getNormalizedArgs(args);
+
+ const span = options
+ ? options.path
+ ? plugin._startIpcSpan(options, this)
+ : plugin._startTcpSpan(options, this)
+ : plugin._startGenericSpan(this);
+
+ return safeExecuteInTheMiddle(
+ () => original.apply(this, args),
+ error => {
+ if (error !== undefined) {
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error.message,
+ });
+ span.recordException(error);
+ span.end();
+ }
+ }
+ );
+ };
+ };
+ }
+
+ /* 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);
+
+ return span;
+ }
+
+ 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 = [
+ SocketEvent.CLOSE,
+ SocketEvent.CONNECT,
+ SocketEvent.ERROR,
+];
+
+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,
+ { hostAttributes = false }: { hostAttributes?: boolean } = {}
+) {
+ 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(SocketEvent.ERROR, setSpanError);
+
+ if (hostAttributes) {
+ socket.once(SocketEvent.CONNECT, setHostAttributes);
+ }
+
+ const removeListeners = () => {
+ socket.removeListener(SocketEvent.ERROR, setSpanError);
+ socket.removeListener(SocketEvent.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);
+ }
+}
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..f767252dcf
--- /dev/null
+++ b/plugins/node/opentelemetry-instrumentation-net/src/types.ts
@@ -0,0 +1,31 @@
+/*
+ * 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;
+
+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..4f77d29a0e
--- /dev/null
+++ b/plugins/node/opentelemetry-instrumentation-net/src/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 { 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;
+
+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/src/version.ts b/plugins/node/opentelemetry-instrumentation-net/src/version.ts
new file mode 100644
index 0000000000..bc552fd543
--- /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.14.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..b97672c191
--- /dev/null
+++ b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts
@@ -0,0 +1,229 @@
+/*
+ * 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 { SpanStatusCode } from '@opentelemetry/api';
+import {
+ InMemorySpanExporter,
+ SimpleSpanProcessor,
+} from '@opentelemetry/tracing';
+import { GeneralAttribute } from '@opentelemetry/semantic-conventions';
+import { NodeTracerProvider } from '@opentelemetry/node';
+import * as net from 'net';
+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 getSpan() {
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ const [span] = spans;
+ return span;
+}
+
+describe('NetInstrumentation', () => {
+ 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: HOST,
+ },
+ () => {
+ 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: HOST,
+ },
+ () => {
+ 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: HOST,
+ },
+ () => {
+ assertTcpSpan(getSpan(), socket);
+ done();
+ }
+ );
+ });
+ });
+
+ describe('invalid input', () => {
+ it('should produce an error span when connect throws', done => {
+ assert.throws(() => {
+ // Invalid cast on purpose to avoid compiler errors.
+ socket.connect({ port: {} } as { port: number });
+ });
+
+ 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(SocketEvent.CLOSE, () => {
+ const span = getSpan();
+ assert.strictEqual(
+ span.attributes[GeneralAttribute.NET_TRANSPORT],
+ undefined
+ );
+ assert.strictEqual(span.status.code, SpanStatusCode.ERROR);
+ done();
+ });
+ socket.connect((undefined as unknown) as string);
+ });
+ });
+
+ describe('cleanup', () => {
+ function assertNoDanglingListeners() {
+ const events = new Set(socket.eventNames());
+ for (const event of [
+ SocketEvent.CLOSE,
+ SocketEvent.CONNECT,
+ SocketEvent.ERROR,
+ ]) {
+ assert.equal(events.has(event), false);
+ }
+ }
+
+ it('should clean up listeners when destroying the socket', done => {
+ socket.connect(PORT);
+ socket.destroy();
+ socket.once(SocketEvent.CLOSE, () => {
+ 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();
+ });
+ });
+ });
+ });
+});
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..53f3490582
--- /dev/null
+++ b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts
@@ -0,0 +1,76 @@
+/*
+ * 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 { isWrapped } from '@opentelemetry/instrumentation';
+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';
+import { HOST, PORT } from './utils';
+
+const memoryExporter = new InMemorySpanExporter();
+const provider = new NodeTracerProvider();
+const tracer = provider.getTracer('default');
+provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter));
+
+describe('NetInstrumentation', () => {
+ let instrumentation: NetInstrumentation;
+ let socket: net.Socket;
+ let tcpServer: net.Server;
+
+ before(() => {
+ instrumentation = new NetInstrumentation();
+ instrumentation.setTracerProvider(provider);
+ require('net');
+ assert.strictEqual(isWrapped(net.Socket.prototype.connect), 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, HOST, () => {
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 0);
+ assert.strictEqual(isWrapped(net.Socket.prototype.connect), false);
+ assert.strictEqual((tracer.startSpan as sinon.SinonSpy).called, false);
+ done();
+ });
+ });
+ });
+});
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);
+}
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"
+ ]
+}