From c39e595ad7714bd20e9b50bb0016bbd2b3849f71 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Tue, 12 Jan 2021 19:57:02 +0100 Subject: [PATCH 1/8] feat: add instrumentation-dns port plugin-dns to instrumenation API because the plugin API will be removed from OTel. --- .../.eslintignore | 1 + .../.eslintrc.js | 7 + .../.npmignore | 4 + .../opentelemetry-instrumentation-dns/LICENSE | 201 +++++++++++++++ .../README.md | 72 ++++++ .../package.json | 69 ++++++ .../src/dns.ts | 217 +++++++++++++++++ .../src/enums/AddressFamily.ts | 21 ++ .../src/enums/AttributeNames.ts | 25 ++ .../src/index.ts | 18 ++ .../src/types.ts | 100 ++++++++ .../src/utils.ts | 156 ++++++++++++ .../src/version.ts | 18 ++ .../test/functionals/dns-disable.test.ts | 69 ++++++ .../test/functionals/utils.test.ts | 171 +++++++++++++ .../test/integrations/dns-lookup.test.ts | 221 +++++++++++++++++ .../integrations/dnspromise-lookup.test.ts | 228 ++++++++++++++++++ .../test/utils/assertSpan.ts | 72 ++++++ .../test/utils/utils.ts | 27 +++ .../tsconfig.json | 11 + 20 files changed, 1708 insertions(+) create mode 100644 plugins/node/opentelemetry-instrumentation-dns/.eslintignore create mode 100644 plugins/node/opentelemetry-instrumentation-dns/.eslintrc.js create mode 100644 plugins/node/opentelemetry-instrumentation-dns/.npmignore create mode 100644 plugins/node/opentelemetry-instrumentation-dns/LICENSE create mode 100644 plugins/node/opentelemetry-instrumentation-dns/README.md create mode 100644 plugins/node/opentelemetry-instrumentation-dns/package.json create mode 100644 plugins/node/opentelemetry-instrumentation-dns/src/dns.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/src/enums/AddressFamily.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/src/index.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/src/types.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/src/utils.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/src/version.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts create mode 100644 plugins/node/opentelemetry-instrumentation-dns/tsconfig.json diff --git a/plugins/node/opentelemetry-instrumentation-dns/.eslintignore b/plugins/node/opentelemetry-instrumentation-dns/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-instrumentation-dns/.eslintrc.js b/plugins/node/opentelemetry-instrumentation-dns/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-instrumentation-dns/.npmignore b/plugins/node/opentelemetry-instrumentation-dns/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/opentelemetry-instrumentation-dns/LICENSE b/plugins/node/opentelemetry-instrumentation-dns/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/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-dns/README.md b/plugins/node/opentelemetry-instrumentation-dns/README.md new file mode 100644 index 0000000000..3708d2d893 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/README.md @@ -0,0 +1,72 @@ +# OpenTelemetry DNS 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 automatic instrumentation for [`dns`](http://nodejs.org/dist/latest/docs/api/dns.html). + +For automatic instrumentation see the +[@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-node) package. + +## Installation + +```bash +npm install --save @opentelemetry/instrumentation-dns +``` + +## Usage + +```js +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { DnsInstrumentation } = require('@opentelemetry/instrumentation-dns'); + +const provider = new NodeTracerProvider({ + // be sure to disable old plugin + plugins: { + dns: { enabled: false, path: '@opentelemetry/plugin-dns' } + } +}); + +const dnsInstrumentation = new DnsInstrumentation({ + // see under for available configuration +}); +``` + +### Zipkin + +If you use Zipkin, you must use `ignoreHostnames` in order to not trace those calls. If the server is local. You can set: + +```js +const dnsInstrumentation = new DnsInstrumentation({ + ignoreHostnames: ['localhost'] +}); +``` + +### Dns Instrumentation Options + +Dns instrumentation has currently one option. You can set the following: + +| Options | Type | Description | +| ------- | ---- | ----------- | +| [`ignoreHostnames`](https://github.com/open-telemetry/opentelemetry-js/blob/master/packages/opentelemetry-instrumentation-dns/src/types.ts#L98) | `IgnoreMatcher[]` | Dns instrumentation will not trace all requests that match hostnames | + +## 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.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/blob/master/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/status.svg?path=packages/opentelemetry-instrumentation-dns +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-dns +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-instrumentation-dns +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-dns&type=dev diff --git a/plugins/node/opentelemetry-instrumentation-dns/package.json b/plugins/node/opentelemetry-instrumentation-dns/package.json new file mode 100644 index 0000000000..9aa9579ce2 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/package.json @@ -0,0 +1,69 @@ +{ + "name": "@opentelemetry/instrumentation-dns", + "version": "0.12.0", + "description": "OpenTelemetry dns automatic instrumentation package.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "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", + "dns", + "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.14.0", + "@opentelemetry/node": "^0.14.0", + "@opentelemetry/tracing": "^0.14.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": "3.9.7" + }, + "dependencies": { + "@opentelemetry/api": "^0.14.0", + "@opentelemetry/instrumentation": "^0.14.0", + "semver": "^7.3.2" + } +} diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts b/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts new file mode 100644 index 0000000000..e46ef3953e --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/src/dns.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 { LookupAddress } from 'dns'; +import { Span, SpanKind, SpanOptions } from '@opentelemetry/api'; +import { + InstrumentationBase, + InstrumentationConfig, + InstrumentationNodeModuleDefinition, + isWrapped, +} from '@opentelemetry/instrumentation'; +import * as semver from 'semver'; +import { AddressFamily } from './enums/AddressFamily'; +import { AttributeNames } from './enums/AttributeNames'; +import { + Dns, + DnsInstrumentationConfig, + LookupCallbackSignature, + LookupFunctionSignature, + LookupPromiseSignature, +} from './types'; +import * as utils from './utils'; +import { VERSION } from './version'; + +/** + * Dns instrumentation for Opentelemetry + */ +export class DnsInstrumentation extends InstrumentationBase { + constructor(protected _config: DnsInstrumentationConfig = {}) { + super('@opentelemetry/instrumentation-dns', VERSION, _config); + } + + public setConfig( + config: DnsInstrumentationConfig & InstrumentationConfig = {} + ) { + this._config = Object.assign({}, config); + } + + init(): InstrumentationNodeModuleDefinition[] { + return [ + new InstrumentationNodeModuleDefinition( + 'dns', + ['*'], + moduleExports => { + this._logger.debug('Applying patch for dns'); + if (isWrapped(moduleExports.lookup)) { + this._unwrap(moduleExports, 'lookup'); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._wrap(moduleExports, 'lookup', this._getLookup() as any); + // new promise methods in node >= 10.6.0 + // https://nodejs.org/docs/latest/api/dns.html#dns_dnspromises_lookup_hostname_options + if (semver.gte(process.version, '10.6.0')) { + this._wrap( + moduleExports.promises, + 'lookup', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._getLookup() as any + ); + } + return moduleExports; + }, + moduleExports => { + if (moduleExports === undefined) return; + this._logger.debug('Removing patch for dns'); + this._unwrap(moduleExports, 'lookup'); + if (semver.gte(process.version, '10.6.0')) { + this._unwrap(moduleExports.promises, 'lookup'); + } + } + ), + ]; + } + + /** + * Get the patched lookup function + */ + private _getLookup() { + return (original: (hostname: string, ...args: unknown[]) => void) => { + return this._getPatchLookupFunction(original); + }; + } + + /** + * Creates spans for lookup operations, restoring spans' context if applied. + */ + private _getPatchLookupFunction( + original: (hostname: string, ...args: unknown[]) => void + ) { + this._logger.debug('patch lookup function'); + const plugin = this; + return function patchedLookup( + this: {}, + hostname: string, + ...args: unknown[] + ) { + if ( + utils.isIgnored(hostname, plugin._config.ignoreHostnames, (e: Error) => + plugin._logger.error('caught ignoreHostname error: ', e) + ) + ) { + return original.apply(this, [hostname, ...args]); + } + + const argsCount = args.length; + plugin._logger.debug('wrap lookup callback function and starts span'); + const name = utils.getOperationName('lookup'); + const span = plugin._startDnsSpan(name, { + attributes: { + [AttributeNames.PEER_HOSTNAME]: hostname, + }, + }); + + const originalCallback = args[argsCount - 1]; + if (typeof originalCallback === 'function') { + args[argsCount - 1] = plugin._wrapLookupCallback( + originalCallback, + args[argsCount - 2], + span + ); + return plugin._safeExecute(span, () => + (original as LookupFunctionSignature).apply(this, [ + hostname, + ...args, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ] as any) + ); + } else { + const promise = plugin._safeExecute(span, () => + (original as LookupPromiseSignature).apply(this, [hostname, ...args]) + ); + promise.then( + result => { + utils.setLookupAttributes(span, result as LookupAddress); + span.end(); + }, + (e: NodeJS.ErrnoException) => { + utils.setError(e, span, process.version); + span.end(); + } + ); + + return promise; + } + }; + } + + /** + * Start a new span with default attributes and kind + */ + private _startDnsSpan(name: string, options: Omit) { + return this.tracer + .startSpan(name, { ...options, kind: SpanKind.CLIENT }) + .setAttribute( + AttributeNames.COMPONENT, + '@opentelemetry/instrumentation-dns' + ); + } + + /** + * Wrap lookup callback function + */ + private _wrapLookupCallback( + original: Function, + options: unknown, + span: Span + ): LookupCallbackSignature { + const plugin = this; + return function wrappedLookupCallback( + this: {}, + err: NodeJS.ErrnoException | null, + address: string | LookupAddress[], + family?: AddressFamily + ): void { + plugin._logger.debug('executing wrapped lookup callback function'); + + if (err !== null) { + utils.setError(err, span, process.version); + } else { + utils.setLookupAttributes(span, address, family); + } + + span.end(); + plugin._logger.debug('executing original lookup callback function'); + return original.apply(this, arguments); + }; + } + + /** + * Safely handle "execute" callback + */ + private _safeExecute ReturnType>( + span: Span, + execute: T + ): ReturnType { + try { + return execute(); + } catch (error) { + utils.setError(error, span, process.version); + span.end(); + throw error; + } + } +} diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/enums/AddressFamily.ts b/plugins/node/opentelemetry-instrumentation-dns/src/enums/AddressFamily.ts new file mode 100644 index 0000000000..57522ecc1d --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/src/enums/AddressFamily.ts @@ -0,0 +1,21 @@ +/* + * 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 enum AddressFamily { + IPV4 = 4, + IPV6 = 6, + UNKNOWN = 0, +} diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.ts b/plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.ts new file mode 100644 index 0000000000..384ea7dcb1 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.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. + */ +export enum AttributeNames { + COMPONENT = 'component', + PEER_HOSTNAME = 'peer.hostname', + PEER_PORT = 'peer.port', + PEER_SERVICE = 'peer.service', + // NOT ON OFFICIAL SPEC + DNS_ERROR_CODE = 'dns.error_code', + DNS_ERROR_NAME = 'dns.error_name', + DNS_ERROR_MESSAGE = 'dns.error_message', +} diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/index.ts b/plugins/node/opentelemetry-instrumentation-dns/src/index.ts new file mode 100644 index 0000000000..292b36d614 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/src/index.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. + */ + +export * from './dns'; +export { DnsInstrumentationConfig } from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/types.ts b/plugins/node/opentelemetry-instrumentation-dns/src/types.ts new file mode 100644 index 0000000000..cbd9c0ca70 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/src/types.ts @@ -0,0 +1,100 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as dns from 'dns'; +import { InstrumentationConfig } from '@opentelemetry/instrumentation'; + +export type Dns = typeof dns; + +export type IgnoreMatcher = string | RegExp | ((url: string) => boolean); + +export type LookupFunction = (( + hostname: string, + family: number, + callback: LookupSimpleCallback +) => void) & + (( + hostname: string, + options: dns.LookupOneOptions, + callback: LookupSimpleCallback + ) => void) & + (( + hostname: string, + options: dns.LookupAllOptions, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: dns.LookupAddress[] + ) => void + ) => void) & + (( + hostname: string, + options: dns.LookupOptions, + callback: ( + err: NodeJS.ErrnoException | null, + address: string | dns.LookupAddress[], + family: number + ) => void + ) => void) & + ((hostname: string, callback: LookupSimpleCallback) => void); + +export type LookupSimpleArgs = [number, LookupSimpleCallback]; +export type LookupOneArgs = [dns.LookupOneOptions, LookupSimpleCallback]; +export type LookupAllArgs = [ + dns.LookupAllOptions, + (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => void +]; +export type LookupArgs = [ + dns.LookupOptions, + ( + err: NodeJS.ErrnoException | null, + address: string | dns.LookupAddress[], + family: number + ) => void +]; +export type LookupArgSignature = LookupSimpleArgs & + LookupSimpleCallback & + LookupOneArgs & + LookupAllArgs & + LookupArgs; + +export type LookupFunctionSignature = ( + hostname: string, + args: Array +) => void; +export type LookupPromiseSignature = ( + hostname: string, + ...args: unknown[] +) => Promise; +export type LookupSimpleCallback = ( + err: NodeJS.ErrnoException | null, + address: string, + family: number +) => void; + +export type LookupCallbackSignature = LookupSimpleCallback & + (( + err: NodeJS.ErrnoException | null, + addresses: dns.LookupAddress[] + ) => void) & + (( + err: NodeJS.ErrnoException | null, + address: string | dns.LookupAddress[], + family: number + ) => void); + +export interface DnsInstrumentationConfig extends InstrumentationConfig { + ignoreHostnames?: IgnoreMatcher[]; +} diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/utils.ts b/plugins/node/opentelemetry-instrumentation-dns/src/utils.ts new file mode 100644 index 0000000000..8d7c149cae --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/src/utils.ts @@ -0,0 +1,156 @@ +/* + * 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 { Span, StatusCode, Attributes } from '@opentelemetry/api'; +import { AttributeNames } from './enums/AttributeNames'; +import { AddressFamily } from './enums/AddressFamily'; +import * as dns from 'dns'; +import { IgnoreMatcher } from './types'; + +/** + * Set error attributes on the span passed in params + * @param err the error that we use for filling the attributes + * @param span the span to be set + * @param nodeVersion the node version + */ +export const setError = ( + err: NodeJS.ErrnoException, + span: Span, + nodeVersion: string +) => { + const { code, message, name } = err; + const attributes = { + [AttributeNames.DNS_ERROR_MESSAGE]: message, + [AttributeNames.DNS_ERROR_NAME]: name, + } as Attributes; + + if (nodeVersion.startsWith('v12')) { + attributes[AttributeNames.DNS_ERROR_CODE] = code!; + } + + span.setAttributes(attributes); + + span.setStatus({ + code: StatusCode.ERROR, + message, + }); +}; + +/** + * Returns the family attribute name to be set on the span + * @param family `4` (ipv4) or `6` (ipv6). `0` means bug. + * @param [index] `4` (ipv4) or `6` (ipv6). `0` means bug. + */ +export const getFamilyAttribute = ( + family: AddressFamily, + index?: number +): string => { + return index ? `peer[${index}].ipv${family}` : `peer.ipv${family}`; +}; + +/** + * Returns the span name + * @param funcName function name that is wrapped (e.g `lookup`) + * @param [service] e.g `http` + */ +export const getOperationName = ( + funcName: string, + service?: string +): string => { + return service ? `dns.${service}/${funcName}` : `dns.${funcName}`; +}; + +export const setLookupAttributes = ( + span: Span, + address: string | dns.LookupAddress[] | dns.LookupAddress, + family?: number +) => { + const attributes = {} as Attributes; + const isObject = typeof address === 'object'; + let addresses = address; + + if (!isObject) { + addresses = [{ address, family } as dns.LookupAddress]; + } else if (!(addresses instanceof Array)) { + addresses = [ + { + address: (address as dns.LookupAddress).address, + family: (address as dns.LookupAddress).family, + } as dns.LookupAddress, + ]; + } + + addresses.forEach((_, i) => { + const peerAttrFormat = getFamilyAttribute(_.family, i); + attributes[peerAttrFormat] = _.address; + }); + + span.setAttributes(attributes); +}; + +/** + * Check whether the given obj match pattern + * @param constant e.g URL of request + * @param obj obj to inspect + * @param pattern Match pattern + */ +export const satisfiesPattern = ( + constant: string, + pattern: IgnoreMatcher +): boolean => { + if (typeof pattern === 'string') { + return pattern === constant; + } else if (pattern instanceof RegExp) { + return pattern.test(constant); + } else if (typeof pattern === 'function') { + return pattern(constant); + } else { + throw new TypeError('Pattern is in unsupported datatype'); + } +}; + +/** + * Check whether the given dns request is ignored by configuration + * It will not re-throw exceptions from `list` provided by the client + * @param constant e.g URL of request + * @param [list] List of ignore patterns + * @param [onException] callback for doing something when an exception has + * occurred + */ +export const isIgnored = ( + constant: string, + list?: IgnoreMatcher[], + onException?: (error: Error) => void +): boolean => { + if (!list) { + // No ignored urls - trace everything + return false; + } + // Try/catch outside the loop for failing fast + try { + for (const pattern of list) { + if (satisfiesPattern(constant, pattern)) { + return true; + } + } + } catch (e) { + if (onException) { + onException(e); + } + } + + return false; +}; diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/version.ts b/plugins/node/opentelemetry-instrumentation-dns/src/version.ts new file mode 100644 index 0000000000..707690f363 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/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.12.0'; diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts new file mode 100644 index 0000000000..8af5316cb2 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts @@ -0,0 +1,69 @@ +/* + * 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 { DnsInstrumentation } from '../../src/dns'; +import * as sinon from 'sinon'; +import * as dns from 'dns'; + +const memoryExporter = new InMemorySpanExporter(); +const provider = new NodeTracerProvider(); +const tracer = provider.getTracer('default'); +provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('DnsInstrumentation', () => { + let instrumentation: DnsInstrumentation; + + before(() => { + instrumentation = new DnsInstrumentation(); + instrumentation.setTracerProvider(provider); + require('dns'); + assert.strictEqual(dns.lookup.__wrapped, true); + }); + + beforeEach(() => { + tracer.startSpan = sinon.spy(); + tracer.withSpan = sinon.spy(); + }); + + afterEach(() => { + sinon.restore(); + }); + + describe('unpatch()', () => { + it('should not call tracer methods for creating span', done => { + instrumentation.disable(); + const hostname = 'localhost'; + + dns.lookup(hostname, (err, address, family) => { + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 0); + + assert.strictEqual(dns.lookup.__wrapped, undefined); + assert.strictEqual((tracer.withSpan as sinon.SinonSpy).called, false); + done(); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts new file mode 100644 index 0000000000..f07347368b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts @@ -0,0 +1,171 @@ +/* + * 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 { NoopLogger } from '@opentelemetry/core'; +import { BasicTracerProvider, Span } from '@opentelemetry/tracing'; +import { ROOT_CONTEXT, SpanKind, TraceFlags } from '@opentelemetry/api'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import { AttributeNames } from '../../src/enums/AttributeNames'; +import { IgnoreMatcher } from '../../src/types'; +import * as utils from '../../src/utils'; + +describe('Utility', () => { + describe('satisfiesPattern()', () => { + it('string pattern', () => { + const answer1 = utils.satisfiesPattern('localhost', 'localhost'); + assert.strictEqual(answer1, true); + const answer2 = utils.satisfiesPattern('hostname', 'localhost'); + assert.strictEqual(answer2, false); + }); + + it('regex pattern', () => { + const answer1 = utils.satisfiesPattern('LocalHost', /localhost/i); + assert.strictEqual(answer1, true); + const answer2 = utils.satisfiesPattern('Montreal.ca', /montreal.ca/); + assert.strictEqual(answer2, false); + }); + + it('should throw if type is unknown', () => { + try { + utils.satisfiesPattern( + 'google.com', + (true as unknown) as IgnoreMatcher + ); + assert.fail(); + } catch (error) { + assert.strictEqual(error instanceof TypeError, true); + } + }); + + it('function pattern', () => { + const answer1 = utils.satisfiesPattern( + 'montreal.ca', + (url: string) => url === 'montreal.ca' + ); + assert.strictEqual(answer1, true); + const answer2 = utils.satisfiesPattern( + 'montreal.ca', + (url: string) => url !== 'montreal.ca' + ); + assert.strictEqual(answer2, false); + }); + }); + + describe('isIgnored()', () => { + let satisfiesPatternStub: sinon.SinonSpy<[string, IgnoreMatcher], boolean>; + beforeEach(() => { + satisfiesPatternStub = sinon.spy(utils, 'satisfiesPattern'); + }); + + afterEach(() => { + satisfiesPatternStub.restore(); + }); + + it('should call isSatisfyPattern, n match', () => { + const answer1 = utils.isIgnored('localhost', ['test']); + assert.strictEqual(answer1, false); + assert.strictEqual( + (utils.satisfiesPattern as sinon.SinonSpy).callCount, + 1 + ); + }); + + it('should call isSatisfyPattern, match for function', () => { + satisfiesPatternStub.restore(); + const answer1 = utils.isIgnored('api.montreal.ca', [ + url => url.endsWith('montreal.ca'), + ]); + assert.strictEqual(answer1, true); + }); + + it('should not re-throw when function throws an exception', () => { + satisfiesPatternStub.restore(); + const log = new NoopLogger(); + const onException = (e: Error) => { + log.error('error', e); + }; + for (const callback of [undefined, onException]) { + assert.doesNotThrow(() => + utils.isIgnored( + 'test', + [ + url => { + throw new Error('test'); + }, + ], + callback + ) + ); + } + }); + + it('should call onException when function throws an exception', () => { + satisfiesPatternStub.restore(); + const onException = sinon.spy(); + assert.doesNotThrow(() => + utils.isIgnored( + 'test', + [ + url => { + throw new Error('test'); + }, + ], + onException + ) + ); + assert.strictEqual((onException as sinon.SinonSpy).callCount, 1); + }); + + it('should not call isSatisfyPattern', () => { + utils.isIgnored('test', []); + assert.strictEqual( + (utils.satisfiesPattern as sinon.SinonSpy).callCount, + 0 + ); + }); + + it('should return false on empty list', () => { + const answer1 = utils.isIgnored('test', []); + assert.strictEqual(answer1, false); + }); + + it('should not throw and return false when list is undefined', () => { + const answer2 = utils.isIgnored('test', undefined); + assert.strictEqual(answer2, false); + }); + }); + + describe('setError()', () => { + it('should have error attributes', () => { + const errorMessage = 'test error'; + const span = new Span( + new BasicTracerProvider().getTracer('default'), + ROOT_CONTEXT, + 'test', + { spanId: '', traceId: '', traceFlags: TraceFlags.NONE }, + SpanKind.INTERNAL + ); + utils.setError(new Error(errorMessage), span, process.versions.node); + const attributes = span.attributes; + assert.strictEqual( + attributes[AttributeNames.DNS_ERROR_MESSAGE], + errorMessage + ); + assert.ok(attributes[AttributeNames.DNS_ERROR_NAME]); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.test.ts new file mode 100644 index 0000000000..b87aed39ce --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.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 { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { DnsInstrumentation } from '../../src/dns'; +import * as dns from 'dns'; +import * as utils from '../utils/utils'; +import { assertSpan } from '../utils/assertSpan'; +import { StatusCode } from '@opentelemetry/api'; + +const memoryExporter = new InMemorySpanExporter(); +const provider = new NodeTracerProvider(); +provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('dns.lookup()', () => { + let instrumentation: DnsInstrumentation; + + before(function (done) { + // mandatory + if (process.env.CI) { + instrumentation = new DnsInstrumentation(); + instrumentation.setTracerProvider(provider); + require('dns'); + done(); + return; + } + + utils.checkInternet(isConnected => { + if (!isConnected) { + this.skip(); + // don't disturbe people + } + done(); + }); + instrumentation = new DnsInstrumentation(); + instrumentation.setTracerProvider(provider); + require('dns'); + }); + + afterEach(() => { + memoryExporter.reset(); + }); + + after(() => { + instrumentation.disable(); + }); + + describe('with family param', () => { + [4, 6].forEach(ipversion => { + it(`should export a valid span with "family" arg to ${ipversion}`, done => { + const hostname = 'google.com'; + dns.lookup(hostname, ipversion, (err, address, family) => { + assert.strictEqual(err, null); + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { addresses: [{ address, family }], hostname }); + done(); + }); + }); + }); + }); + + describe('with no options param', () => { + it('should export a valid span', done => { + const hostname = 'google.com'; + dns.lookup(hostname, (err, address, family) => { + assert.strictEqual(err, null); + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { addresses: [{ address, family }], hostname }); + done(); + }); + }); + + it('should export a valid span with error NOT_FOUND', done => { + const hostname = 'ᚕ'; + dns.lookup(hostname, (err, address, family) => { + assert.ok(err); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + + assert.strictEqual(spans.length, 1); + assertSpan(span, { + addresses: [{ address, family }], + hostname, + forceStatus: { + code: StatusCode.ERROR, + message: err!.message, + }, + }); + done(); + }); + }); + + it('should export a valid span with error INVALID_ARGUMENT when "family" param is equal to -1', () => { + const hostname = 'google.com'; + try { + dns.lookup(hostname, -1, () => {}); + assert.fail(); + } catch (error) { + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { + addresses: [], + hostname, + forceStatus: { + code: StatusCode.ERROR, + message: error!.message, + }, + }); + } + }); + + it('should export a valid span with error INVALID_ARGUMENT when "hostname" param is a number', () => { + const hostname = 1234; + try { + // tslint:disable-next-line:no-any + dns.lookup(hostname as any, 4, () => {}); + assert.fail(); + } catch (error) { + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { + addresses: [], + // tslint:disable-next-line:no-any + hostname: hostname as any, + forceStatus: { + code: StatusCode.ERROR, + message: error!.message, + }, + }); + } + }); + }); + describe('with options param', () => { + [4, 6].forEach(family => { + it(`should export a valid span with "family" to ${family}`, done => { + const hostname = 'google.com'; + dns.lookup(hostname, { family }, (err, address, family) => { + assert.strictEqual(err, null); + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + + assertSpan(span, { addresses: [{ address, family }], hostname }); + done(); + }); + }); + + it(`should export a valid span when setting "verbatim" property to true and "family" to ${family}`, done => { + const hostname = 'google.com'; + dns.lookup( + hostname, + { family, verbatim: true }, + (err, address, family) => { + assert.strictEqual(err, null); + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + + assertSpan(span, { addresses: [{ address, family }], hostname }); + done(); + } + ); + }); + }); + + it('should export a valid span when setting "all" property to true', done => { + const hostname = 'montreal.ca'; + dns.lookup( + hostname, + { all: true }, + (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => { + assert.strictEqual(err, null); + assert.ok(addresses instanceof Array); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { addresses, hostname }); + done(); + } + ); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts new file mode 100644 index 0000000000..9169eb847a --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts @@ -0,0 +1,228 @@ +/* + * 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 { DnsInstrumentation } from '../../src/dns'; +import * as dns from 'dns'; +import * as utils from '../utils/utils'; +import { assertSpan } from '../utils/assertSpan'; +import { StatusCode } from '@opentelemetry/api'; + +const memoryExporter = new InMemorySpanExporter(); +const provider = new NodeTracerProvider(); +provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +async function lookupPromise( + hostname: string, + options: dns.LookupOptions = {} +): Promise { + return new Promise((resolve, reject) => { + dns.lookup(hostname, options, (err, address, family) => { + if (err) reject(err); + if (options.all) { + resolve(address); + } else { + resolve({ address, family }); + } + }); + }); +} + +describe('dns.promises.lookup()', () => { + let instrumentation: DnsInstrumentation; + + before(function (done) { + // if node version is supported, it's mandatory for CI + if (process.env.CI) { + instrumentation = new DnsInstrumentation(); + instrumentation.setTracerProvider(provider); + require('dns'); + done(); + return; + } + + utils.checkInternet(isConnected => { + if (!isConnected) { + this.skip(); + // don't disturb people + } + done(); + }); + instrumentation = new DnsInstrumentation(); + instrumentation.setTracerProvider(provider); + require('dns'); + }); + + afterEach(() => { + memoryExporter.reset(); + }); + + after(() => { + instrumentation.disable(); + }); + + describe('with family param', () => { + [4, 6].forEach(ipversion => { + it(`should export a valid span with "family" arg to ${ipversion}`, async () => { + const hostname = 'google.com'; + const { address, family } = await lookupPromise(hostname, { + family: ipversion, + }); + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { addresses: [{ address, family }], hostname }); + }); + }); + }); + + describe('with no options param', () => { + it('should export a valid span', async () => { + const hostname = 'google.com'; + const { address, family } = await lookupPromise(hostname); + + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { addresses: [{ address, family }], hostname }); + }); + + it('should export a valid span with error NOT_FOUND', async () => { + const hostname = 'ᚕ'; + try { + await lookupPromise(hostname); + assert.fail(); + } catch (error) { + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + + assert.strictEqual(spans.length, 1); + assertSpan(span, { + addresses: [], + hostname, + forceStatus: { + code: StatusCode.ERROR, + message: error!.message, + }, + }); + } + }); + + it('should export a valid span with error INVALID_ARGUMENT when "family" param is equal to -1', async () => { + const hostname = 'google.com'; + try { + await lookupPromise(hostname, { family: -1 }); + assert.fail(); + } catch (error) { + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + + assert.strictEqual(spans.length, 1); + assertSpan(span, { + addresses: [], + // tslint:disable-next-line:no-any + hostname: hostname as any, + forceStatus: { + code: StatusCode.ERROR, + message: error!.message, + }, + }); + } + }); + + it('should export a valid span with error INVALID_ARGUMENT when "hostname" param is a number', async () => { + const hostname = 1234; + try { + // tslint:disable-next-line:no-any + await lookupPromise(hostname as any, { family: 4 }); + assert.fail(); + } catch (error) { + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + + assert.strictEqual(spans.length, 1); + assertSpan(span, { + addresses: [], + // tslint:disable-next-line:no-any + hostname: hostname as any, + forceStatus: { + code: StatusCode.ERROR, + message: error!.message, + }, + }); + } + }); + }); + describe('with options param', () => { + [4, 6].forEach(ipversion => { + it(`should export a valid span with "family" to ${ipversion}`, async () => { + const hostname = 'google.com'; + const { address, family } = await lookupPromise(hostname, { + family: ipversion, + }); + + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + + assertSpan(span, { addresses: [{ address, family }], hostname }); + }); + + it(`should export a valid span when setting "verbatim" property to true and "family" to ${ipversion}`, async () => { + const hostname = 'google.com'; + const { address, family } = await lookupPromise(hostname, { + family: ipversion, + verbatim: true, + }); + + assert.ok(address); + assert.ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + + assertSpan(span, { addresses: [{ address, family }], hostname }); + }); + }); + + it('should export a valid span when setting "all" property to true', async () => { + const hostname = 'montreal.ca'; + const addresses = await lookupPromise(hostname, { all: true }); + + assert.ok(addresses instanceof Array); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + assert.strictEqual(spans.length, 1); + assertSpan(span, { addresses, hostname }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts b/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts new file mode 100644 index 0000000000..5fa8117e7a --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts @@ -0,0 +1,72 @@ +/* + * 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, Status, StatusCode } from '@opentelemetry/api'; +import { hrTimeToNanoseconds } from '@opentelemetry/core'; +import * as assert from 'assert'; +import { AttributeNames } from '../../src/enums/AttributeNames'; +import { ReadableSpan } from '@opentelemetry/tracing'; +import * as utils from '../../src/utils'; +import { LookupAddress } from 'dns'; + +export const assertSpan = ( + span: ReadableSpan, + validations: { + addresses: LookupAddress[]; + hostname: string; + forceStatus?: Status; + } +) => { + if (span.spanContext.traceId) { + assert.strictEqual(span.spanContext.traceId.length, 32); + } + if (span.spanContext.spanId) { + assert.strictEqual(span.spanContext.spanId.length, 16); + } + + assert.strictEqual(span.kind, SpanKind.CLIENT); + + assert.strictEqual( + span.attributes[AttributeNames.COMPONENT], + '@opentelemetry/instrumentation-dns' + ); + assert.strictEqual( + span.attributes[AttributeNames.DNS_ERROR_MESSAGE], + span.status.message + ); + assert.strictEqual( + span.attributes[AttributeNames.PEER_HOSTNAME], + validations.hostname + ); + + validations.addresses.forEach((_, i) => { + assert.strictEqual( + span.attributes[utils.getFamilyAttribute(_.family, i)], + _.address + ); + }); + + assert.ok(span.endTime); + assert.strictEqual(span.links.length, 0); + assert.strictEqual(span.events.length, 0); + + assert.deepStrictEqual( + span.status, + validations.forceStatus || { code: StatusCode.UNSET } + ); + + assert.ok(hrTimeToNanoseconds(span.duration), 'must have positive duration'); +}; diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts b/plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts new file mode 100644 index 0000000000..a4e37eabea --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as dns from 'dns'; + +export const checkInternet = (cb: (isConnected: boolean) => void) => { + dns.lookup('google.com', err => { + if (err && err.code === 'ENOTFOUND') { + cb(false); + } else { + cb(true); + } + }); +}; diff --git a/plugins/node/opentelemetry-instrumentation-dns/tsconfig.json b/plugins/node/opentelemetry-instrumentation-dns/tsconfig.json new file mode 100644 index 0000000000..28be80d266 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-dns/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} From 5cdd84353d2f6a54925b30a9a06cdebe3b2b23d5 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Thu, 14 Jan 2021 20:03:17 +0100 Subject: [PATCH 2/8] remove setConfig --- plugins/node/opentelemetry-instrumentation-dns/src/dns.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts b/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts index e46ef3953e..973f3d648b 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts @@ -18,7 +18,6 @@ import { LookupAddress } from 'dns'; import { Span, SpanKind, SpanOptions } from '@opentelemetry/api'; import { InstrumentationBase, - InstrumentationConfig, InstrumentationNodeModuleDefinition, isWrapped, } from '@opentelemetry/instrumentation'; @@ -43,12 +42,6 @@ export class DnsInstrumentation extends InstrumentationBase { super('@opentelemetry/instrumentation-dns', VERSION, _config); } - public setConfig( - config: DnsInstrumentationConfig & InstrumentationConfig = {} - ) { - this._config = Object.assign({}, config); - } - init(): InstrumentationNodeModuleDefinition[] { return [ new InstrumentationNodeModuleDefinition( From 640fe05774ff06d916a50b30eee1a54b8d3fd0c8 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Mon, 18 Jan 2021 10:23:29 +0100 Subject: [PATCH 3/8] chore: review findings --- .../README.md | 24 ++----- .../package.json | 1 + .../src/dns.ts | 69 +++++++------------ .../src/enums/AttributeNames.ts | 4 -- .../src/types.ts | 2 +- .../test/utils/assertSpan.ts | 11 ++- 6 files changed, 39 insertions(+), 72 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-dns/README.md b/plugins/node/opentelemetry-instrumentation-dns/README.md index 3708d2d893..64775cb523 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/README.md +++ b/plugins/node/opentelemetry-instrumentation-dns/README.md @@ -34,23 +34,13 @@ const dnsInstrumentation = new DnsInstrumentation({ }); ``` -### Zipkin - -If you use Zipkin, you must use `ignoreHostnames` in order to not trace those calls. If the server is local. You can set: - -```js -const dnsInstrumentation = new DnsInstrumentation({ - ignoreHostnames: ['localhost'] -}); -``` - ### Dns Instrumentation Options Dns instrumentation has currently one option. You can set the following: | Options | Type | Description | | ------- | ---- | ----------- | -| [`ignoreHostnames`](https://github.com/open-telemetry/opentelemetry-js/blob/master/packages/opentelemetry-instrumentation-dns/src/types.ts#L98) | `IgnoreMatcher[]` | Dns instrumentation will not trace all requests that match hostnames | +| [`ignoreHostnames`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/master/packages/opentelemetry-instrumentation-dns/src/types.ts#L99) | `IgnoreMatcher[]` | Dns instrumentation will not trace all requests that match hostnames | ## Useful links @@ -62,11 +52,11 @@ Dns instrumentation has currently one option. You can set the following: Apache 2.0 - See [LICENSE][license-url] for more information. -[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg +[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/blob/master/LICENSE +[license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/master/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/status.svg?path=packages/opentelemetry-instrumentation-dns -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-dns -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-instrumentation-dns -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-dns&type=dev +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/status.svg?path=packages/opentelemetry-instrumentation-dns +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-dns +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=packages/opentelemetry-instrumentation-dns +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-dns&type=dev diff --git a/plugins/node/opentelemetry-instrumentation-dns/package.json b/plugins/node/opentelemetry-instrumentation-dns/package.json index 9aa9579ce2..fe6157a239 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/package.json +++ b/plugins/node/opentelemetry-instrumentation-dns/package.json @@ -64,6 +64,7 @@ "dependencies": { "@opentelemetry/api": "^0.14.0", "@opentelemetry/instrumentation": "^0.14.0", + "@opentelemetry/semantic-conventions": "^0.14.0", "semver": "^7.3.2" } } diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts b/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts index 973f3d648b..2e03803e47 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/src/dns.ts @@ -15,20 +15,20 @@ */ import { LookupAddress } from 'dns'; -import { Span, SpanKind, SpanOptions } from '@opentelemetry/api'; +import { Span, SpanKind } from '@opentelemetry/api'; +import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; import { InstrumentationBase, InstrumentationNodeModuleDefinition, isWrapped, + safeExecuteInTheMiddle, } from '@opentelemetry/instrumentation'; import * as semver from 'semver'; import { AddressFamily } from './enums/AddressFamily'; -import { AttributeNames } from './enums/AttributeNames'; import { Dns, DnsInstrumentationConfig, LookupCallbackSignature, - LookupFunctionSignature, LookupPromiseSignature, } from './types'; import * as utils from './utils'; @@ -111,9 +111,10 @@ export class DnsInstrumentation extends InstrumentationBase { const argsCount = args.length; plugin._logger.debug('wrap lookup callback function and starts span'); const name = utils.getOperationName('lookup'); - const span = plugin._startDnsSpan(name, { + const span = plugin.tracer.startSpan(name, { + kind: SpanKind.CLIENT, attributes: { - [AttributeNames.PEER_HOSTNAME]: hostname, + [GeneralAttribute.NET_PEER_HOSTNAME]: hostname, }, }); @@ -121,19 +122,30 @@ export class DnsInstrumentation extends InstrumentationBase { if (typeof originalCallback === 'function') { args[argsCount - 1] = plugin._wrapLookupCallback( originalCallback, - args[argsCount - 2], span ); - return plugin._safeExecute(span, () => - (original as LookupFunctionSignature).apply(this, [ - hostname, - ...args, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ] as any) + return safeExecuteInTheMiddle( + () => original.apply(this, [hostname, ...args]), + error => { + if (error != null) { + utils.setError(error, span, process.version); + span.end(); + } + } ); } else { - const promise = plugin._safeExecute(span, () => - (original as LookupPromiseSignature).apply(this, [hostname, ...args]) + const promise = safeExecuteInTheMiddle( + () => + (original as LookupPromiseSignature).apply(this, [ + hostname, + ...args, + ]), + error => { + if (error != null) { + utils.setError(error, span, process.version); + span.end(); + } + } ); promise.then( result => { @@ -151,24 +163,11 @@ export class DnsInstrumentation extends InstrumentationBase { }; } - /** - * Start a new span with default attributes and kind - */ - private _startDnsSpan(name: string, options: Omit) { - return this.tracer - .startSpan(name, { ...options, kind: SpanKind.CLIENT }) - .setAttribute( - AttributeNames.COMPONENT, - '@opentelemetry/instrumentation-dns' - ); - } - /** * Wrap lookup callback function */ private _wrapLookupCallback( original: Function, - options: unknown, span: Span ): LookupCallbackSignature { const plugin = this; @@ -191,20 +190,4 @@ export class DnsInstrumentation extends InstrumentationBase { return original.apply(this, arguments); }; } - - /** - * Safely handle "execute" callback - */ - private _safeExecute ReturnType>( - span: Span, - execute: T - ): ReturnType { - try { - return execute(); - } catch (error) { - utils.setError(error, span, process.version); - span.end(); - throw error; - } - } } diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.ts b/plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.ts index 384ea7dcb1..2364b3769c 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/src/enums/AttributeNames.ts @@ -14,10 +14,6 @@ * limitations under the License. */ export enum AttributeNames { - COMPONENT = 'component', - PEER_HOSTNAME = 'peer.hostname', - PEER_PORT = 'peer.port', - PEER_SERVICE = 'peer.service', // NOT ON OFFICIAL SPEC DNS_ERROR_CODE = 'dns.error_code', DNS_ERROR_NAME = 'dns.error_name', diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/types.ts b/plugins/node/opentelemetry-instrumentation-dns/src/types.ts index cbd9c0ca70..70f4f6d54e 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/src/types.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/src/types.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as dns from 'dns'; +import type * as dns from 'dns'; import { InstrumentationConfig } from '@opentelemetry/instrumentation'; export type Dns = typeof dns; diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts b/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts index 5fa8117e7a..a05f9ad5c1 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts @@ -16,11 +16,12 @@ import { SpanKind, Status, StatusCode } from '@opentelemetry/api'; import { hrTimeToNanoseconds } from '@opentelemetry/core'; +import { ReadableSpan } from '@opentelemetry/tracing'; +import { GeneralAttribute } from '@opentelemetry/semantic-conventions'; import * as assert from 'assert'; +import type { LookupAddress } from 'dns'; import { AttributeNames } from '../../src/enums/AttributeNames'; -import { ReadableSpan } from '@opentelemetry/tracing'; import * as utils from '../../src/utils'; -import { LookupAddress } from 'dns'; export const assertSpan = ( span: ReadableSpan, @@ -39,16 +40,12 @@ export const assertSpan = ( assert.strictEqual(span.kind, SpanKind.CLIENT); - assert.strictEqual( - span.attributes[AttributeNames.COMPONENT], - '@opentelemetry/instrumentation-dns' - ); assert.strictEqual( span.attributes[AttributeNames.DNS_ERROR_MESSAGE], span.status.message ); assert.strictEqual( - span.attributes[AttributeNames.PEER_HOSTNAME], + span.attributes[GeneralAttribute.NET_PEER_HOSTNAME], validations.hostname ); From 1989590feb0d5e05a0fd31d8fa7eac5abb44aa0b Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Fri, 22 Jan 2021 00:09:19 +0100 Subject: [PATCH 4/8] chore: move to otel 0.15.0 --- .../opentelemetry-instrumentation-dns/package.json | 12 ++++++------ .../test/functionals/dns-disable.test.ts | 11 ++++++----- .../test/functionals/utils.test.ts | 8 ++++++-- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-dns/package.json b/plugins/node/opentelemetry-instrumentation-dns/package.json index fe6157a239..705b7709eb 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/package.json +++ b/plugins/node/opentelemetry-instrumentation-dns/package.json @@ -41,9 +41,9 @@ "access": "public" }, "devDependencies": { - "@opentelemetry/core": "^0.14.0", - "@opentelemetry/node": "^0.14.0", - "@opentelemetry/tracing": "^0.14.0", + "@opentelemetry/core": "^0.15.0", + "@opentelemetry/node": "^0.15.0", + "@opentelemetry/tracing": "^0.15.0", "@types/mocha": "7.0.2", "@types/node": "14.0.27", "@types/semver": "7.3.1", @@ -62,9 +62,9 @@ "typescript": "3.9.7" }, "dependencies": { - "@opentelemetry/api": "^0.14.0", - "@opentelemetry/instrumentation": "^0.14.0", - "@opentelemetry/semantic-conventions": "^0.14.0", + "@opentelemetry/api": "^0.15.0", + "@opentelemetry/instrumentation": "^0.15.0", + "@opentelemetry/semantic-conventions": "^0.15.0", "semver": "^7.3.2" } } diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts index 8af5316cb2..00252fb9f2 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +import { context } from '@opentelemetry/api'; import { InMemorySpanExporter, SimpleSpanProcessor, @@ -21,7 +22,7 @@ import { import * as assert from 'assert'; import { NodeTracerProvider } from '@opentelemetry/node'; import { DnsInstrumentation } from '../../src/dns'; -import * as sinon from 'sinon'; +import * as Sinon from 'sinon'; import * as dns from 'dns'; const memoryExporter = new InMemorySpanExporter(); @@ -40,12 +41,12 @@ describe('DnsInstrumentation', () => { }); beforeEach(() => { - tracer.startSpan = sinon.spy(); - tracer.withSpan = sinon.spy(); + Sinon.spy(tracer, 'startSpan'); + Sinon.spy(context, 'with'); }); afterEach(() => { - sinon.restore(); + Sinon.restore(); }); describe('unpatch()', () => { @@ -61,7 +62,7 @@ describe('DnsInstrumentation', () => { assert.strictEqual(spans.length, 0); assert.strictEqual(dns.lookup.__wrapped, undefined); - assert.strictEqual((tracer.withSpan as sinon.SinonSpy).called, false); + assert.strictEqual((context.with as sinon.SinonSpy).called, false); done(); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts index f07347368b..90393f5449 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts @@ -14,9 +14,13 @@ * limitations under the License. */ -import { NoopLogger } from '@opentelemetry/core'; +import { + ROOT_CONTEXT, + SpanKind, + TraceFlags, + NoopLogger, +} from '@opentelemetry/api'; import { BasicTracerProvider, Span } from '@opentelemetry/tracing'; -import { ROOT_CONTEXT, SpanKind, TraceFlags } from '@opentelemetry/api'; import * as assert from 'assert'; import * as sinon from 'sinon'; import { AttributeNames } from '../../src/enums/AttributeNames'; From ae2df64e4bbaab0687d915c56b76925caf90f959 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Thu, 28 Jan 2021 00:06:24 +0100 Subject: [PATCH 5/8] chore: update version --- plugins/node/opentelemetry-instrumentation-dns/package.json | 2 +- plugins/node/opentelemetry-instrumentation-dns/src/version.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-dns/package.json b/plugins/node/opentelemetry-instrumentation-dns/package.json index 705b7709eb..fe01297348 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/package.json +++ b/plugins/node/opentelemetry-instrumentation-dns/package.json @@ -1,6 +1,6 @@ { "name": "@opentelemetry/instrumentation-dns", - "version": "0.12.0", + "version": "0.12.1", "description": "OpenTelemetry dns automatic instrumentation package.", "main": "build/src/index.js", "types": "build/src/index.d.ts", diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/version.ts b/plugins/node/opentelemetry-instrumentation-dns/src/version.ts index 707690f363..c032ed99f3 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/src/version.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/src/version.ts @@ -15,4 +15,4 @@ */ // this is autogenerated file, see scripts/version-update.js -export const VERSION = '0.12.0'; +export const VERSION = '0.12.1'; From f4ab56fd24d87c084d89204619ee919df4f10d14 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Thu, 28 Jan 2021 11:05:50 +0100 Subject: [PATCH 6/8] (chore) correct links to point to main --- plugins/node/opentelemetry-instrumentation-dns/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-dns/README.md b/plugins/node/opentelemetry-instrumentation-dns/README.md index 64775cb523..45c0ed5b6b 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/README.md +++ b/plugins/node/opentelemetry-instrumentation-dns/README.md @@ -8,7 +8,7 @@ This module provides automatic instrumentation for [`dns`](http://nodejs.org/dist/latest/docs/api/dns.html). For automatic instrumentation see the -[@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-node) package. +[@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-node) package. ## Installation @@ -40,7 +40,7 @@ Dns instrumentation has currently one option. You can set the following: | Options | Type | Description | | ------- | ---- | ----------- | -| [`ignoreHostnames`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/master/packages/opentelemetry-instrumentation-dns/src/types.ts#L99) | `IgnoreMatcher[]` | Dns instrumentation will not trace all requests that match hostnames | +| [`ignoreHostnames`](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/packages/opentelemetry-instrumentation-dns/src/types.ts#L99) | `IgnoreMatcher[]` | Dns instrumentation will not trace all requests that match hostnames | ## Useful links @@ -54,7 +54,7 @@ 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/master/LICENSE +[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-dns [dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-dns From 6867b481818ca6f94f5d8ee2ca30c18c01727e91 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Thu, 28 Jan 2021 11:14:03 +0100 Subject: [PATCH 7/8] chore: correct repo --- plugins/node/opentelemetry-instrumentation-dns/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-dns/package.json b/plugins/node/opentelemetry-instrumentation-dns/package.json index fe01297348..7ed96a48bd 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/package.json +++ b/plugins/node/opentelemetry-instrumentation-dns/package.json @@ -4,7 +4,7 @@ "description": "OpenTelemetry dns automatic instrumentation package.", "main": "build/src/index.js", "types": "build/src/index.d.ts", - "repository": "open-telemetry/opentelemetry-js", + "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", From 8f981f7bccd247411f199a06e8a73e6d27ed52c4 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Mon, 1 Feb 2021 19:55:35 +0100 Subject: [PATCH 8/8] chore: move to 0.13.0 --- plugins/node/opentelemetry-instrumentation-dns/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-dns/package.json b/plugins/node/opentelemetry-instrumentation-dns/package.json index 7ed96a48bd..dc9ec631be 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/package.json +++ b/plugins/node/opentelemetry-instrumentation-dns/package.json @@ -1,6 +1,6 @@ { "name": "@opentelemetry/instrumentation-dns", - "version": "0.12.1", + "version": "0.13.0", "description": "OpenTelemetry dns automatic instrumentation package.", "main": "build/src/index.js", "types": "build/src/index.d.ts",