diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml index c60700cfa8..35f3207bd6 100644 --- a/.github/workflows/unit-test.yml +++ b/.github/workflows/unit-test.yml @@ -14,10 +14,28 @@ jobs: container: image: ${{ matrix.container }} services: + memcached: + image: memcached:1.6.9-alpine + ports: + - 11211:11211 mongo: image: mongo ports: - 27017:27017 + mysql: + image: circleci/mysql:5.7 + env: + MYSQL_USER: otel + MYSQL_PASSWORD: secret + MYSQL_DATABASE: circle_database + MYSQL_ROOT_PASSWORD: rootpw + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 postgres: image: circleci/postgres:9.6-alpine env: @@ -39,25 +57,14 @@ jobs: --health-interval 10s --health-timeout 5s --health-retries 5 - mysql: - image: circleci/mysql:5.7 - env: - MYSQL_USER: otel - MYSQL_PASSWORD: secret - MYSQL_DATABASE: circle_database - MYSQL_ROOT_PASSWORD: rootpw - ports: - - 3306:3306 - options: >- - --health-cmd="mysqladmin ping" - --health-interval 10s - --health-timeout 5s - --health-retries 5 env: - RUN_POSTGRES_TESTS: 1 - RUN_MYSQL_TESTS: 1 + RUN_MEMCACHED_TESTS: 1 RUN_MONGODB_TESTS: 1 + RUN_MYSQL_TESTS: 1 + RUN_POSTGRES_TESTS: 1 RUN_REDIS_TESTS: 1 + OPENTELEMETRY_MEMCACHED_HOST: memcached + OPENTELEMETRY_MEMCACHED_PORT: 11211 POSTGRES_USER: postgres POSTGRES_DB: circle_database POSTGRES_HOST: postgres diff --git a/examples/memcached/README.md b/examples/memcached/README.md new file mode 100644 index 0000000000..7b535b784b --- /dev/null +++ b/examples/memcached/README.md @@ -0,0 +1,18 @@ +# Overview + +OpenTelemetry Memcached instrumentation allows user to automatically collect trace data from queries made by the client and export them to the backend of choice. This example does not showcase export functionality, but there are numerous other examples doing that: [`express`](../express), [`router`](../router). + +## Running the Example + +Created spans are printed out to stdout while running the example. + +```sh +npm install # install the dependencies +npm run docker:start # start memcached server +npm run start # run the example +npm run docker:stop # spin down and clean up the docker container +``` + +## LICENSE + +Apache License 2.0 diff --git a/examples/memcached/index.js b/examples/memcached/index.js new file mode 100644 index 0000000000..d25c2bc0db --- /dev/null +++ b/examples/memcached/index.js @@ -0,0 +1,20 @@ +'use strict'; + +require('./tracer')('example-resource'); +const Memcached = require('memcached'); +const assert = require('assert'); + +const KEY = '_KEY_'; +const VALUE = `RAND:${Math.random().toFixed(4)}`; +const LT = 10; +const client = new Memcached(); + +client.set(KEY, VALUE, LT, (err) => { + assert.strictEqual(err, undefined); + client.get(KEY, (err, result) => { + assert.strictEqual(err, undefined); + assert.strictEqual(result, VALUE); + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); + setTimeout(() => { console.log('Completed.'); }, 5000); + }); +}); diff --git a/examples/memcached/package.json b/examples/memcached/package.json new file mode 100644 index 0000000000..471ae56dbe --- /dev/null +++ b/examples/memcached/package.json @@ -0,0 +1,39 @@ +{ + "name": "memcached-example", + "private": true, + "version": "0.22.0", + "description": "Example of Memcached client with OpenTelemetry", + "main": "index.js", + "scripts": { + "docker:start": "docker run --rm -d --name otel-memcached -p 11211:11211 memcached:1.6.9-alpine", + "docker:stop": "docker rm -f otel-memcached", + "start": "node index.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js-contrib.git" + }, + "keywords": [ + "opentelemetry", + "instrumentation", + "memcached", + "tracing" + ], + "engines": { + "node": ">=8.5.0" + }, + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/open-telemetry/opentelemetry-js-contrib/issues" + }, + "dependencies": { + "@opentelemetry/api": "^1.0.1", + "@opentelemetry/instrumentation": "^0.22.0", + "@opentelemetry/instrumentation-memcached": "^0.22.0", + "@opentelemetry/node": "^0.22.0", + "@opentelemetry/tracing": "^0.22.0", + "memcached": "^2.2.2" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib#readme" +} diff --git a/examples/memcached/tracer.js b/examples/memcached/tracer.js new file mode 100644 index 0000000000..b86bceb967 --- /dev/null +++ b/examples/memcached/tracer.js @@ -0,0 +1,37 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/api'); + +const { diag, DiagConsoleLogger, DiagLogLevel } = opentelemetry; +diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.VERBOSE); + +const { registerInstrumentations } = require('@opentelemetry/instrumentation'); +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { SimpleSpanProcessor, ConsoleSpanExporter } = require('@opentelemetry/tracing'); +const { Resource } = require('@opentelemetry/resources'); +const { ResourceAttributes } = require('@opentelemetry/semantic-conventions'); + +const { MemcachedInstrumentation } = require('@opentelemetry/instrumentation-memcached'); + +module.exports = (serviceName) => { + const provider = new NodeTracerProvider({ + resource: new Resource({ + [ResourceAttributes.SERVICE_NAME]: serviceName, + }), + }); + registerInstrumentations({ + tracerProvider: provider, + instrumentations: [ + new MemcachedInstrumentation(), + ], + }); + + const exporter = new ConsoleSpanExporter(); + + provider.addSpanProcessor(new SimpleSpanProcessor(exporter)); + + // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings + provider.register(); + + return opentelemetry.trace.getTracer('memcached-example'); +}; diff --git a/packages/opentelemetry-test-utils/testUtils.ts b/packages/opentelemetry-test-utils/testUtils.ts index 48abc13b51..387b0502eb 100644 --- a/packages/opentelemetry-test-utils/testUtils.ts +++ b/packages/opentelemetry-test-utils/testUtils.ts @@ -29,23 +29,18 @@ import { hrTimeToMicroseconds, } from '@opentelemetry/core'; -export function startDocker(db: 'redis' | 'mysql' | 'postgres') { - let dockerRunCmd; - switch (db) { - case 'redis': - dockerRunCmd = `docker run -d -p 63790:6379 --name ot${db} ${db}:alpine`; - break; - - case 'mysql': - dockerRunCmd = `docker run --rm -d -e MYSQL_ROOT_PASSWORD=rootpw -e MYSQL_DATABASE=test_db -e MYSQL_USER=otel -e MYSQL_PASSWORD=secret -p 33306:3306 --name ot${db} circleci/${db}:5.7`; - break; - - case 'postgres': - dockerRunCmd = `docker run -d -p 54320:5432 -e POSTGRES_PASSWORD=postgres --name ot${db} ${db}:alpine`; - break; - } +const dockerRunCmds = { + redis: 'docker run --rm -d --name otel-redis -p 63790:6379 redis:alpine', + mysql: + 'docker run --rm -d --name otel-mysql -p 33306:3306 -e MYSQL_ROOT_PASSWORD=rootpw -e MYSQL_DATABASE=test_db -e MYSQL_USER=otel -e MYSQL_PASSWORD=secret circleci/mysql:5.7', + postgres: + 'docker run --rm -d --name otel-postgres -p 54320:5432 -e POSTGRES_PASSWORD=postgres postgres:alpine', + memcached: + 'docker run --rm -d --name otel-memcached -p 11211:11211 memcached:1.6.9-alpine', +}; - const tasks = [run(dockerRunCmd)]; +export function startDocker(db: keyof typeof dockerRunCmds) { + const tasks = [run(dockerRunCmds[db])]; for (let i = 0; i < tasks.length; i++) { const task = tasks[i]; @@ -58,9 +53,9 @@ export function startDocker(db: 'redis' | 'mysql' | 'postgres') { return true; } -export function cleanUpDocker(db: 'redis' | 'mysql' | 'postgres') { - run(`docker stop ot${db}`); - run(`docker rm ot${db}`); +export function cleanUpDocker(db: keyof typeof dockerRunCmds) { + run(`docker stop otel-${db}`); + run(`docker rm otel-${db}`); } function run(cmd: string) { diff --git a/plugins/node/opentelemetry-instrumentation-memcached/.eslintignore b/plugins/node/opentelemetry-instrumentation-memcached/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-instrumentation-memcached/.eslintrc.js b/plugins/node/opentelemetry-instrumentation-memcached/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-instrumentation-memcached/.npmignore b/plugins/node/opentelemetry-instrumentation-memcached/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/opentelemetry-instrumentation-memcached/LICENSE b/plugins/node/opentelemetry-instrumentation-memcached/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/plugins/node/opentelemetry-instrumentation-memcached/README.md b/plugins/node/opentelemetry-instrumentation-memcached/README.md new file mode 100644 index 0000000000..983105f151 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/README.md @@ -0,0 +1,72 @@ +# OpenTelemetry Memcached Instrumentation for Node.js + +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +This module provides automatic instrumentation for [`memcached@>=2.2.0`][repo-url]. + +For automatic instrumentation see the +[@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-node) package. + +## Installation + +```bash +npm install --save @opentelemetry/instrumentation-memcached +``` + +### Supported Versions + +- `>=2.2` + +## Usage + +OpenTelemetry Memcached Instrumentation allows the user to automatically collect trace data and export them to the backend of choice, to give observability to distributed systems when working with [memcached][pkg-url]. + +To load a specific instrumentation (**memcached** in this case), specify it in the registerInstrumentations' configuration + +```javascript +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { MemcachedInstrumentation } = require('@opentelemetry/instrumentation-memcached'); +const { registerInstrumentations } = require('@opentelemetry/instrumentation'); + +const provider = new NodeTracerProvider(); +provider.register(); + +registerInstrumentations({ + instrumentations: [ + new MemcachedInstrumentation({ + enhancedDatabaseReporting: false, + }), + ], +}); +``` + +### Configuration Options + +| Option | Type | Example | Description | +| ------- | ---- | ------- | ----------- | +| `enhancedDatabaseReporting` | `boolean` | `false` | Include full command statement in the span - **leaks potentially sensitive information to your spans**. Defaults to `false`. | + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached +[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached&type=dev +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-memcached +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-memcached.svg +[repo-url]: https://github.com/3rd-Eden/memcached +[pkg-url]: https://www.npmjs.com/package/memcached diff --git a/plugins/node/opentelemetry-instrumentation-memcached/package.json b/plugins/node/opentelemetry-instrumentation-memcached/package.json new file mode 100644 index 0000000000..57829ead89 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/package.json @@ -0,0 +1,71 @@ +{ + "name": "@opentelemetry/instrumentation-memcached", + "version": "0.22.0", + "description": "OpenTelemetry memcached automatic instrumentation package.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js-contrib", + "scripts": { + "clean": "rimraf build/*", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "compile": "npm run version:update && tsc -p .", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "precompile": "tsc --version", + "prepare": "npm run compile", + "tdd": "npm run test -- --watch-extensions ts --watch", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "test:debug": "cross-env RUN_MEMCACHED_TESTS_LOCAL=true ts-mocha --inspect-brk --no-timeouts -p tsconfig.json 'test/**/*.test.ts'", + "test:local": "cross-env RUN_MEMCACHED_TESTS_LOCAL=true npm run test", + "version:update": "node ../../../scripts/version-update.js" + }, + "keywords": [ + "opentelemetry", + "memcached", + "nodejs", + "tracing", + "profiling", + "instrumentation" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.1" + }, + "devDependencies": { + "@opentelemetry/api": "1.0.1", + "@opentelemetry/context-async-hooks": "0.22.0", + "@opentelemetry/node": "0.22.0", + "@opentelemetry/test-utils": "^0.22.0", + "@opentelemetry/tracing": "0.22.0", + "@types/mocha": "7.0.2", + "@types/node": "14.17.2", + "codecov": "3.8.2", + "cross-env": "7.0.3", + "gts": "3.1.0", + "memcached": "^2.2.2", + "mocha": "7.2.0", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "ts-mocha": "8.0.0", + "typescript": "4.3.2" + }, + "dependencies": { + "@opentelemetry/instrumentation": "^0.22.0", + "@opentelemetry/semantic-conventions": "^0.22.0", + "@types/memcached": "^2.2.6" + } +} diff --git a/plugins/node/opentelemetry-instrumentation-memcached/src/index.ts b/plugins/node/opentelemetry-instrumentation-memcached/src/index.ts new file mode 100644 index 0000000000..4c831c2980 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/src/index.ts @@ -0,0 +1,22 @@ +/* + * 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 { Instrumentation } from './instrumentation'; +export { InstrumentationConfig } from './types'; + +export * from './instrumentation'; +export default Instrumentation; +export { Instrumentation as MemcachedInstrumentation }; diff --git a/plugins/node/opentelemetry-instrumentation-memcached/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-memcached/src/instrumentation.ts new file mode 100644 index 0000000000..4bc30e87df --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/src/instrumentation.ts @@ -0,0 +1,188 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as api from '@opentelemetry/api'; +import { + isWrapped, + InstrumentationBase, + InstrumentationNodeModuleDefinition, +} from '@opentelemetry/instrumentation'; +import type * as Memcached from 'memcached'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import * as utils from './utils'; +import { InstrumentationConfig } from './types'; +import { VERSION } from './version'; + +export class Instrumentation extends InstrumentationBase { + static readonly COMPONENT = 'memcached'; + static readonly COMMON_ATTRIBUTES = { + [SemanticAttributes.DB_SYSTEM]: Instrumentation.COMPONENT, + }; + static readonly DEFAULT_CONFIG: InstrumentationConfig = { + enhancedDatabaseReporting: false, + }; + + constructor(config: InstrumentationConfig = {}) { + super( + '@opentelemetry/instrumentation-memcached', + VERSION, + Object.assign({}, Instrumentation.DEFAULT_CONFIG, config) + ); + } + + setConfig(config: InstrumentationConfig = {}) { + this._config = Object.assign({}, Instrumentation.DEFAULT_CONFIG, config); + } + + init() { + return [ + new InstrumentationNodeModuleDefinition( + 'memcached', + ['>=2.2'], + (moduleExports, moduleVersion) => { + this._diag.debug( + `Patching ${Instrumentation.COMPONENT}@${moduleVersion}` + ); + this.ensureWrapped( + moduleVersion, + moduleExports.prototype, + 'command', + this.wrapCommand.bind(this, moduleVersion) + ); + return moduleExports; + }, + (moduleExports, moduleVersion) => { + this._diag.debug( + `Unpatching ${Instrumentation.COMPONENT}@${moduleVersion}` + ); + if (moduleExports === undefined) return; + // `command` is documented API missing from the types + this._unwrap(moduleExports.prototype, 'command' as keyof Memcached); + } + ), + ]; + } + + wrapCommand( + moduleVersion: undefined | string, + original: ( + queryCompiler: () => Memcached.CommandData, + server?: string + ) => any + ) { + const instrumentation = this; + return function ( + this: Memcached, + queryCompiler: () => Memcached.CommandData, + server?: string + ) { + if (typeof queryCompiler !== 'function') { + return original.apply(this, arguments as any); + } + // The name will be overwritten later + const span = instrumentation.tracer.startSpan( + 'unknown memcached command', + { + kind: api.SpanKind.CLIENT, + attributes: { + 'memcached.version': moduleVersion, + ...Instrumentation.COMMON_ATTRIBUTES, + }, + } + ); + const parentContext = api.context.active(); + const context = api.trace.setSpan(parentContext, span); + + return api.context.with( + context, + original, + this, + instrumentation.wrapQueryCompiler.call( + instrumentation, + queryCompiler, + this, + server, + parentContext, + span + ), + server + ); + }; + } + + wrapQueryCompiler( + original: () => Memcached.CommandData, + client: Memcached, + server: undefined | string, + callbackContext: api.Context, + span: api.Span + ) { + const instrumentation = this; + return function (this: Memcached) { + const query = original.apply(this, arguments as any); + const callback = query.callback; + + span.updateName(`${query.type} ${query.key}`); + span.setAttributes({ + 'db.memcached.key': query.key, + 'db.memcached.lifetime': query.lifetime, + [SemanticAttributes.DB_OPERATION]: query.type, + [SemanticAttributes.DB_STATEMENT]: ( + instrumentation._config as InstrumentationConfig + ).enhancedDatabaseReporting + ? query.command + : undefined, + ...utils.getPeerAttributes(client, server, query), + }); + + query.callback = api.context.bind( + callbackContext, + function (this: Memcached.CommandData, err: any) { + if (err) { + span.recordException(err); + span.setStatus({ + code: api.SpanStatusCode.ERROR, + message: err.message, + }); + } + + span.end(); + + if (typeof callback === 'function') { + return callback.apply(this, arguments as any); + } + } + ); + + return query; + }; + } + + private ensureWrapped( + moduleVersion: string | undefined, + obj: any, + methodName: string, + wrapper: (original: any) => any + ) { + this._diag.debug( + `Applying ${methodName} patch for ${Instrumentation.COMPONENT}@${moduleVersion}` + ); + if (isWrapped(obj[methodName])) { + this._unwrap(obj, methodName); + } + this._wrap(obj, methodName, wrapper); + } +} diff --git a/plugins/node/opentelemetry-instrumentation-memcached/src/types.ts b/plugins/node/opentelemetry-instrumentation-memcached/src/types.ts new file mode 100644 index 0000000000..b2b395f069 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/src/types.ts @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { InstrumentationConfig as BaseInstrumentationConfig } from '@opentelemetry/instrumentation'; + +export interface InstrumentationConfig extends BaseInstrumentationConfig { + enhancedDatabaseReporting?: boolean; +} diff --git a/plugins/node/opentelemetry-instrumentation-memcached/src/utils.ts b/plugins/node/opentelemetry-instrumentation-memcached/src/utils.ts new file mode 100644 index 0000000000..aa49f6c357 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/src/utils.ts @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type * as Memcached from 'memcached'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; + +export const getPeerAttributes = ( + client: any /* Memcached, but the type definitions are lacking */, + server: string | undefined, + query: Memcached.CommandData +) => { + if (!server) { + if (client.servers.length === 1) { + server = client.servers[0]; + } else { + let redundancy = + client.redundancy && client.redundancy < client.servers.length; + const queryRedundancy = query.redundancyEnabled; + + if (redundancy && queryRedundancy) { + redundancy = client.HashRing.range( + query.key, + client.redundancy + 1, + true + ); + server = redundancy.shift(); + } else { + server = client.HashRing.get(query.key); + } + } + } + + if (typeof server === 'string') { + const [host, port] = server && server.split(':'); + return { + [SemanticAttributes.NET_PEER_NAME]: host, + [SemanticAttributes.NET_PEER_PORT]: port, + }; + } + return {}; +}; diff --git a/plugins/node/opentelemetry-instrumentation-memcached/src/version.ts b/plugins/node/opentelemetry-instrumentation-memcached/src/version.ts new file mode 100644 index 0000000000..8b92491b98 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/src/version.ts @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// this is autogenerated file, see scripts/version-update.js +export const VERSION = '0.22.0'; diff --git a/plugins/node/opentelemetry-instrumentation-memcached/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-memcached/test/index.test.ts new file mode 100644 index 0000000000..ca6c54b3ad --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/test/index.test.ts @@ -0,0 +1,310 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { context, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import * as testUtils from '@opentelemetry/test-utils'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import type * as Memcached from 'memcached'; +import * as assert from 'assert'; +import Instrumentation from '../src'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import * as util from 'util'; + +const instrumentation = new Instrumentation(); +const memoryExporter = new InMemorySpanExporter(); + +const CONFIG = { + host: process.env.OPENTELEMETRY_MEMCACHED_HOST || 'localhost', + port: process.env.OPENTELEMETRY_MEMCACHED_PORT || '11211', +}; + +const DEFAULT_ATTRIBUTES = { + [SemanticAttributes.DB_SYSTEM]: Instrumentation.COMPONENT, + [SemanticAttributes.NET_PEER_NAME]: CONFIG.host, + [SemanticAttributes.NET_PEER_PORT]: CONFIG.port, +}; + +interface ExtendedMemcached extends Memcached { + getPromise: (key: string) => Promise; + setPromise: (key: string, value: any, lifetime: number) => Promise; + appendPromise: (key: string, value: any) => Promise; +} +const getClient = (...args: any[]): ExtendedMemcached => { + const Memcached = require('memcached'); + const client = new Memcached(...args); + client.getPromise = util.promisify(client.get.bind(client)); + client.setPromise = util.promisify(client.set.bind(client)); + client.appendPromise = util.promisify(client.append.bind(client)); + return client; +}; +const KEY = 'foo'; +const VALUE = '_test_value_'; +const shouldTestLocal = process.env.RUN_MEMCACHED_TESTS_LOCAL; +const shouldTest = process.env.RUN_MEMCACHED_TESTS || shouldTestLocal; + +describe('memcached@2.x', () => { + const provider = new NodeTracerProvider(); + const tracer = provider.getTracer('default'); + provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + instrumentation.setTracerProvider(provider); + let contextManager: AsyncHooksContextManager; + + beforeEach(() => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + instrumentation.setConfig({}); + instrumentation.enable(); + }); + + afterEach(() => { + memoryExporter.reset(); + context.disable(); + instrumentation.disable(); + }); + + before(function () { + // needs to be "function" to have MochaContext "this" context + if (!shouldTest) { + // this.skip() workaround + // https://github.com/mochajs/mocha/issues/2683#issuecomment-375629901 + this.test!.parent!.pending = true; + this.skip(); + } + + if (shouldTestLocal) { + testUtils.startDocker('memcached'); + } + }); + + after(() => { + if (shouldTestLocal) { + testUtils.cleanUpDocker('memcached'); + } + }); + + describe('default config', () => { + let client: ExtendedMemcached; + beforeEach(() => { + client = getClient(`${CONFIG.host}:${CONFIG.port}`, { retries: 0 }); + }); + + afterEach(() => { + client.end(); + }); + + it('should collect basic info', async () => { + const parentSpan = tracer.startSpan('parentSpan'); + + await context.with( + trace.setSpan(context.active(), parentSpan), + async () => { + await client.setPromise(KEY, VALUE, 10); + const value = await client.getPromise(KEY); + + assert.strictEqual(value, VALUE); + const instrumentationSpans = memoryExporter.getFinishedSpans(); + assertSpans(instrumentationSpans, [ + { + op: 'set', + key: KEY, + parentSpan, + }, + { + op: 'get', + key: KEY, + parentSpan, + }, + ]); + } + ); + }); + + it('should handle errors', async () => { + const parentSpan = tracer.startSpan('parentSpan'); + const KEY = 'unset_key'; + const neverError = new Error('Expected to error but did not'); + + await context.with( + trace.setSpan(context.active(), parentSpan), + async () => { + try { + await client.appendPromise(KEY, VALUE); + assert.fail(neverError); + } catch (e) { + assert.notStrictEqual(e, neverError); + } + + const instrumentationSpans = memoryExporter.getFinishedSpans(); + assertSpans(instrumentationSpans, [ + { + op: 'append', + key: KEY, + parentSpan, + status: { + code: SpanStatusCode.ERROR, + message: 'Item is not stored', + }, + }, + ]); + + assertMatch( + instrumentationSpans?.[0]?.events[0]?.attributes?.[ + SemanticAttributes.EXCEPTION_MESSAGE + ] as 'string', + /not stored/ + ); + } + ); + }); + + it('should not require callback to be present', done => { + // want to force an signature without the callback + (client.get as any)(KEY); + + setTimeout(() => { + try { + const instrumentationSpans = memoryExporter.getFinishedSpans(); + assertSpans(instrumentationSpans, [ + { + op: 'get', + key: KEY, + }, + ]); + done(); + } catch (e) { + done(e); + } + }, 25); + }); + + it('should return to parent context in callback', done => { + const parentSpan = tracer.startSpan('parentSpan'); + const parentContext = trace.setSpan(context.active(), parentSpan); + + context.with(parentContext, () => { + client.get(KEY, () => { + try { + const cbContext = context.active(); + assert.strictEqual(cbContext, parentContext); + done(); + } catch (e) { + done(e); + } + }); + }); + }); + + it('should collect be able to collect statements', async () => { + instrumentation.setConfig({ + enhancedDatabaseReporting: true, + }); + const value = await client.getPromise(KEY); + + assert.strictEqual(value, VALUE); + const instrumentationSpans = memoryExporter.getFinishedSpans(); + assertSpans(instrumentationSpans, [ + { + op: 'get', + key: KEY, + statement: 'get foo', + }, + ]); + }); + + it('should not create new spans when disabled', async () => { + instrumentation.disable(); + await client.getPromise(KEY); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + }); + + describe('alternate memcached configurations', () => { + it('should support multiple server configuration', async () => { + const client = getClient( + { + [`${CONFIG.host}:${CONFIG.port}`]: 1, + 'other:11211': 1, + }, + { retries: 0 } + ); + + await Promise.all([client.getPromise(KEY)]); + + const instrumentationSpans = memoryExporter.getFinishedSpans(); + assertSpans(instrumentationSpans, [ + { + op: 'get', + key: KEY, + }, + ]); + }); + }); +}); + +const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { + assert(Array.isArray(actualSpans), 'Expected `actualSpans` to be an array'); + assert( + Array.isArray(expectedSpans), + 'Expected `expectedSpans` to be an array' + ); + assert.strictEqual( + actualSpans.length, + expectedSpans.length, + 'Expected span count different from actual' + ); + actualSpans.forEach((span, idx) => { + const expected = expectedSpans[idx]; + if (expected === null) return; + try { + assert.notStrictEqual(span, undefined); + assert.notStrictEqual(expected, undefined); + assertMatch(span.name, new RegExp(expected.op)); + assertMatch(span.name, new RegExp(expected.key)); + assert.strictEqual(span.kind, SpanKind.CLIENT); + assert.strictEqual(span.attributes['db.statement'], expected.statement); + for (const attr in DEFAULT_ATTRIBUTES) { + assert.strictEqual(span.attributes[attr], DEFAULT_ATTRIBUTES[attr]); + } + assert.strictEqual(span.attributes['db.memcached.key'], expected.key); + assert.strictEqual( + typeof span.attributes['memcached.version'], + 'string', + 'memcached.version not specified' + ); + assert.deepEqual( + span.status, + expected.status || { code: SpanStatusCode.UNSET } + ); + assert.strictEqual(span.attributes['db.operation'], expected.op); + assert.strictEqual( + span.parentSpanId, + expected.parentSpan?.spanContext().spanId + ); + } catch (e) { + e.message = `At span[${idx}]: ${e.message}`; + throw e; + } + }); +}; + +const assertMatch = (str: string, regexp: RegExp, err?: any) => { + assert.ok(regexp.test(str), err ?? `Expected '${str} to match ${regexp}`); +}; diff --git a/plugins/node/opentelemetry-instrumentation-memcached/tsconfig.json b/plugins/node/opentelemetry-instrumentation-memcached/tsconfig.json new file mode 100644 index 0000000000..28be80d266 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-memcached/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +}