diff --git a/examples/dns/README.md b/examples/dns/README.md new file mode 100644 index 0000000000..3d18e2816f --- /dev/null +++ b/examples/dns/README.md @@ -0,0 +1,60 @@ +# Overview + +OpenTelemetry DNS Instrumentation allows the user to automatically collect trace data and export them to the backend of choice (we can use Zipkin or Jaeger for this example), to give observability to distributed systems. + +This is a simple example that demonstrates tracing DNS request. The example +shows key aspects of tracing such as +- Root Span (on Client) +- Child Span (on Client) +- Span Attributes + +## Installation + +```sh +$ # from this directory +$ npm install +``` + +Setup [Zipkin Tracing](https://zipkin.io/pages/quickstart.html) +or +Setup [Jaeger Tracing](https://www.jaegertracing.io/docs/latest/getting-started/#all-in-one) + +## Run the Application + +### Zipkin + + - Run the client + + ```sh + $ # from this directory + $ npm run zipkin:client + ``` + +#### Zipkin UI +`zipkin:client` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`). +Go to Zipkin with your browser [http://localhost:9411/zipkin/traces/(your-trace-id)]() (e.g http://localhost:9411/zipkin/traces/4815c3d576d930189725f1f1d1bdfcc6) + +

+ +### Jaeger + + - Run the client + + ```sh + $ # from this directory + $ npm run jaeger:client + ``` +#### Jaeger UI + +`jaeger:client` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`). +Go to Jaeger with your browser [http://localhost:16686/trace/(your-trace-id)]() (e.g http://localhost:16686/trace/4815c3d576d930189725f1f1d1bdfcc6) + +

+ +## Useful links +- For more information on OpenTelemetry, visit: +- For more information on OpenTelemetry for Node.js, visit: + +## LICENSE + +Apache License 2.0 diff --git a/examples/dns/client.js b/examples/dns/client.js new file mode 100644 index 0000000000..83399387ab --- /dev/null +++ b/examples/dns/client.js @@ -0,0 +1,42 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/core'); +const config = require('./setup'); + +/** + * The trace instance needs to be initialized first, if you want to enable + * automatic tracing for built-in plugins (DNS in this case). + */ +config.setupTracerAndExporters('dns-client-service'); + +const dns = require('dns').promises; +const tracer = opentelemetry.getTracer(); + +/** A function which makes a dns lookup and handles response. */ +function makeLookup() { + // span corresponds to dns lookup. Here, we have manually created + // the span, which is created to track work that happens outside of the + // dns lookup query. + const span = tracer.startSpan('dnsLookup'); + tracer.withSpan(span, async () => { + try { + await dns.lookup('montreal.ca'); + } catch (error) { + span.setAttributes({ + 'error.name': error.name, + 'error.message': error.message + }); + }finally{ + console.log(`traceid: ${span.context().traceId}`); + span.end(); + } + }); + + // The process must live for at least the interval past any traces that + // must be exported, or some risk being lost if they are recorded after the + // last export. + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.') + setTimeout(() => { console.log('Completed.'); }, 5000); +} + +makeLookup(); diff --git a/examples/dns/images/jaeger-ui.png b/examples/dns/images/jaeger-ui.png new file mode 100644 index 0000000000..334d3220b1 Binary files /dev/null and b/examples/dns/images/jaeger-ui.png differ diff --git a/examples/dns/images/zipkin-ui.png b/examples/dns/images/zipkin-ui.png new file mode 100644 index 0000000000..8f75bbd01e Binary files /dev/null and b/examples/dns/images/zipkin-ui.png differ diff --git a/examples/dns/package.json b/examples/dns/package.json new file mode 100644 index 0000000000..cb47be415c --- /dev/null +++ b/examples/dns/package.json @@ -0,0 +1,40 @@ +{ + "name": "dns-example", + "private": true, + "version": "0.1.0", + "description": "Example of DNS integration with OpenTelemetry", + "main": "index.js", + "scripts": { + "zipkin:client": "cross-env EXPORTER=zipkin node ./client.js", + "jaeger:client": "cross-env EXPORTER=jaeger node ./client.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js.git" + }, + "keywords": [ + "opentelemetry", + "dns", + "tracing" + ], + "engines": { + "node": ">=8" + }, + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/open-telemetry/opentelemetry-js/issues" + }, + "dependencies": { + "@opentelemetry/core": "^0.1.0", + "@opentelemetry/exporter-jaeger": "^0.1.0", + "@opentelemetry/exporter-zipkin": "^0.1.0", + "@opentelemetry/node": "^0.1.0", + "@opentelemetry/plugin-dns": "^0.1.0", + "@opentelemetry/tracing": "^0.1.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme", + "devDependencies": { + "cross-env": "^6.0.3" + } +} diff --git a/examples/dns/setup.js b/examples/dns/setup.js new file mode 100644 index 0000000000..26da571236 --- /dev/null +++ b/examples/dns/setup.js @@ -0,0 +1,41 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/core'); +const { NodeTracer } = require('@opentelemetry/node'); +const { SimpleSpanProcessor } = require('@opentelemetry/tracing'); +const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); +const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); +const EXPORTER = process.env.EXPORTER || ''; + +function setupTracerAndExporters(service) { + const tracer = new NodeTracer({ +      plugins: { +          dns: { +            enabled: true, +            path: '@opentelemetry/plugin-dns', + // Avoid dns lookup loop with http zipkin calls + ignoreHostnames: ['localhost'] +        } +      } +  }); + + let exporter; + if (EXPORTER.toLowerCase().startsWith('z')) { + exporter = new ZipkinExporter({ + serviceName: service, + }); + } else { + exporter = new JaegerExporter({ + serviceName: service, + // The default flush interval is 5 seconds. + flushInterval: 2000 + }); + } + + tracer.addSpanProcessor(new SimpleSpanProcessor(exporter)); + + // Initialize the OpenTelemetry APIs to use the BasicTracer bindings + opentelemetry.initGlobalTracer(tracer); +} + +exports.setupTracerAndExporters = setupTracerAndExporters; diff --git a/packages/opentelemetry-plugin-dns/.npmignore b/packages/opentelemetry-plugin-dns/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/packages/opentelemetry-plugin-dns/LICENSE b/packages/opentelemetry-plugin-dns/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/packages/opentelemetry-plugin-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/packages/opentelemetry-plugin-dns/README.md b/packages/opentelemetry-plugin-dns/README.md new file mode 100644 index 0000000000..6f0c28432c --- /dev/null +++ b/packages/opentelemetry-plugin-dns/README.md @@ -0,0 +1,59 @@ +# 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/plugin-dns +``` + +## Usage + +```js +const { NodeTracer } = require('@opentelemetry/node'); + +const tracer = new NodeTracer({ + plugins: { + dns: { + enabled: true, + // You may use a package name or absolute path to the file. + path: '@opentelemetry/plugin-dns', + // dns plugin options + } + } +}); +``` + +### Dns Plugin Options + +Dns plugin has currently one option. You can set the following: + +| Options | Type | Description | +| ------- | ---- | ----------- | +| [`ignoreHostnames`](https://github.com/open-telemetry/opentelemetry-js/blob/master/packages/opentelemetry-plugin-dns/src/types.ts#L98) | `IgnoreMatcher[]` | Dns plugin 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-plugin-dns +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-plugin-dns +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-plugin-dns +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-plugin-dns&type=dev diff --git a/packages/opentelemetry-plugin-dns/package.json b/packages/opentelemetry-plugin-dns/package.json new file mode 100644 index 0000000000..3dcac61258 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/package.json @@ -0,0 +1,65 @@ +{ + "name": "@opentelemetry/plugin-dns", + "version": "0.1.0", + "description": "OpenTelemetry dns automatic instrumentation package.", + "private": true, + "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/**/*.ts'", + "tdd": "yarn test -- --watch-extensions ts --watch", + "clean": "rimraf build/*", + "check": "gts check", + "compile": "tsc -p .", + "fix": "gts fix" + }, + "keywords": [ + "opentelemetry", + "dns", + "nodejs", + "tracing", + "profiling", + "plugin" + ], + "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": { + "@types/mocha": "^5.2.7", + "@types/node": "^12.7.12", + "@types/shimmer": "^1.0.1", + "@types/sinon": "^7.5.0", + "@opentelemetry/tracing": "^0.1.0", + "@opentelemetry/node": "^0.1.0", + "codecov": "^3.6.1", + "gts": "^1.1.0", + "mocha": "^6.2.1", + "nyc": "^14.1.1", + "rimraf": "^3.0.0", + "sinon": "^7.5.0", + "tslint-microsoft-contrib": "^6.2.0", + "tslint-consistent-codestyle": "^1.16.0", + "ts-mocha": "^6.0.0", + "ts-node": "^8.4.1", + "typescript": "^3.6.4" + }, + "dependencies": { + "@opentelemetry/core": "^0.1.0", + "@opentelemetry/types": "^0.1.0", + "semver": "^6.3.0", + "shimmer": "^1.2.1" + } +} diff --git a/packages/opentelemetry-plugin-dns/src/dns.ts b/packages/opentelemetry-plugin-dns/src/dns.ts new file mode 100644 index 0000000000..2046ecb320 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/src/dns.ts @@ -0,0 +1,213 @@ +/*! + * Copyright 2019, 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 shimmer from 'shimmer'; +import * as semver from 'semver'; +import * as utils from './utils'; +import { BasePlugin } from '@opentelemetry/core'; +import { SpanOptions, SpanKind, Span } from '@opentelemetry/types'; +import { + Dns, + LookupPromiseSignature, + LookupFunction, + LookupFunctionSignature, + LookupCallbackSignature, + DnsPluginConfig, +} from './types'; +import { AttributeNames } from './enums/AttributeNames'; +import { AddressFamily } from './enums/AddressFamily'; +import { LookupAddress } from 'dns'; + +/** + * Dns instrumentation plugin for Opentelemetry + */ +export class DnsPlugin extends BasePlugin { + readonly component: string; + protected _config!: DnsPluginConfig; + + constructor(readonly moduleName: string, readonly version: string) { + super(); + // For now component is equal to moduleName but it can change in the future. + this.component = this.moduleName; + this._config = {}; + } + + /** Patches DNS functions. */ + protected patch() { + this._logger.debug( + 'applying patch to %s@%s', + this.moduleName, + this.version + ); + + shimmer.wrap<{ lookup: LookupFunction }, 'lookup'>( + this._moduleExports, + 'lookup', + // tslint:disable-next-line:no-any + 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(this.version, '10.6.0')) { + shimmer.wrap( + this._moduleExports.promises, + 'lookup', + // tslint:disable-next-line:no-any + this._getLookup() as any + ); + } + + return this._moduleExports; + } + + /** Unpatches all DNS patched function. */ + protected unpatch(): void { + shimmer.unwrap(this._moduleExports, 'lookup'); + if (semver.gte(this.version, '10.6.0')) { + shimmer.unwrap(this._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, { + parent: plugin._tracer.getCurrentSpan() || undefined, + 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, () => + // tslint:disable-next-line:no-any + (original as LookupFunctionSignature).apply(this, [ + hostname, + ...args, + ] 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, plugin.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, this.component); + } + + /** + * 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, plugin.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, this.version); + span.end(); + throw error; + } + } +} +export const plugin = new DnsPlugin('dns', process.versions.node); diff --git a/packages/opentelemetry-plugin-dns/src/enums/AddressFamily.ts b/packages/opentelemetry-plugin-dns/src/enums/AddressFamily.ts new file mode 100644 index 0000000000..1dca88f7fe --- /dev/null +++ b/packages/opentelemetry-plugin-dns/src/enums/AddressFamily.ts @@ -0,0 +1,21 @@ +/*! + * Copyright 2019, 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/packages/opentelemetry-plugin-dns/src/enums/AttributeNames.ts b/packages/opentelemetry-plugin-dns/src/enums/AttributeNames.ts new file mode 100644 index 0000000000..96fa000e7d --- /dev/null +++ b/packages/opentelemetry-plugin-dns/src/enums/AttributeNames.ts @@ -0,0 +1,33 @@ +/*! + * Copyright 2019, 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. + */ + +/** + * Attributes Names according to Opencensus HTTP Specs since there is no specific OpenTelemetry Attributes + * https://github.com/open-telemetry/opentelemetry-specification/blob/master/work_in_progress/opencensus/HTTP.md#attributes + */ +export enum AttributeNames { + COMPONENT = 'component', + PEER_HOSTNAME = 'peer.hostname', + PEER_IPV4 = 'peer.ipv4', + PEER_IPV6 = 'peer.ipv6', + PEER_PORT = 'peer.port', + PEER_SERVICE = 'peer.service', + // NOT ON OFFICIAL SPEC + PEER_IPV0 = 'peer.ipv0', + DNS_ERROR_CODE = 'dns.error_code', + DNS_ERROR_NAME = 'dns.error_name', + DNS_ERROR_MESSAGE = 'dns.error_message', +} diff --git a/packages/opentelemetry-plugin-dns/src/index.ts b/packages/opentelemetry-plugin-dns/src/index.ts new file mode 100644 index 0000000000..ab0fd3142e --- /dev/null +++ b/packages/opentelemetry-plugin-dns/src/index.ts @@ -0,0 +1,20 @@ +/*! + * Copyright 2019, 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 * from './enums/AttributeNames'; +export * from './enums/AddressFamily'; +export * from './types'; diff --git a/packages/opentelemetry-plugin-dns/src/types.ts b/packages/opentelemetry-plugin-dns/src/types.ts new file mode 100644 index 0000000000..0f84de4f60 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/src/types.ts @@ -0,0 +1,100 @@ +/*! + * Copyright 2019, 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 { PluginConfig } from '@opentelemetry/types'; + +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 DnsPluginConfig extends PluginConfig { + ignoreHostnames?: IgnoreMatcher[]; +} diff --git a/packages/opentelemetry-plugin-dns/src/utils.ts b/packages/opentelemetry-plugin-dns/src/utils.ts new file mode 100644 index 0000000000..d2d1b2ce84 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/src/utils.ts @@ -0,0 +1,211 @@ +/*! + * Copyright 2019, 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, CanonicalCode, Status, Attributes } from '@opentelemetry/types'; +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('12')) { + attributes[AttributeNames.DNS_ERROR_CODE] = code!; + } + + span.setAttributes(attributes); + const status = parseErrorCode(code); + status.message = message; + span.setStatus(status); +}; + +/** + * 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 /** + * Parse the error code from DNS response. + * @param code the error code to parse + */ +const parseErrorCode = (code: string | undefined): Status => { + if (!code) { + return { code: CanonicalCode.UNKNOWN }; + } else { + switch (code) { + case dns.BADQUERY: + case dns.BADNAME: + case dns.BADFAMILY: + case dns.BADSTR: + case dns.BADFLAGS: + case dns.BADHINTS: + case dns.FORMERR: + case 'ERR_INVALID_OPT_VALUE': + case 'ERR_INVALID_ARG_TYPE': + case 'ERR_INVALID_ARG_VALUE': + case 'ERR_INVALID_ADDRESS_FAMILY': + case 'ERR_INVALID_CALLBACK': + case 'ERR_INVALID_IP_ADDRESS': + case 'ERR_INVALID_FILE_URL_HOST': + case 'ERR_INVALID_FILE_URL_PATH': + case 'ERR_MISSING_ARGS': + return { code: CanonicalCode.INVALID_ARGUMENT }; + case dns.BADRESP: + case dns.NODATA: + case dns.FILE: + case dns.NOMEM: + case dns.DESTRUCTION: + case dns.NONAME: + case dns.LOADIPHLPAPI: + case dns.ADDRGETNETWORKPARAMS: + return { code: CanonicalCode.INTERNAL }; + case dns.SERVFAIL: + case dns.NOTINITIALIZED: + case dns.CONNREFUSED: + return { code: CanonicalCode.UNAVAILABLE }; + case dns.NOTFOUND: + return { code: CanonicalCode.NOT_FOUND }; + case dns.NOTIMP: + return { code: CanonicalCode.UNIMPLEMENTED }; + case dns.REFUSED: + return { code: CanonicalCode.RESOURCE_EXHAUSTED }; + case dns.CANCELLED: + return { code: CanonicalCode.CANCELLED }; + case dns.TIMEOUT: + return { code: CanonicalCode.DEADLINE_EXCEEDED }; + case dns.EOF: + return { code: CanonicalCode.OUT_OF_RANGE }; + default: + return { code: CanonicalCode.UNKNOWN }; + } + } +}; + +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/packages/opentelemetry-plugin-dns/test/functionals/dns-disable.test.ts b/packages/opentelemetry-plugin-dns/test/functionals/dns-disable.test.ts new file mode 100644 index 0000000000..c3bd111b53 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/test/functionals/dns-disable.test.ts @@ -0,0 +1,66 @@ +/*! + * Copyright 2019, 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 { NoopLogger } from '@opentelemetry/core'; +import { NodeTracer } from '@opentelemetry/node'; +import { plugin } from '../../src/dns'; +import * as sinon from 'sinon'; +import * as dns from 'dns'; + +const memoryExporter = new InMemorySpanExporter(); +const logger = new NoopLogger(); +const tracer = new NodeTracer({ logger }); +tracer.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('DnsPlugin', () => { + before(() => { + plugin.enable(dns, tracer, tracer.logger); + 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 => { + plugin.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/packages/opentelemetry-plugin-dns/test/functionals/dns-enable.test.ts b/packages/opentelemetry-plugin-dns/test/functionals/dns-enable.test.ts new file mode 100644 index 0000000000..be6fde2d93 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/test/functionals/dns-enable.test.ts @@ -0,0 +1,44 @@ +/*! + * Copyright 2019, 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 { NoopLogger } from '@opentelemetry/core'; +import { NodeTracer } from '@opentelemetry/node'; +import { plugin, DnsPlugin } from '../../src/dns'; +import * as dns from 'dns'; + +const memoryExporter = new InMemorySpanExporter(); +const logger = new NoopLogger(); +const tracer = new NodeTracer({ logger }); +tracer.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('DnsPlugin', () => { + before(() => { + plugin.enable(dns, tracer, tracer.logger); + }); + + after(() => { + plugin.disable(); + }); + + it('should return a plugin', () => { + assert.ok(plugin instanceof DnsPlugin); + }); +}); diff --git a/packages/opentelemetry-plugin-dns/test/functionals/utils.test.ts b/packages/opentelemetry-plugin-dns/test/functionals/utils.test.ts new file mode 100644 index 0000000000..8bda076750 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/test/functionals/utils.test.ts @@ -0,0 +1,179 @@ +/*! + * Copyright 2019, 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 assert from 'assert'; +import * as sinon from 'sinon'; +import { CanonicalCode, SpanKind } from '@opentelemetry/types'; +import { IgnoreMatcher } from '../../src/types'; +import * as utils from '../../src/utils'; +import { Span, BasicTracer } from '@opentelemetry/tracing'; +import { NoopLogger } from '@opentelemetry/core'; +import { AttributeNames } from '../../src/enums/AttributeNames'; + +describe('Utility', () => { + describe('parseResponseStatus()', () => { + it('should return UNKNOWN code by default', () => { + [(undefined as unknown) as string, '', 'DSHKJSAD'].forEach(code => { + const status = utils.parseErrorCode(code); + assert.deepStrictEqual(status, { code: CanonicalCode.UNKNOWN }); + }); + }); + }); + + 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 BasicTracer(), + 'test', + { spanId: '', traceId: '' }, + SpanKind.INTERNAL + ); + utils.setError(new Error(errorMessage), span, process.versions.node); + const attributes = span.toReadableSpan().attributes; + assert.strictEqual( + attributes[AttributeNames.DNS_ERROR_MESSAGE], + errorMessage + ); + assert.ok(attributes[AttributeNames.DNS_ERROR_NAME]); + }); + }); +}); diff --git a/packages/opentelemetry-plugin-dns/test/integrations/dns-lookup.test.ts b/packages/opentelemetry-plugin-dns/test/integrations/dns-lookup.test.ts new file mode 100644 index 0000000000..05ba0effb4 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/test/integrations/dns-lookup.test.ts @@ -0,0 +1,221 @@ +/*! + * Copyright 2019, 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 { NoopLogger } from '@opentelemetry/core'; +import { NodeTracer } from '@opentelemetry/node'; +import { plugin } from '../../src/dns'; +import * as dns from 'dns'; +import * as utils from '../utils/utils'; +import { assertSpan } from '../utils/assertSpan'; +import { CanonicalCode } from '@opentelemetry/types'; + +const memoryExporter = new InMemorySpanExporter(); +const logger = new NoopLogger(); +const tracer = new NodeTracer({ logger }); +tracer.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('dns.lookup()', () => { + before(function(done) { + // mandatory + if (process.env.CI) { + plugin.enable(dns, tracer, tracer.logger); + done(); + return; + } + + utils.checkInternet(isConnected => { + if (!isConnected) { + this.skip(); + // don't disturbe people + } + done(); + }); + plugin.enable(dns, tracer, tracer.logger); + }); + + afterEach(() => { + memoryExporter.reset(); + }); + + after(() => { + plugin.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: CanonicalCode.NOT_FOUND, + 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: process.versions.node.startsWith('8') + ? CanonicalCode.UNKNOWN + : CanonicalCode.INVALID_ARGUMENT, + 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: process.versions.node.startsWith('8') + ? CanonicalCode.UNKNOWN + : CanonicalCode.INVALID_ARGUMENT, + 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/packages/opentelemetry-plugin-dns/test/integrations/dnspromise-lookup.test.ts b/packages/opentelemetry-plugin-dns/test/integrations/dnspromise-lookup.test.ts new file mode 100644 index 0000000000..9856985e72 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/test/integrations/dnspromise-lookup.test.ts @@ -0,0 +1,216 @@ +/*! + * Copyright 2019, 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 { NoopLogger } from '@opentelemetry/core'; +import { NodeTracer } from '@opentelemetry/node'; +import { plugin } from '../../src/dns'; +import * as dns from 'dns'; +import * as utils from '../utils/utils'; +import * as semver from 'semver'; +import { assertSpan } from '../utils/assertSpan'; +import { CanonicalCode } from '@opentelemetry/types'; + +const memoryExporter = new InMemorySpanExporter(); +const logger = new NoopLogger(); +const tracer = new NodeTracer({ logger }); +tracer.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('dns.promises.lookup()', () => { + before(function(done) { + // skip tests if node version is not supported + if (semver.lte(process.versions.node, '10.6.0')) { + this.skip(); + done(); + return; + } + + // if node version is supported, it's mandatory for CI + if (process.env.CI) { + plugin.enable(dns, tracer, tracer.logger); + done(); + return; + } + + utils.checkInternet(isConnected => { + if (!isConnected) { + this.skip(); + // don't disturbe people + } + done(); + }); + plugin.enable(dns, tracer, tracer.logger); + }); + + afterEach(() => { + memoryExporter.reset(); + }); + + after(() => { + plugin.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 dns.promises.lookup( + hostname, + 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 dns.promises.lookup(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 dns.promises.lookup(hostname); + assert.fail(); + } catch (error) { + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + + assert.strictEqual(spans.length, 1); + assertSpan(span, { + addresses: [], + hostname, + forceStatus: { + code: CanonicalCode.NOT_FOUND, + 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 dns.promises.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: CanonicalCode.INVALID_ARGUMENT, + 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 dns.promises.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: CanonicalCode.INVALID_ARGUMENT, + 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 dns.promises.lookup(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 dns.promises.lookup(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 dns.promises.lookup(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/packages/opentelemetry-plugin-dns/test/utils/assertSpan.ts b/packages/opentelemetry-plugin-dns/test/utils/assertSpan.ts new file mode 100644 index 0000000000..dc8df543dd --- /dev/null +++ b/packages/opentelemetry-plugin-dns/test/utils/assertSpan.ts @@ -0,0 +1,69 @@ +/*! + * Copyright 2019, 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, CanonicalCode } from '@opentelemetry/types'; +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], '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: CanonicalCode.OK } + ); + + assert.ok(hrTimeToNanoseconds(span.duration), 'must have positive duration'); +}; diff --git a/packages/opentelemetry-plugin-dns/test/utils/utils.ts b/packages/opentelemetry-plugin-dns/test/utils/utils.ts new file mode 100644 index 0000000000..57a75516a1 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/test/utils/utils.ts @@ -0,0 +1,27 @@ +/*! + * Copyright 2019, 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/packages/opentelemetry-plugin-dns/tsconfig.json b/packages/opentelemetry-plugin-dns/tsconfig.json new file mode 100644 index 0000000000..a2042cd68b --- /dev/null +++ b/packages/opentelemetry-plugin-dns/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} diff --git a/packages/opentelemetry-plugin-dns/tslint.json b/packages/opentelemetry-plugin-dns/tslint.json new file mode 100644 index 0000000000..0710b135d0 --- /dev/null +++ b/packages/opentelemetry-plugin-dns/tslint.json @@ -0,0 +1,4 @@ +{ + "rulesDirectory": ["node_modules/tslint-microsoft-contrib"], + "extends": ["../../tslint.base.js", "./node_modules/tslint-consistent-codestyle"] +}