diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 155822db67..f7cf174533 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -14,6 +14,8 @@ components: packages/opentelemetry-id-generator-aws-xray: - NathanielRN - willarmiros + plugins/node/instrumentation-fs: + - rauno56 plugins/node/instrumentation-tedious: - rauno56 plugins/node/opentelemetry-instrumentation-aws-lambda: diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 10ad648c67..4b424dfb7d 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -20,7 +20,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v2 + uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index b9f4e142f7..b7fc1072a3 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -13,7 +13,7 @@ jobs: image: node:14 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Lint markdown files uses: avto-dev/markdown-lint@v1 diff --git a/.github/workflows/peer-api.yaml b/.github/workflows/peer-api.yaml index 39081b743e..15dc648361 100644 --- a/.github/workflows/peer-api.yaml +++ b/.github/workflows/peer-api.yaml @@ -13,10 +13,13 @@ jobs: image: node:14 steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install lerna run: npm install -g lerna + - name: Install script dependencies + run: npm install + - name: Check API dependency semantics run: lerna exec "node \$LERNA_ROOT_PATH/scripts/peer-api-check.js" diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 6d3aae6883..9ac19a04f2 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -18,7 +18,7 @@ jobs: # The logic below handles the npm publication: - name: Checkout Repository if: ${{ steps.release.outputs.releases_created }} - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 diff --git a/.github/workflows/test-all-versions.yml b/.github/workflows/test-all-versions.yml index e14436c165..1289d1fe1e 100644 --- a/.github/workflows/test-all-versions.yml +++ b/.github/workflows/test-all-versions.yml @@ -116,7 +116,7 @@ jobs: NPM_CONFIG_UNSAFE_PERM: true steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-node@v3 diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml index 89cc20835e..6339096973 100644 --- a/.github/workflows/unit-test.yml +++ b/.github/workflows/unit-test.yml @@ -110,7 +110,7 @@ jobs: NPM_CONFIG_UNSAFE_PERM: true steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-node@v3 @@ -160,7 +160,7 @@ jobs: NPM_CONFIG_UNSAFE_PERM: true steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-node@v3 diff --git a/README.md b/README.md index 4402881b3c..67edf0ad09 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ OpenTelemetry can collect tracing data automatically using instrumentations. Ven - [@opentelemetry/instrumentation-dns][otel-contrib-instrumentation-dns] - [@opentelemetry/instrumentation-express][otel-contrib-instrumentation-express] - [@opentelemetry/instrumentation-fastify][otel-contrib-instrumentation-fastify] +- [@opentelemetry/instrumentation-fs][otel-contrib-instrumentation-fs] - [@opentelemetry/instrumentation-generic-pool][otel-contrib-instrumentation-generic-pool] - [@opentelemetry/instrumentation-graphql][otel-contrib-instrumentation-graphql] - [@opentelemetry/instrumentation-grpc][otel-instrumentation-grpc] @@ -169,6 +170,7 @@ Apache 2.0 - See [LICENSE][license-url] for more information. [otel-contrib-instrumentation-document-load]: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/web/opentelemetry-instrumentation-document-load [otel-contrib-instrumentation-express]: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express [otel-contrib-instrumentation-fastify]: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-fastify +[otel-contrib-instrumentation-fs]: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/instrumentation-fs [otel-contrib-instrumentation-generic-pool]: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-generic-pool [otel-contrib-instrumentation-graphql]: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-graphql [otel-contrib-instrumentation-hapi]: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-hapi diff --git a/plugins/node/instrumentation-fs/.eslintignore b/plugins/node/instrumentation-fs/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/instrumentation-fs/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/instrumentation-fs/.eslintrc.js b/plugins/node/instrumentation-fs/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/instrumentation-fs/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/instrumentation-fs/.npmignore b/plugins/node/instrumentation-fs/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/instrumentation-fs/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/instrumentation-fs/LICENSE b/plugins/node/instrumentation-fs/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/instrumentation-fs/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/instrumentation-fs/README.md b/plugins/node/instrumentation-fs/README.md new file mode 100644 index 0000000000..000be75bc8 --- /dev/null +++ b/plugins/node/instrumentation-fs/README.md @@ -0,0 +1,69 @@ +# OpenTelemetry `fs` 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 [`fs`](http://nodejs.org/dist/latest/docs/api/fs.html). + +For automatic instrumentation see the +[@opentelemetry/sdk-trace-node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-node) package. + +Compatible with OpenTelemetry JS API and SDK `1.0+`. + +See the full list of instrumented functions in [constants.ts](src/constants.ts); + +## Installation + +```bash +npm install --save @opentelemetry/instrumentation-fs +``` + +## Usage + +```js +const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node'); +const { FsInstrumentation } = require('@opentelemetry/instrumentation-fs'); +const { registerInstrumentations } = require('@opentelemetry/instrumentation'); + +const provider = new NodeTracerProvider(); +provider.register(); + +registerInstrumentations({ + instrumentations: [ + new FsInstrumentation({ + // see below for available configuration + }), + ], +}); +``` + +### Instrumentation Options + +You can set the following: + +| Options | Type | Description | +| ------- | ---- | ----------- | +| `createHook` | `(functionName: FMember | FPMember, info: { args: ArrayLike }) => boolean` | Hook called before creating the span. If `false` is returned this and all the sibling calls will not be traced. | +| `endHook` | `( functionName: FMember | FPMember, info: { args: ArrayLike; span: api.Span } ) => void` | Function called just before the span is ended. Useful for adding attributes. | + +## 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-fs +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-fs +[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-fs&type=dev +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-fs&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-fs +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-fs.svg diff --git a/plugins/node/instrumentation-fs/package.json b/plugins/node/instrumentation-fs/package.json new file mode 100644 index 0000000000..85a1dba4b5 --- /dev/null +++ b/plugins/node/instrumentation-fs/package.json @@ -0,0 +1,67 @@ +{ + "name": "@opentelemetry/instrumentation-fs", + "version": "0.1.0", + "description": "OpenTelemetry automatic instrumentation package for fs", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js-contrib", + "scripts": { + "test": "ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "tdd": "npm run test -- --watch-extensions ts --watch", + "clean": "rimraf build/*", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "precompile": "tsc --version && lerna run version --scope @opentelemetry/instrumentation-fs --include-dependencies", + "prewatch": "npm run precompile", + "prepare": "npm run compile", + "version:update": "node ../../../scripts/version-update.js", + "compile": "npm run version:update && tsc -p ." + }, + "keywords": [ + "fs", + "instrumentation", + "nodejs", + "opentelemetry", + "profiling", + "tracing" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts" + ], + "publishConfig": { + "access": "public" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.4" + }, + "devDependencies": { + "@opentelemetry/api": "1.0.4", + "@opentelemetry/context-async-hooks": "1.0.1", + "@opentelemetry/resources": "1.0.1", + "@opentelemetry/sdk-trace-base": "1.0.1", + "@opentelemetry/sdk-trace-node": "1.0.1", + "@types/mocha": "7.0.2", + "@types/node": "14.17.9", + "@types/shimmer": "1.0.2", + "@types/sinon": "^10.0.11", + "gts": "3.1.0", + "mocha": "7.2.0", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "sinon": "^13.0.1", + "ts-mocha": "8.0.0", + "typescript": "4.3.5" + }, + "dependencies": { + "@opentelemetry/core": "^1.0.1", + "@opentelemetry/instrumentation": "^0.27.0", + "@opentelemetry/semantic-conventions": "^1.0.1" + } +} diff --git a/plugins/node/instrumentation-fs/src/constants.ts b/plugins/node/instrumentation-fs/src/constants.ts new file mode 100644 index 0000000000..2247951aa5 --- /dev/null +++ b/plugins/node/instrumentation-fs/src/constants.ts @@ -0,0 +1,136 @@ +/* + * 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 { FMember, FPMember } from './types'; + +export const PROMISE_FUNCTIONS: FPMember[] = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'copyFile', + 'cp' as FPMember, // added in v16 + 'lchown', + 'link', + 'lstat', + 'lutimes', // added in v12 + 'mkdir', + 'mkdtemp', + 'open', + 'opendir', // added in v12 + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rm', // added in v14 + 'rmdir', + 'stat', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'writeFile', + // 'lchmod', // only implemented on macOS +]; + +export const CALLBACK_FUNCTIONS: FMember[] = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'copyFile', + 'cp' as FMember, // added in v16 + 'exists', // deprecated, inconsistent cb signature + 'lchown', + 'link', + 'lstat', + 'lutimes', // added in v12 + 'mkdir', + 'mkdtemp', + 'open', + 'opendir', // added in v12 + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rm', // added in v14 + 'rmdir', + 'stat', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'writeFile', + // 'close', // functions on file descriptor + // 'fchmod', // functions on file descriptor + // 'fchown', // functions on file descriptor + // 'fdatasync', // functions on file descriptor + // 'fstat', // functions on file descriptor + // 'fsync', // functions on file descriptor + // 'ftruncate', // functions on file descriptor + // 'futimes', // functions on file descriptor + // 'lchmod', // only implemented on macOS + // 'read', // functions on file descriptor + // 'readv', // functions on file descriptor + // 'write', // functions on file descriptor + // 'writev', // functions on file descriptor +]; + +export const SYNC_FUNCTIONS: FMember[] = [ + 'accessSync', + 'appendFileSync', + 'chmodSync', + 'chownSync', + 'copyFileSync', + 'cpSync' as FMember, // added in v16 + 'existsSync', + 'lchownSync', + 'linkSync', + 'lstatSync', + 'lutimesSync', // added in v12 + 'mkdirSync', + 'mkdtempSync', + 'opendirSync', // added in v12 + 'openSync', + 'readdirSync', + 'readFileSync', + 'readlinkSync', + 'realpathSync', + 'renameSync', + 'rmdirSync', + 'rmSync', // added in v14 + 'statSync', + 'symlinkSync', + 'truncateSync', + 'unlinkSync', + 'utimesSync', + 'writeFileSync', + // 'closeSync', // functions on file descriptor + // 'fchmodSync', // functions on file descriptor + // 'fchownSync', // functions on file descriptor + // 'fdatasyncSync', // functions on file descriptor + // 'fstatSync', // functions on file descriptor + // 'fsyncSync', // functions on file descriptor + // 'ftruncateSync', // functions on file descriptor + // 'futimesSync', // functions on file descriptor + // 'lchmodSync', // only implemented on macOS + // 'readSync', // functions on file descriptor + // 'readvSync', // functions on file descriptor + // 'writeSync', // functions on file descriptor + // 'writevSync', // functions on file descriptor +]; diff --git a/plugins/node/instrumentation-fs/src/index.ts b/plugins/node/instrumentation-fs/src/index.ts new file mode 100644 index 0000000000..a5d5e04e00 --- /dev/null +++ b/plugins/node/instrumentation-fs/src/index.ts @@ -0,0 +1,30 @@ +/* + * 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 FsInstrumentation from './instrumentation'; + +export { FsInstrumentation }; + +export * from './instrumentation'; +export { + FMember, + FPMember, + CreateHook, + EndHook, + FsInstrumentationConfig, +} from './types'; + +export default FsInstrumentation; diff --git a/plugins/node/instrumentation-fs/src/instrumentation.ts b/plugins/node/instrumentation-fs/src/instrumentation.ts new file mode 100644 index 0000000000..86959ac370 --- /dev/null +++ b/plugins/node/instrumentation-fs/src/instrumentation.ts @@ -0,0 +1,323 @@ +/* + * 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 { isTracingSuppressed, suppressTracing } from '@opentelemetry/core'; +import { + InstrumentationBase, + InstrumentationNodeModuleDefinition, + isWrapped, +} from '@opentelemetry/instrumentation'; +import { VERSION } from './version'; +import { + CALLBACK_FUNCTIONS, + PROMISE_FUNCTIONS, + SYNC_FUNCTIONS, +} from './constants'; +import type * as fs from 'fs'; +import type { + FMember, + FPMember, + CreateHook, + EndHook, + FsInstrumentationConfig, +} from './types'; + +type FS = typeof fs; + +const supportsPromises = parseInt(process.versions.node.split('.')[0], 10) > 8; + +export default class FsInstrumentation extends InstrumentationBase { + constructor(config?: FsInstrumentationConfig) { + super('@opentelemetry/instrumentation-fs', VERSION, config); + } + + init(): InstrumentationNodeModuleDefinition[] { + return [ + new InstrumentationNodeModuleDefinition( + 'fs', + ['*'], + (fs: FS) => { + this._diag.debug('Applying patch for fs'); + for (const fName of SYNC_FUNCTIONS) { + if (isWrapped(fs[fName])) { + this._unwrap(fs, fName); + } + this._wrap( + fs, + fName, + this._patchSyncFunction.bind(this, fName) + ); + } + for (const fName of CALLBACK_FUNCTIONS) { + if (isWrapped(fs[fName])) { + this._unwrap(fs, fName); + } + this._wrap( + fs, + fName, + this._patchCallbackFunction.bind(this, fName) + ); + } + if (supportsPromises) { + for (const fName of PROMISE_FUNCTIONS) { + if (isWrapped(fs.promises[fName])) { + this._unwrap(fs.promises, fName); + } + this._wrap( + fs.promises, + fName, + this._patchPromiseFunction.bind(this, fName) + ); + } + } + return fs; + }, + (fs: FS) => { + if (fs === undefined) return; + this._diag.debug('Removing patch for fs'); + for (const fName of SYNC_FUNCTIONS) { + if (isWrapped(fs[fName])) { + this._unwrap(fs, fName); + } + } + for (const fName of CALLBACK_FUNCTIONS) { + if (isWrapped(fs[fName])) { + this._unwrap(fs, fName); + } + } + if (supportsPromises) { + for (const fName of PROMISE_FUNCTIONS) { + if (isWrapped(fs.promises[fName])) { + this._unwrap(fs.promises, fName); + } + } + } + } + ), + ]; + } + + protected _patchSyncFunction ReturnType>( + functionName: FMember, + original: T + ): T { + const instrumentation = this; + return function (this: any, ...args: any[]) { + if (isTracingSuppressed(api.context.active())) { + // Performance optimization. Avoid creating additional contexts and spans + // if we already know that the tracing is being suppressed. + return original.apply(this, args); + } + if ( + instrumentation._runCreateHook(functionName, { + args: args, + }) === false + ) { + return api.context.with( + suppressTracing(api.context.active()), + original, + this, + ...args + ); + } + + const span = instrumentation.tracer.startSpan( + `fs ${functionName}` + ) as api.Span; + + try { + // Suppress tracing for internal fs calls + const res = api.context.with( + suppressTracing(api.trace.setSpan(api.context.active(), span)), + original, + this, + ...args + ); + instrumentation._runEndHook(functionName, { args: args, span }); + return res; + } catch (error) { + span.recordException(error); + span.setStatus({ + message: error.message, + code: api.SpanStatusCode.ERROR, + }); + instrumentation._runEndHook(functionName, { args: args, span, error }); + throw error; + } finally { + span.end(); + } + }; + } + + protected _patchCallbackFunction ReturnType>( + functionName: FMember, + original: T + ): T { + const instrumentation = this; + return function (this: any, ...args: any[]) { + if (isTracingSuppressed(api.context.active())) { + // Performance optimization. Avoid creating additional contexts and spans + // if we already know that the tracing is being suppressed. + return original.apply(this, args); + } + if ( + instrumentation._runCreateHook(functionName, { + args: args, + }) === false + ) { + return api.context.with( + suppressTracing(api.context.active()), + original, + this, + ...args + ); + } + + const lastIdx = args.length - 1; + const cb = args[lastIdx]; + if (typeof cb === 'function') { + const span = instrumentation.tracer.startSpan( + `fs ${functionName}` + ) as api.Span; + + // Return to the context active during the call in the callback + args[lastIdx] = api.context.bind( + api.context.active(), + function (this: unknown, error?: Error) { + if (error) { + span.recordException(error); + span.setStatus({ + message: error.message, + code: api.SpanStatusCode.ERROR, + }); + } + instrumentation._runEndHook(functionName, { + args: args, + span, + error, + }); + span.end(); + return cb.apply(this, arguments); + } + ); + + try { + // Suppress tracing for internal fs calls + return api.context.with( + suppressTracing(api.trace.setSpan(api.context.active(), span)), + original, + this, + ...args + ); + } catch (error) { + span.recordException(error); + span.setStatus({ + message: error.message, + code: api.SpanStatusCode.ERROR, + }); + instrumentation._runEndHook(functionName, { + args: args, + span, + error, + }); + span.end(); + throw error; + } + } else { + // TODO: what to do if we are pretty sure it's going to throw + return original.apply(this, args); + } + }; + } + + protected _patchPromiseFunction ReturnType>( + functionName: FPMember, + original: T + ): T { + const instrumentation = this; + return async function (this: any, ...args: any[]) { + if (isTracingSuppressed(api.context.active())) { + // Performance optimization. Avoid creating additional contexts and spans + // if we already know that the tracing is being suppressed. + return original.apply(this, args); + } + if ( + instrumentation._runCreateHook(functionName, { + args: args, + }) === false + ) { + return api.context.with( + suppressTracing(api.context.active()), + original, + this, + ...args + ); + } + + const span = instrumentation.tracer.startSpan( + `fs ${functionName}` + ) as api.Span; + + try { + // Suppress tracing for internal fs calls + const res = await api.context.with( + suppressTracing(api.trace.setSpan(api.context.active(), span)), + original, + this, + ...args + ); + instrumentation._runEndHook(functionName, { args: args, span }); + return res; + } catch (error) { + span.recordException(error); + span.setStatus({ + message: error.message, + code: api.SpanStatusCode.ERROR, + }); + instrumentation._runEndHook(functionName, { args: args, span, error }); + throw error; + } finally { + span.end(); + } + }; + } + + protected _runCreateHook( + ...args: Parameters + ): ReturnType { + const { createHook } = this.getConfig() as FsInstrumentationConfig; + if (typeof createHook === 'function') { + try { + return createHook(...args); + } catch (e) { + this._diag.error('caught createHook error', e); + } + } + return true; + } + + protected _runEndHook(...args: Parameters): ReturnType { + const { endHook } = this.getConfig() as FsInstrumentationConfig; + if (typeof endHook === 'function') { + try { + endHook(...args); + } catch (e) { + this._diag.error('caught endHook error', e); + } + } + } +} diff --git a/plugins/node/instrumentation-fs/src/types.ts b/plugins/node/instrumentation-fs/src/types.ts new file mode 100644 index 0000000000..d531cae43c --- /dev/null +++ b/plugins/node/instrumentation-fs/src/types.ts @@ -0,0 +1,41 @@ +/* + * 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 fs from 'fs'; + +import type * as api from '@opentelemetry/api'; +import type { InstrumentationConfig } from '@opentelemetry/instrumentation'; + +export type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; +}[keyof T]; +export type FunctionProperties = Pick>; + +export type FMember = FunctionPropertyNames; +export type FPMember = FunctionPropertyNames; + +export type CreateHook = ( + functionName: FMember | FPMember, + info: { args: ArrayLike } +) => boolean; +export type EndHook = ( + functionName: FMember | FPMember, + info: { args: ArrayLike; span: api.Span; error?: Error } +) => void; + +export interface FsInstrumentationConfig extends InstrumentationConfig { + createHook?: CreateHook; + endHook?: EndHook; +} diff --git a/plugins/node/instrumentation-fs/test/definitions.ts b/plugins/node/instrumentation-fs/test/definitions.ts new file mode 100644 index 0000000000..ba7ebe73fd --- /dev/null +++ b/plugins/node/instrumentation-fs/test/definitions.ts @@ -0,0 +1,70 @@ +/* + * 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 { FMember, FPMember } from '../src/types'; +import * as fs from 'fs'; + +export type FsFunction = FPMember & FMember; +export type Opts = { + sync?: boolean; + callback?: boolean; + promise?: boolean; +}; +export type Result = { error?: RegExp; result?: any }; +export type TestCase = [FsFunction, any[], Result, any[], Opts?]; +export type TestCreator = ( + name: FsFunction, + args: any[], + result: Result, + spans: any[] +) => void; + +const TEST_CONTENTS = Buffer.from('hello, world\n'); +const ENOENT = /ENOENT: no such file or directory, /; +const tests: TestCase[] = [ + [ + 'access', + ['./test/fixtures/readtest', fs.constants.R_OK], + { result: undefined }, + [{ name: 'fs %NAME' }], + ], + [ + 'access', + ['./test/fixtures/readtest-404', fs.constants.R_OK], + { error: ENOENT }, + [{ name: 'fs %NAME', error: ENOENT }], + ], + [ + 'readFile', + ['./test/fixtures/readtest'], + { result: TEST_CONTENTS }, + [{ name: 'fs %NAME' }], + ], + [ + 'readFile', + ['./test/fixtures/readtest-404'], + { error: ENOENT }, + [{ name: 'fs %NAME', error: ENOENT }], + ], + [ + 'writeFile', + ['./test/fixtures/writetest', TEST_CONTENTS], + { result: undefined }, + [{ name: 'fs %NAME' }], + ], +]; + +export default tests; diff --git a/plugins/node/instrumentation-fs/test/fixtures/readtest b/plugins/node/instrumentation-fs/test/fixtures/readtest new file mode 100644 index 0000000000..4b5fa63702 --- /dev/null +++ b/plugins/node/instrumentation-fs/test/fixtures/readtest @@ -0,0 +1 @@ +hello, world diff --git a/plugins/node/instrumentation-fs/test/fixtures/writetest b/plugins/node/instrumentation-fs/test/fixtures/writetest new file mode 100644 index 0000000000..4b5fa63702 --- /dev/null +++ b/plugins/node/instrumentation-fs/test/fixtures/writetest @@ -0,0 +1 @@ +hello, world diff --git a/plugins/node/instrumentation-fs/test/hooks.test.ts b/plugins/node/instrumentation-fs/test/hooks.test.ts new file mode 100644 index 0000000000..a85c83fcc2 --- /dev/null +++ b/plugins/node/instrumentation-fs/test/hooks.test.ts @@ -0,0 +1,164 @@ +/* + * 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 { + BasicTracerProvider, + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/sdk-trace-base'; +import * as assert from 'assert'; +import Instrumentation from '../src'; +import * as sinon from 'sinon'; +import type * as FSType from 'fs'; +import type { FsInstrumentationConfig } from '../src/types'; + +const supportsPromises = parseInt(process.versions.node.split('.')[0], 10) > 8; + +const createHookError = new Error('createHook failed'); +const createHook = sinon.spy((_functionName: string) => { + throw createHookError; +}); +const endHookError = new Error('endHook failed'); +const endHook = sinon.spy((_functionName: string) => { + throw endHookError; +}); +const pluginConfig = { + createHook, + endHook, +}; + +const provider = new BasicTracerProvider(); +const memoryExporter = new InMemorySpanExporter(); +provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +const assertNotHookError = (err?: Error | null) => { + assert.ok( + err && + err.message !== createHookError.message && + err.message !== endHookError.message, + 'Hook error shadowed the error from the original call' + ); +}; + +const assertSuccessfulCallHooks = (expectedFunctionName: string) => { + const createHookCall = createHook.withArgs(expectedFunctionName); + sinon.assert.called(createHookCall); + sinon.assert.threw(createHookCall, createHookError); + + const endHookCall = endHook.withArgs(expectedFunctionName); + sinon.assert.called(endHookCall); + sinon.assert.threw(endHookCall, endHookError); + assert( + !(endHookCall.getCall(0).args as any)[1].error, + 'Did not expect an error' + ); +}; + +const assertFailingCallHooks = (expectedFunctionName: string) => { + const createHookCall = createHook.withArgs(expectedFunctionName); + sinon.assert.called(createHookCall); + sinon.assert.threw(createHookCall, createHookError); + + const endHookCall = endHook.withArgs(expectedFunctionName); + sinon.assert.called(endHookCall); + sinon.assert.threw(endHookCall, endHookError); + assert((endHookCall.getCall(0).args as any)[1].error, 'Expected an error'); +}; + +describe('fs instrumentation: hooks', () => { + let plugin: Instrumentation; + let fs: typeof FSType; + + beforeEach(async () => { + plugin = new Instrumentation(pluginConfig); + plugin.setTracerProvider(provider); + plugin.setConfig(pluginConfig as FsInstrumentationConfig); + plugin.enable(); + fs = require('fs'); + createHook.resetHistory(); + endHook.resetHistory(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + + afterEach(() => { + plugin.disable(); + memoryExporter.reset(); + }); + + describe('Syncronous API', () => { + it('should not fail the original successful call when hooks throw', () => { + fs.accessSync('./test/fixtures/readtest', fs.constants.R_OK); + + assertSuccessfulCallHooks('accessSync'); + }); + + it('should not shadow the error from original call when hooks throw', () => { + try { + fs.accessSync('./test/fixtures/readtest-404', fs.constants.R_OK); + } catch (e) { + assertNotHookError(e); + } + + assertFailingCallHooks('accessSync'); + }); + }); + + describe('Callback API', () => { + it('should not fail the original successful call when hooks throw', done => { + fs.access('./test/fixtures/readtest', fs.constants.R_OK, () => { + try { + assertSuccessfulCallHooks('access'); + done(); + } catch (e) { + done(e); + } + }); + }); + + it('should not shadow the error from original call when hooks throw', done => { + fs.access('./test/fixtures/readtest-404', fs.constants.R_OK, err => { + // this assertion doesn't realistically make as much sense as in the other cases + // because we'd have to conciously catch the error and pass it to the cb + assertNotHookError(err); + try { + assertFailingCallHooks('access'); + done(); + } catch (e) { + done(e); + } + }); + }); + }); + + if (supportsPromises) { + describe('Promise API', () => { + it('should not fail the original successful call when hooks throw', async () => { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + await fs.promises.access('./test/fixtures/readtest', fs.constants.R_OK); + + assertSuccessfulCallHooks('access'); + }); + + it('should not shadow the error from original call when hooks throw', async () => { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + await fs.promises + .access('./test/fixtures/readtest-404', fs.constants.R_OK) + .catch(assertNotHookError); + + assertFailingCallHooks('access'); + }); + }); + } +}); diff --git a/plugins/node/instrumentation-fs/test/index.test.ts b/plugins/node/instrumentation-fs/test/index.test.ts new file mode 100644 index 0000000000..4933841a03 --- /dev/null +++ b/plugins/node/instrumentation-fs/test/index.test.ts @@ -0,0 +1,397 @@ +/* + * 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, trace, SpanStatusCode, SpanKind } from '@opentelemetry/api'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import { + BasicTracerProvider, + InMemorySpanExporter, + ReadableSpan, + SimpleSpanProcessor, +} from '@opentelemetry/sdk-trace-base'; +import * as assert from 'assert'; +import Instrumentation from '../src'; +import * as sinon from 'sinon'; +import type * as FSType from 'fs'; +import tests, { TestCase, TestCreator } from './definitions'; +import type { FMember, FPMember, CreateHook, EndHook } from '../src/types'; + +const supportsPromises = parseInt(process.versions.node.split('.')[0], 10) > 8; + +const TEST_ATTRIBUTE = 'test.attr'; +const TEST_VALUE = 'test.attr.value'; + +const createHook = sinon.spy( + (fnName: FMember | FPMember, { args, span }) => { + // `ts-node`, which we use via `ts-mocha` also patches module loading and creates + // a lot of unrelated spans. Filter those out. + if (['readFileSync', 'existsSync'].includes(fnName)) { + const filename = args[0]; + if (!/test\/fixtures/.test(filename)) { + return false; + } + } + return true; + } +); +const endHook = sinon.spy((fnName, { args, span }) => { + span.setAttribute(TEST_ATTRIBUTE, TEST_VALUE); +}); +const pluginConfig = { + createHook, + endHook, +}; +const provider = new BasicTracerProvider(); +const tracer = provider.getTracer('default'); +const memoryExporter = new InMemorySpanExporter(); +provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + +describe('fs instrumentation', () => { + let contextManager: AsyncHooksContextManager; + let fs: typeof FSType; + let plugin: Instrumentation; + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + plugin = new Instrumentation(pluginConfig); + plugin.setTracerProvider(provider); + plugin.enable(); + fs = require('fs'); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + + afterEach(() => { + plugin.disable(); + memoryExporter.reset(); + context.disable(); + }); + + const syncTest: TestCreator = ( + name: FMember, + args, + { error, result }, + spans + ) => { + const syncName: FMember = `${name}Sync` as FMember; + const rootSpanName = `${syncName} test span`; + it(`${syncName} ${error ? 'error' : 'success'}`, () => { + const rootSpan = tracer.startSpan(rootSpanName); + + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + context.with(trace.setSpan(context.active(), rootSpan), () => { + if (error) { + assert.throws(() => Reflect.apply(fs[syncName], fs, args), error); + } else { + assert.deepEqual(Reflect.apply(fs[syncName], fs, args), result); + } + }); + rootSpan.end(); + + assertSpans(memoryExporter.getFinishedSpans(), [ + ...spans.map((s: any) => { + const spanName = s.name.replace(/%NAME/, syncName); + const attributes = { + ...(s.attributes ?? {}), + }; + attributes[TEST_ATTRIBUTE] = TEST_VALUE; + return { + ...s, + name: spanName, + attributes, + }; + }), + { name: rootSpanName }, + ]); + }); + }; + + const callbackTest: TestCreator = ( + name: FMember, + args, + { error, result }, + spans + ) => { + const rootSpanName = `${name} test span`; + it(`${name} ${error ? 'error' : 'success'}`, done => { + const rootSpan = tracer.startSpan(rootSpanName); + + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + context.with(trace.setSpan(context.active(), rootSpan), () => { + (fs[name] as Function)( + ...args, + (actualError: any | undefined, actualResult: any) => { + assert.strictEqual(trace.getSpan(context.active()), rootSpan); + + try { + rootSpan.end(); + if (error) { + assert( + error.test(actualError?.message ?? ''), + `Expected ${actualError?.message} to match ${error}` + ); + } else { + if (actualError) { + return done(actualError); + } + assert.deepEqual(actualResult, result); + } + assertSpans(memoryExporter.getFinishedSpans(), [ + ...spans.map((s: any) => { + const spanName = s.name.replace(/%NAME/, name); + const attributes = { + ...(s.attributes ?? {}), + }; + attributes[TEST_ATTRIBUTE] = TEST_VALUE; + return { + ...s, + name: spanName, + attributes, + }; + }), + { name: rootSpanName }, + ]); + done(); + } catch (e) { + done(e); + } + } + ); + }); + }); + }; + + const promiseTest: TestCreator = ( + name: FPMember, + args, + { error, result }, + spans + ) => { + const rootSpanName = `${name} test span`; + it(`promises.${name} ${error ? 'error' : 'success'}`, async () => { + const rootSpan = tracer.startSpan(rootSpanName); + + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + await context + .with(trace.setSpan(context.active(), rootSpan), () => { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + return Reflect.apply(fs.promises[name], fs.promises, args); + }) + .then((actualResult: any) => { + if (error) { + assert.fail(`promises.${name} did not reject`); + } else { + assert.deepEqual(actualResult, result); + } + }) + .catch((actualError: any) => { + if (error) { + assert( + error.test(actualError?.message ?? ''), + `Expected "${actualError?.message}" to match ${error}` + ); + } else { + actualError.message = `Did not expect promises.${name} to reject: ${actualError.message}`; + assert.fail(actualError); + } + }); + rootSpan.end(); + assertSpans(memoryExporter.getFinishedSpans(), [ + ...spans.map((s: any) => { + const spanName = s.name.replace(/%NAME/, name); + const attributes = { + ...(s.attributes ?? {}), + }; + attributes[TEST_ATTRIBUTE] = TEST_VALUE; + return { + ...s, + name: spanName, + attributes, + }; + }), + { name: rootSpanName }, + ]); + }); + }; + + describe('Syncronous API', () => { + const selection: TestCase[] = tests.filter( + ([, , , , options = {}]) => options.sync !== false + ); + + describe('Instrumentation enabled', () => { + selection.forEach(([name, args, result, spans]) => { + syncTest(name, args, result, spans); + }); + + it('should instrument mkdirSync calls', () => { + fs.mkdirSync('./test/fixtures/mkdirSync'); + fs.rmdirSync('./test/fixtures/mkdirSync'); + + assertSpans(memoryExporter.getFinishedSpans(), [ + { + name: 'fs mkdirSync', + attributes: { [TEST_ATTRIBUTE]: TEST_VALUE }, + }, + { + name: 'fs rmdirSync', + attributes: { [TEST_ATTRIBUTE]: TEST_VALUE }, + }, + ]); + }); + }); + + describe('Instrumentation disabled', () => { + beforeEach(() => { + plugin.disable(); + }); + + selection.forEach(([name, args, result]) => { + syncTest(name, args, result, []); + }); + }); + }); + + describe('Callback API', () => { + const selection: TestCase[] = tests.filter( + ([, , , , options = {}]) => options.callback !== false + ); + + describe('Instrumentation enabled', () => { + selection.forEach(([name, args, result, spans]) => { + callbackTest(name, args, result, spans); + }); + + it('should not suppress tracing in callbacks', done => { + const readFileCatchErrors = (cb: Function) => { + fs.readFile('./test/fixtures/readtest', (err, result) => { + try { + if (err) { + return done(err); + } + cb(result); + } catch (err) { + done(err); + } + }); + }; + + readFileCatchErrors(() => { + readFileCatchErrors(() => { + assertSpans(memoryExporter.getFinishedSpans(), [ + { + name: 'fs readFile', + attributes: { [TEST_ATTRIBUTE]: TEST_VALUE }, + }, + { + name: 'fs readFile', + attributes: { [TEST_ATTRIBUTE]: TEST_VALUE }, + }, + ]); + done(); + }); + }); + }); + }); + + describe('Instrumentation disabled', () => { + beforeEach(() => { + plugin.disable(); + }); + + selection.forEach(([name, args, result]) => { + callbackTest(name, args, result, []); + }); + }); + }); + + if (supportsPromises) { + describe('Promise API', () => { + const selection: TestCase[] = tests.filter( + ([, , , , options = {}]) => options.promise !== false + ); + + describe('Instrumentation enabled', () => { + selection.forEach(([name, args, result, spans]) => { + promiseTest(name as FPMember, args, result, spans); + }); + }); + + describe('Instrumentation disabled', () => { + beforeEach(() => { + plugin.disable(); + }); + + selection.forEach(([name, args, result]) => { + promiseTest(name as FPMember, args, result, []); + }); + }); + }); + } +}); + +const assertSpans = (spans: ReadableSpan[], expected: any) => { + assert.strictEqual( + spans.length, + expected.length, + `Expected ${expected.length} spans, got ${spans.length}(${spans + .map((s: any) => `"${s.name}"`) + .join(', ')})` + ); + + spans.forEach((span, i) => { + assertSpan(span, expected[i]); + }); + + assert.strictEqual( + spans.length, + expected.length, + `Expected ${expected.length} spans, got ${spans.length}` + ); +}; + +const assertSpan = (span: ReadableSpan, expected: any) => { + assert(span); + assert.strictEqual(span.name, expected.name); + assert.strictEqual( + span.kind, + SpanKind.INTERNAL, + 'Expected to be of INTERNAL kind' + ); + if (expected.parentSpan) { + assert.strictEqual( + span.parentSpanId, + expected.parentSpan.spanContext().spanId + ); + } + if (expected.attributes) { + assert.deepEqual(span.attributes, expected.attributes); + } + if (expected.error) { + assert( + expected.error.test(span.status.message), + `Expected "${span.status.message}" to match ${expected.error}` + ); + assert.strictEqual(span.status.code, SpanStatusCode.ERROR); + } else { + assert.strictEqual( + span.status.code, + SpanStatusCode.UNSET, + 'Expected status to be unset' + ); + assert.strictEqual(span.status.message, undefined); + } +}; diff --git a/plugins/node/instrumentation-fs/tsconfig.json b/plugins/node/instrumentation-fs/tsconfig.json new file mode 100644 index 0000000000..28be80d266 --- /dev/null +++ b/plugins/node/instrumentation-fs/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} diff --git a/release-please-config.json b/release-please-config.json index 85dac87950..584936b418 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -16,6 +16,7 @@ "packages/opentelemetry-id-generator-aws-xray": {}, "packages/opentelemetry-propagation-utils": {}, "packages/opentelemetry-test-utils": {}, + "plugins/node/instrumentation-fs": {}, "plugins/node/instrumentation-tedious": {}, "plugins/node/opentelemetry-instrumentation-aws-lambda": {}, "plugins/node/opentelemetry-instrumentation-aws-sdk": {}, diff --git a/scripts/package.json b/scripts/package.json new file mode 100644 index 0000000000..5d9c49bffe --- /dev/null +++ b/scripts/package.json @@ -0,0 +1,8 @@ +{ + "name": "opentelemetry-contrib-scripts", + "private": true, + "license": "Apache-2.0", + "dependencies": { + "semver": "7.3.5" + } +} diff --git a/scripts/peer-api-check.js b/scripts/peer-api-check.js index dbb4002c3a..542bcfad2c 100644 --- a/scripts/peer-api-check.js +++ b/scripts/peer-api-check.js @@ -15,6 +15,8 @@ */ const path = require('path'); +const semver = require('semver'); + const appRoot = process.cwd(); const packageJsonUrl = path.resolve(`${appRoot}/package.json`); const pjson = require(packageJsonUrl); @@ -32,10 +34,10 @@ if (peerVersion) { `Package ${pjson.name} does't have API version pinned in dev dependencies: ${devVersion}` ); } - if (peerVersion !== `^${devVersion}`) { + if (!semver.satisfies(devVersion, peerVersion)) { throw new Error( `Package ${pjson.name} depends on peer API version ${peerVersion} ` + - `but version ${devVersion} in development` + `but version ${devVersion} in development which doesn't satisfy the peer API version` ); } console.log(`${pjson.name} OK`);