diff --git a/examples/koa/README.md b/examples/koa/README.md new file mode 100644 index 0000000000..194542b9e7 --- /dev/null +++ b/examples/koa/README.md @@ -0,0 +1,76 @@ +# Overview + +OpenTelemetry Koa 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 calls made in a Koa application. The example +shows key aspects of tracing such as +- Root Span (on Client) +- Child Span (on Client) +- Span Events +- 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 server + + ```sh + # from this directory + $ npm run zipkin:server + ``` + + - Run the client + + ```sh + # from this directory + npm run zipkin:client + ``` + +#### Zipkin UI +`zipkin:server` 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 server + + ```sh + # from this directory + $ npm run jaeger:server + ``` + + - Run the client + + ```sh + # from this directory + npm run jaeger:client + ``` + +#### Jaeger UI + +`jaeger:server` 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/koa/client.js b/examples/koa/client.js new file mode 100644 index 0000000000..26ba69ea48 --- /dev/null +++ b/examples/koa/client.js @@ -0,0 +1,28 @@ +'use strict'; + +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-koa-client'); +const api = require('@opentelemetry/api'); +const axios = require('axios').default; + +function makeRequest() { + const span = tracer.startSpan('client.makeRequest()', { + parent: tracer.getCurrentSpan(), + kind: api.SpanKind.CLIENT, + }); + + tracer.withSpan(span, async () => { + try { + const res = await axios.get('http://localhost:8081/run_test'); + span.setStatus({ code: api.CanonicalCode.OK }); + console.log(res.statusText); + } catch (e) { + span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e.message }); + } + span.end(); + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); + setTimeout(() => { console.log('Completed.'); }, 5000); + }); +} + +makeRequest(); diff --git a/examples/koa/images/jaeger.jpg b/examples/koa/images/jaeger.jpg new file mode 100644 index 0000000000..a4fd826d6a Binary files /dev/null and b/examples/koa/images/jaeger.jpg differ diff --git a/examples/koa/images/zipkin.jpg b/examples/koa/images/zipkin.jpg new file mode 100644 index 0000000000..5f6fea25d4 Binary files /dev/null and b/examples/koa/images/zipkin.jpg differ diff --git a/examples/koa/package.json b/examples/koa/package.json new file mode 100644 index 0000000000..23a3c5197a --- /dev/null +++ b/examples/koa/package.json @@ -0,0 +1,50 @@ +{ + "name": "koa-example", + "private": true, + "version": "0.9.0", + "description": "Example of Koa and @koa/router integration with OpenTelemetry", + "main": "index.js", + "scripts": { + "zipkin:server": "cross-env EXPORTER=zipkin node ./server.js", + "zipkin:client": "cross-env EXPORTER=zipkin node ./client.js", + "jaeger:server": "cross-env EXPORTER=jaeger node ./server.js", + "jaeger:client": "cross-env EXPORTER=jaeger node ./client.js", + "lint": "eslint . --ext .js", + "lint:fix": "eslint . --ext .js --fix" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js-contrib.git" + }, + "keywords": [ + "opentelemetry", + "koa", + "tracing", + "instrumentation" + ], + "engines": { + "node": ">=8" + }, + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/open-telemetry/opentelemetry-js-contrib/issues" + }, + "dependencies": { + "@koa/router": "^9.3.1", + "@opentelemetry/api": "^0.10.2", + "@opentelemetry/exporter-jaeger": "^0.10.2", + "@opentelemetry/exporter-zipkin": "^0.10.2", + "@opentelemetry/node": "^0.10.2", + "@opentelemetry/plugin-http": "^0.10.2", + "@opentelemetry/koa-instrumentation": "^0.9.0", + "@opentelemetry/tracing": "^0.10.2", + "axios": "^0.19.0", + "koa": "^2.13.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib#readme", + "devDependencies": { + "cross-env": "^6.0.0", + "eslint": "^7.4.0" + } +} diff --git a/examples/koa/server.js b/examples/koa/server.js new file mode 100644 index 0000000000..7bd3a1b2f1 --- /dev/null +++ b/examples/koa/server.js @@ -0,0 +1,69 @@ +'use strict'; + +// eslint-disable-next-line +const tracer = require('./tracer')('example-koa-server'); + +// Adding Koa router (if desired) +const router = require('@koa/router')(); +const Koa = require('koa'); + +// Setup koa +const app = new Koa(); +const PORT = 8081; + +// route definitions +router.get('/run_test', runTest) + .get('/post/new', addPost) + .get('/post/:id', showNewPost); + +async function setUp() { + app.use(noOp); + app.use(router.routes()); +} + +/** + * Router functions: list, add, or show posts +*/ +const posts = ['post 0', 'post 1', 'post 2']; + +function addPost(ctx) { + posts.push(`post ${posts.length}`); + const currentSpan = tracer.getCurrentSpan(); + currentSpan.addEvent('Added post'); + currentSpan.setAttribute('Date', new Date()); + ctx.body = `Added post: ${posts[posts.length - 1]}`; + ctx.redirect('/post/3'); +} + +async function showNewPost(ctx) { + const { id } = ctx.params; + console.log(`showNewPost with id: ${id}`); + const post = posts[id]; + if (!post) ctx.throw(404, 'Invalid post id'); + const syntheticDelay = 500; + await new Promise((r) => setTimeout(r, syntheticDelay)); + ctx.body = post; +} + +function runTest(ctx) { + console.log('runTest'); + const currentSpan = tracer.getCurrentSpan(); + const { traceId } = currentSpan.context(); + console.log(`traceid: ${traceId}`); + console.log(`Jaeger URL: http://localhost:16686/trace/${traceId}`); + console.log(`Zipkin URL: http://localhost:9411/zipkin/traces/${traceId}`); + ctx.body = `All posts: ${posts}`; + ctx.redirect('/post/new'); +} + +async function noOp(ctx, next) { + console.log('Sample basic koa middleware'); + const syntheticDelay = 100; + await new Promise((r) => setTimeout(r, syntheticDelay)); + next(); +} + +setUp().then(() => { + app.listen(PORT); + console.log(`Listening on http://localhost:${PORT}`); +}); diff --git a/examples/koa/tracer.js b/examples/koa/tracer.js new file mode 100644 index 0000000000..fec566dd21 --- /dev/null +++ b/examples/koa/tracer.js @@ -0,0 +1,38 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/api'); +const { NodeTracerProvider } = 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 || ''; + +module.exports = (serviceName) => { + const provider = new NodeTracerProvider({ + plugins: { + koa: { + enabled: true, + path: '@opentelemetry/koa-instrumentation', + enhancedDatabaseReporting: true, + }, + http: { + enabled: true, + path: '@opentelemetry/plugin-http', + }, + }, + }); + + let exporter; + if (EXPORTER === 'jaeger') { + exporter = new JaegerExporter({ serviceName }); + } else { + exporter = new ZipkinExporter({ serviceName }); + } + provider.addSpanProcessor(new SimpleSpanProcessor(exporter)); + + // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings + provider.register(); + + return opentelemetry.trace.getTracer('koa-example'); +}; diff --git a/plugins/node/opentelemetry-koa-instrumentation/.eslintignore b/plugins/node/opentelemetry-koa-instrumentation/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-koa-instrumentation/.eslintrc.js b/plugins/node/opentelemetry-koa-instrumentation/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-koa-instrumentation/.npmignore b/plugins/node/opentelemetry-koa-instrumentation/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/opentelemetry-koa-instrumentation/LICENSE b/plugins/node/opentelemetry-koa-instrumentation/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/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-koa-instrumentation/README.md b/plugins/node/opentelemetry-koa-instrumentation/README.md new file mode 100644 index 0000000000..e1f17a9acb --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/README.md @@ -0,0 +1,68 @@ +# OpenTelemetry Koa 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 [`Koa`](https://github.com/koajs/koa). + +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/koa-instrumentation +``` +### Supported Versions + - Koa `^2.0.0` + +## Usage + +OpenTelemetry Koa Instrumentation allows the user to automatically collect trace data and export them to their backend of choice, to give observability to distributed systems. + +To load a specific instrumentation (Koa in this case), specify it in the Node Tracer's configuration. +```js +const { NodeTracerProvider } = require('@opentelemetry/node'); + +const provider = new NodeTracerProvider({ + plugins: { + koa: { + enabled: true, + // You may use a package name or absolute path to the file. + path: '@opentelemetry/koa-instrumentation', + } + } +}); +``` + +To load all of the [supported instrumentations](https://github.com/open-telemetry/opentelemetry-js#plugins), use below approach. Each instrumentation is only loaded when the module that it patches is loaded; in other words, there is no computational overhead for listing instrumentations for unused modules. +```js +const { NodeTracerProvider } = require('@opentelemetry/node'); + +const provider = new NodeTracerProvider(); +``` + +See [examples/koa](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/master/examples/koa) for a short example using both Koa and @koa/router + +## Koa Packages + +This package provides automatic tracing for middleware added using either the core [`Koa`](https://github.com/koajs/koa) package or the [`@koa/router`](https://github.com/koajs/router) package. + +## 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-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-contrib/status.svg?path=plugins/node/opentelemetry-koa-instrumentation +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins/node/opentelemetry-koa-instrumentation +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=plugins/node/opentelemetry-koa-instrumentation +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins/node/opentelemetry-koa-instrumentation&type=dev diff --git a/plugins/node/opentelemetry-koa-instrumentation/package.json b/plugins/node/opentelemetry-koa-instrumentation/package.json new file mode 100644 index 0000000000..7479e38697 --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/package.json @@ -0,0 +1,74 @@ +{ + "name": "@opentelemetry/koa-instrumentation", + "version": "0.9.0", + "description": "OpenTelemetry Koa automatic instrumentation package.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js-contrib", + "scripts": { + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.ts'", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "tdd": "yarn test -- --watch-extensions ts --watch", + "clean": "rimraf build/*", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "precompile": "tsc --version", + "version:update": "node ../../../scripts/version-update.js", + "compile": "npm run version:update && tsc -p .", + "prepare": "npm run compile" + }, + "keywords": [ + "opentelemetry", + "koa", + "nodejs", + "tracing", + "profiling", + "plugin", + "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": { + "@koa/router": "^9.3.1", + "@opentelemetry/context-async-hooks": "0.10.2", + "@opentelemetry/node": "0.10.2", + "@opentelemetry/tracing": "0.10.2", + "@types/koa": "^2.11.3", + "@types/koa__router": "^8.0.2", + "@types/mocha": "7.0.2", + "@types/node": "12.12.47", + "@types/shimmer": "1.0.1", + "codecov": "3.7.1", + "eslint": "^7.6.0", + "eslint-plugin-header": "^3.0.0", + "gts": "2.0.2", + "koa": "^2.13.0", + "mocha": "7.2.0", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "ts-mocha": "7.0.0", + "ts-node": "8.10.2", + "tslint-consistent-codestyle": "1.16.0", + "tslint-microsoft-contrib": "6.2.0", + "typescript": "3.9.6" + }, + "dependencies": { + "@opentelemetry/api": "^0.10.2", + "@opentelemetry/core": "^0.10.2", + "@opentelemetry/semantic-conventions": "^0.10.2", + "shimmer": "^1.2.1" + } +} diff --git a/plugins/node/opentelemetry-koa-instrumentation/src/index.ts b/plugins/node/opentelemetry-koa-instrumentation/src/index.ts new file mode 100644 index 0000000000..a1c84a557f --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/src/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './koa'; diff --git a/plugins/node/opentelemetry-koa-instrumentation/src/koa.ts b/plugins/node/opentelemetry-koa-instrumentation/src/koa.ts new file mode 100644 index 0000000000..73fe921f76 --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/src/koa.ts @@ -0,0 +1,139 @@ +/* + * 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 { BasePlugin } from '@opentelemetry/core'; +import type * as koa from 'koa'; +import * as shimmer from 'shimmer'; +import { + KoaMiddleware, + KoaContext, + KoaComponentName, + kLayerPatched, +} from './types'; +import { VERSION } from './version'; +import { getMiddlewareMetadata } from './utils'; + +/** Koa instrumentation for OpenTelemetry */ +export class KoaInstrumentation extends BasePlugin { + static readonly component = KoaComponentName; + readonly supportedVersions = ['^2.0.0']; + + constructor(readonly moduleName: string) { + super('@opentelemetry/koa-instrumentation', VERSION); + } + + /** + * Patches Koa operations by wrapping the Koa.use function + */ + protected patch(): typeof koa { + this._logger.debug('Patching Koa'); + if (this._moduleExports == null) { + return this._moduleExports; + } + this._logger.debug('Patching Koa.use'); + shimmer.wrap(this._moduleExports.prototype, 'use', this._getKoaUsePatch); + + return this._moduleExports; + } + + /** + * Unpatches all Koa operations + */ + protected unpatch(): void { + this._logger.debug('Unpatching Koa'); + shimmer.unwrap(this._moduleExports.prototype, 'use'); + } + + /** + * Patches the Koa.use function in order to instrument each original + * middleware layer which is introduced + * @param {KoaMiddleware} middleware - the original middleware function + */ + private _getKoaUsePatch(original: (middleware: KoaMiddleware) => koa) { + return function use(this: koa, middlewareFunction: KoaMiddleware) { + let patchedFunction: KoaMiddleware; + if (middlewareFunction.router) { + patchedFunction = plugin._patchRouterDispatch(middlewareFunction); + } else { + patchedFunction = plugin._patchLayer(middlewareFunction, false); + } + return original.apply(this, [patchedFunction]); + }; + } + + /** + * Patches the dispatch function used by @koa/router. This function + * goes through each routed middleware and adds instrumentation via a call + * to the @function _patchLayer function. + * @param {KoaMiddleware} dispatchLayer - the original dispatch function which dispatches + * routed middleware + */ + private _patchRouterDispatch(dispatchLayer: KoaMiddleware): KoaMiddleware { + this._logger.debug('Patching @koa/router dispatch'); + + const router = dispatchLayer.router; + + const routesStack = router?.stack ?? []; + for (const pathLayer of routesStack) { + const path = pathLayer.path; + const pathStack = pathLayer.stack; + for (let j = 0; j < pathStack.length; j++) { + const routedMiddleware: KoaMiddleware = pathStack[j]; + pathStack[j] = this._patchLayer(routedMiddleware, true, path); + } + } + + return dispatchLayer; + } + + /** + * Patches each individual @param middlewareLayer function in order to create the + * span and propagate context. It does not create spans when there is no parent span. + * @param {KoaMiddleware} middlewareLayer - the original middleware function. + * @param {boolean} isRouter - tracks whether the original middleware function + * was dispatched by the router originally + * @param {string?} layerPath - if present, provides additional data from the + * router about the routed path which the middleware is attached to + */ + private _patchLayer( + middlewareLayer: KoaMiddleware, + isRouter: boolean, + layerPath?: string + ): KoaMiddleware { + if (middlewareLayer[kLayerPatched] === true) return middlewareLayer; + middlewareLayer[kLayerPatched] = true; + this._logger.debug('patching Koa middleware layer'); + return async (context: KoaContext, next: koa.Next) => { + if (this._tracer.getCurrentSpan() === undefined) { + return middlewareLayer(context, next); + } + const metadata = getMiddlewareMetadata( + context, + middlewareLayer, + isRouter, + layerPath + ); + const span = this._tracer.startSpan(metadata.name, { + attributes: metadata.attributes, + }); + const result = await middlewareLayer(context, next); + span.end(); + return result; + }; + } +} + +export const plugin = new KoaInstrumentation(KoaComponentName); diff --git a/plugins/node/opentelemetry-koa-instrumentation/src/types.ts b/plugins/node/opentelemetry-koa-instrumentation/src/types.ts new file mode 100644 index 0000000000..4e3db9307c --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/src/types.ts @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { Middleware, ParameterizedContext, DefaultState } from 'koa'; +import type { RouterParamContext } from '@koa/router'; +import type * as Router from '@koa/router'; + +/** + * This symbol is used to mark a Koa layer as being already instrumented + * since its possible to use a given layer multiple times (ex: middlewares) + */ +export const kLayerPatched: unique symbol = Symbol('koa-layer-patched'); + +export type KoaMiddleware = Middleware & { + [kLayerPatched]?: boolean; + router?: Router; +}; + +export type KoaContext = ParameterizedContext; + +export enum AttributeNames { + KOA_TYPE = 'koa.type', + KOA_NAME = 'koa.name', +} + +export enum KoaLayerType { + ROUTER = 'router', + MIDDLEWARE = 'middleware', +} + +export const KoaComponentName = 'koa'; diff --git a/plugins/node/opentelemetry-koa-instrumentation/src/utils.ts b/plugins/node/opentelemetry-koa-instrumentation/src/utils.ts new file mode 100644 index 0000000000..148cfcbec4 --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/src/utils.ts @@ -0,0 +1,52 @@ +/* + * 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 { + AttributeNames, + KoaContext, + KoaMiddleware, + KoaLayerType, +} from './types'; +import { Attributes } from '@opentelemetry/api'; +import { HttpAttribute } from '@opentelemetry/semantic-conventions'; + +export const getMiddlewareMetadata = ( + context: KoaContext, + layer: KoaMiddleware, + isRouter: boolean, + layerPath?: string +): { + attributes: Attributes; + name: string; +} => { + if (isRouter) { + return { + attributes: { + [AttributeNames.KOA_NAME]: layerPath, + [AttributeNames.KOA_TYPE]: KoaLayerType.ROUTER, + [HttpAttribute.HTTP_ROUTE]: layerPath, + }, + name: `router - ${layerPath}`, + }; + } else { + return { + attributes: { + [AttributeNames.KOA_NAME]: layer.name ?? 'middleware', + [AttributeNames.KOA_TYPE]: KoaLayerType.MIDDLEWARE, + }, + name: `middleware - ${layer.name}`, + }; + } +}; diff --git a/plugins/node/opentelemetry-koa-instrumentation/src/version.ts b/plugins/node/opentelemetry-koa-instrumentation/src/version.ts new file mode 100644 index 0000000000..d42e22554c --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/src/version.ts @@ -0,0 +1,16 @@ +/* + * 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 const VERSION = '0.9.0'; diff --git a/plugins/node/opentelemetry-koa-instrumentation/test/koa-router.test.ts b/plugins/node/opentelemetry-koa-instrumentation/test/koa-router.test.ts new file mode 100644 index 0000000000..0a93852cf8 --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/test/koa-router.test.ts @@ -0,0 +1,203 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { context } from '@opentelemetry/api'; +import { NoopLogger } from '@opentelemetry/core'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import * as koa from 'koa'; +import * as KoaRouter from '@koa/router'; +import * as http from 'http'; +import { AddressInfo } from 'net'; +import { plugin } from '../src'; +import { AttributeNames, KoaLayerType } from '../src/types'; +import { HttpAttribute } from '@opentelemetry/semantic-conventions'; + +const httpRequest = { + get: (options: http.ClientRequestArgs | string) => { + return new Promise((resolve, reject) => { + return http.get(options, resp => { + let data = ''; + resp.on('data', chunk => { + data += chunk; + }); + resp.on('end', () => { + resolve(data); + }); + resp.on('error', err => { + reject(err); + }); + }); + }); + }, +}; + +describe('Koa Instrumentation - Router Tests', () => { + const logger = new NoopLogger(); + const provider = new NodeTracerProvider(); + const memoryExporter = new InMemorySpanExporter(); + const spanProcessor = new SimpleSpanProcessor(memoryExporter); + provider.addSpanProcessor(spanProcessor); + const tracer = provider.getTracer('default'); + let contextManager: AsyncHooksContextManager; + let app: koa; + let server: http.Server; + let port: number; + + before(() => { + plugin.enable(koa, provider, logger); + }); + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + + app = new koa(); + server = http.createServer(app.callback()); + await new Promise(resolve => server.listen(0, resolve)); + port = (server.address() as AddressInfo).port; + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + + afterEach(() => { + memoryExporter.reset(); + context.disable(); + server.close(); + }); + + describe('Instrumenting @koa/router calls', () => { + it('should create a child span for middlewares', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + app.use((ctx, next) => tracer.withSpan(rootSpan, next)); + + const router = new KoaRouter(); + router.get('/post/:id', ctx => { + ctx.body = `Post id: ${ctx.params.id}`; + }); + + app.use(router.routes()); + + await tracer.withSpan(rootSpan, async () => { + await httpRequest.get(`http://localhost:${port}/post/0`); + rootSpan.end(); + + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name.includes('router - /post/:id')); + assert.notStrictEqual(requestHandlerSpan, undefined); + + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.KOA_TYPE], + KoaLayerType.ROUTER + ); + + assert.strictEqual( + requestHandlerSpan?.attributes[HttpAttribute.HTTP_ROUTE], + '/post/:id' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should correctly instrument nested routers', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + app.use((ctx, next) => tracer.withSpan(rootSpan, next)); + + const router = new KoaRouter(); + const nestedRouter = new KoaRouter(); + nestedRouter.get('/post/:id', ctx => { + ctx.body = `Post id: ${ctx.params.id}`; + }); + + router.use('/:first', nestedRouter.routes()); + app.use(router.routes()); + + await tracer.withSpan(rootSpan, async () => { + await httpRequest.get(`http://localhost:${port}/test/post/0`); + rootSpan.end(); + + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name.includes('router - /:first/post/:id')); + assert.notStrictEqual(requestHandlerSpan, undefined); + + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.KOA_TYPE], + KoaLayerType.ROUTER + ); + + assert.strictEqual( + requestHandlerSpan?.attributes[HttpAttribute.HTTP_ROUTE], + '/:first/post/:id' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should correctly instrument prefixed routers', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + app.use((ctx, next) => tracer.withSpan(rootSpan, next)); + + const router = new KoaRouter(); + router.get('/post/:id', ctx => { + ctx.body = `Post id: ${ctx.params.id}`; + }); + router.prefix('/:first'); + app.use(router.routes()); + + await tracer.withSpan(rootSpan, async () => { + await httpRequest.get(`http://localhost:${port}/test/post/0`); + rootSpan.end(); + + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name.includes('router - /:first/post/:id')); + assert.notStrictEqual(requestHandlerSpan, undefined); + + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.KOA_TYPE], + KoaLayerType.ROUTER + ); + + assert.strictEqual( + requestHandlerSpan?.attributes[HttpAttribute.HTTP_ROUTE], + '/:first/post/:id' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-koa-instrumentation/test/koa.test.ts b/plugins/node/opentelemetry-koa-instrumentation/test/koa.test.ts new file mode 100644 index 0000000000..df90119227 --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/test/koa.test.ts @@ -0,0 +1,193 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { context } from '@opentelemetry/api'; +import { NoopLogger } from '@opentelemetry/core'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import * as koa from 'koa'; +import * as http from 'http'; +import { AddressInfo } from 'net'; +import { plugin } from '../src'; +import { AttributeNames, KoaLayerType } from '../src/types'; + +const httpRequest = { + get: (options: http.ClientRequestArgs | string) => { + return new Promise((resolve, reject) => { + return http.get(options, resp => { + let data = ''; + resp.on('data', chunk => { + data += chunk; + }); + resp.on('end', () => { + resolve(data); + }); + resp.on('error', err => { + reject(err); + }); + }); + }); + }, +}; + +describe('Koa Instrumentation - Core Tests', () => { + const logger = new NoopLogger(); + const provider = new NodeTracerProvider(); + const memoryExporter = new InMemorySpanExporter(); + const spanProcessor = new SimpleSpanProcessor(memoryExporter); + provider.addSpanProcessor(spanProcessor); + const tracer = provider.getTracer('default'); + let contextManager: AsyncHooksContextManager; + let app: koa; + let server: http.Server; + let port: number; + + before(() => { + plugin.enable(koa, provider, logger); + }); + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + + app = new koa(); + server = http.createServer(app.callback()); + await new Promise(resolve => server.listen(0, resolve)); + port = (server.address() as AddressInfo).port; + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + + afterEach(() => { + memoryExporter.reset(); + context.disable(); + server.close(); + }); + + const simpleResponse: koa.Middleware = async (ctx, next) => { + ctx.body = 'test'; + await next(); + }; + + const customMiddleware: koa.Middleware = async (ctx, next) => { + for (let i = 0; i < 1000000; i++) { + continue; + } + await next(); + }; + + const asyncMiddleware: koa.Middleware = async (ctx, next) => { + const start = Date.now(); + await next(); + const ms = Date.now() - start; + ctx.body = `${ctx.method} ${ctx.url} - ${ms}ms`; + }; + + describe('Instrumenting core middleware calls', () => { + it('should create a child span for middlewares', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + app.use((ctx, next) => tracer.withSpan(rootSpan, next)); + app.use(customMiddleware); + app.use(simpleResponse); + + await tracer.withSpan(rootSpan, async () => { + await httpRequest.get(`http://localhost:${port}`); + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 5); + + assert.notStrictEqual( + memoryExporter + .getFinishedSpans() + .find(span => span.name.includes('customMiddleware')), + undefined + ); + + const simpleResponseSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name.includes('simpleResponse')); + assert.notStrictEqual(simpleResponseSpan, undefined); + + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name.includes('middleware')); + assert.notStrictEqual(requestHandlerSpan, undefined); + + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.KOA_TYPE], + KoaLayerType.MIDDLEWARE + ); + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should not create span if there is no parent span', async () => { + app.use(customMiddleware); + app.use(simpleResponse); + + const res = await httpRequest.get(`http://localhost:${port}`); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + assert.strictEqual(res, 'test'); + }); + + it('should handle async middleware functions', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + app.use((ctx, next) => tracer.withSpan(rootSpan, next)); + app.use(asyncMiddleware); + + await tracer.withSpan(rootSpan, async () => { + await httpRequest.get(`http://localhost:${port}`); + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name.includes('asyncMiddleware')); + assert.notStrictEqual(requestHandlerSpan, undefined); + + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.KOA_TYPE], + KoaLayerType.MIDDLEWARE + ); + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + }); + + describe('Disabling koa instrumentation', () => { + it('should not create new spans', async () => { + plugin.disable(); + const rootSpan = tracer.startSpan('rootSpan'); + app.use(customMiddleware); + + await tracer.withSpan(rootSpan, async () => { + await httpRequest.get(`http://localhost:${port}`); + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 1); + assert.notStrictEqual(memoryExporter.getFinishedSpans()[0], undefined); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-koa-instrumentation/tsconfig.json b/plugins/node/opentelemetry-koa-instrumentation/tsconfig.json new file mode 100644 index 0000000000..ec22e03b9e --- /dev/null +++ b/plugins/node/opentelemetry-koa-instrumentation/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] + }