From 6e9962737dc465306e90d72677d41ff76b00d3b8 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Wed, 12 Aug 2020 18:59:07 -0700 Subject: [PATCH 01/15] refactor: separate resource detector packages --- .../.eslintignore | 1 + .../.eslintrc.js | 9 + .../.npmignore | 4 + .../LICENSE | 201 +++++++++++++ .../README.md | 44 +++ .../package.json | 63 ++++ .../src}/detectors/AwsEc2Detector.ts | 12 +- .../src}/detectors/index.ts | 4 +- .../src/index.ts | 17 ++ .../src/version.ts | 18 ++ .../test/detectors/AwsEc2Detector.test.ts | 4 +- .../test/util/resource-assertions.ts | 277 ++++++++++++++++++ .../tsconfig.json | 8 + .../.eslintignore | 1 + .../.eslintrc.js | 9 + .../.npmignore | 4 + .../LICENSE | 201 +++++++++++++ .../README.md | 44 +++ .../package.json | 63 ++++ .../src}/detectors/EnvDetector.ts | 9 +- .../src/detectors/index.ts | 17 ++ .../src/index.ts | 17 ++ .../src/version.ts | 18 ++ .../test/detectors/EnvDetector.test.ts | 7 +- .../test/util/resource-assertions.ts | 277 ++++++++++++++++++ .../tsconfig.json | 8 + .../.eslintignore | 1 + .../.eslintrc.js | 9 + .../.npmignore | 4 + .../LICENSE | 201 +++++++++++++ .../README.md | 44 +++ .../package.json | 64 ++++ .../src}/detectors/GcpDetector.ts | 9 +- .../src/detectors/index.ts | 17 ++ .../src/index.ts | 17 ++ .../src/version.ts | 18 ++ .../test/detectors/GcpDetector.test.ts | 6 +- .../test/util/resource-assertions.ts | 277 ++++++++++++++++++ .../tsconfig.json | 8 + .../opentelemetry-resources/src/Resource.ts | 7 +- .../opentelemetry-resources/src/config.ts | 2 + packages/opentelemetry-resources/src/index.ts | 1 + .../src/platform/index.ts | 1 + .../src/platform/node/detect-resources.ts | 14 +- .../test/detect-resources.test.ts | 275 ----------------- .../test/util/sample-detector.ts | 32 ++ packages/opentelemetry-sdk-node/package.json | 7 +- packages/opentelemetry-sdk-node/src/sdk.ts | 14 +- .../opentelemetry-sdk-node/test/sdk.test.ts | 149 ++++++++++ 49 files changed, 2200 insertions(+), 314 deletions(-) create mode 100644 packages/opentelemetry-resource-detector-aws/.eslintignore create mode 100644 packages/opentelemetry-resource-detector-aws/.eslintrc.js create mode 100644 packages/opentelemetry-resource-detector-aws/.npmignore create mode 100644 packages/opentelemetry-resource-detector-aws/LICENSE create mode 100644 packages/opentelemetry-resource-detector-aws/README.md create mode 100644 packages/opentelemetry-resource-detector-aws/package.json rename packages/{opentelemetry-resources/src/platform/node => opentelemetry-resource-detector-aws/src}/detectors/AwsEc2Detector.ts (92%) rename packages/{opentelemetry-resources/src/platform/node => opentelemetry-resource-detector-aws/src}/detectors/index.ts (81%) create mode 100644 packages/opentelemetry-resource-detector-aws/src/index.ts create mode 100644 packages/opentelemetry-resource-detector-aws/src/version.ts rename packages/{opentelemetry-resources => opentelemetry-resource-detector-aws}/test/detectors/AwsEc2Detector.test.ts (95%) create mode 100644 packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts create mode 100644 packages/opentelemetry-resource-detector-aws/tsconfig.json create mode 100644 packages/opentelemetry-resource-detector-env/.eslintignore create mode 100644 packages/opentelemetry-resource-detector-env/.eslintrc.js create mode 100644 packages/opentelemetry-resource-detector-env/.npmignore create mode 100644 packages/opentelemetry-resource-detector-env/LICENSE create mode 100644 packages/opentelemetry-resource-detector-env/README.md create mode 100644 packages/opentelemetry-resource-detector-env/package.json rename packages/{opentelemetry-resources/src/platform/node => opentelemetry-resource-detector-env/src}/detectors/EnvDetector.ts (96%) create mode 100644 packages/opentelemetry-resource-detector-env/src/detectors/index.ts create mode 100644 packages/opentelemetry-resource-detector-env/src/index.ts create mode 100644 packages/opentelemetry-resource-detector-env/src/version.ts rename packages/{opentelemetry-resources => opentelemetry-resource-detector-env}/test/detectors/EnvDetector.test.ts (91%) create mode 100644 packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts create mode 100644 packages/opentelemetry-resource-detector-env/tsconfig.json create mode 100644 packages/opentelemetry-resource-detector-gcp/.eslintignore create mode 100644 packages/opentelemetry-resource-detector-gcp/.eslintrc.js create mode 100644 packages/opentelemetry-resource-detector-gcp/.npmignore create mode 100644 packages/opentelemetry-resource-detector-gcp/LICENSE create mode 100644 packages/opentelemetry-resource-detector-gcp/README.md create mode 100644 packages/opentelemetry-resource-detector-gcp/package.json rename packages/{opentelemetry-resources/src/platform/node => opentelemetry-resource-detector-gcp/src}/detectors/GcpDetector.ts (94%) create mode 100644 packages/opentelemetry-resource-detector-gcp/src/detectors/index.ts create mode 100644 packages/opentelemetry-resource-detector-gcp/src/index.ts create mode 100644 packages/opentelemetry-resource-detector-gcp/src/version.ts rename packages/{opentelemetry-resources => opentelemetry-resource-detector-gcp}/test/detectors/GcpDetector.test.ts (97%) create mode 100644 packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts create mode 100644 packages/opentelemetry-resource-detector-gcp/tsconfig.json delete mode 100644 packages/opentelemetry-resources/test/detect-resources.test.ts create mode 100644 packages/opentelemetry-resources/test/util/sample-detector.ts diff --git a/packages/opentelemetry-resource-detector-aws/.eslintignore b/packages/opentelemetry-resource-detector-aws/.eslintignore new file mode 100644 index 00000000000..378eac25d31 --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/.eslintignore @@ -0,0 +1 @@ +build diff --git a/packages/opentelemetry-resource-detector-aws/.eslintrc.js b/packages/opentelemetry-resource-detector-aws/.eslintrc.js new file mode 100644 index 00000000000..9dfe62f9b8c --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/.eslintrc.js @@ -0,0 +1,9 @@ +module.exports = { + "env": { + "mocha": true, + "commonjs": true, + "node": true, + "browser": true + }, + ...require('../../eslint.config.js') +} diff --git a/packages/opentelemetry-resource-detector-aws/.npmignore b/packages/opentelemetry-resource-detector-aws/.npmignore new file mode 100644 index 00000000000..9505ba9450f --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/packages/opentelemetry-resource-detector-aws/LICENSE b/packages/opentelemetry-resource-detector-aws/LICENSE new file mode 100644 index 00000000000..b0e74c7d159 --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/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 [2020] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/opentelemetry-resource-detector-aws/README.md b/packages/opentelemetry-resource-detector-aws/README.md new file mode 100644 index 00000000000..e3551cc496a --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/README.md @@ -0,0 +1,44 @@ +# OpenTelemetry Resource Detector for AWS + +[![Gitter chat][gitter-image]][gitter-url] +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +The OpenTelemetry Resource is an immutable representation of the entity producing telemetry. For example, a process producing telemetry that is running in a container on Kubernetes has a Pod name, it is in a namespace and possibly is part of a Deployment which also has a name. All three of these attributes can be included in the `Resource`. + +[This document][resource-semantic_conventions] defines standard attributes for resources. + +## Installation + +```bash +npm install --save @opentelemetry/resource-detector-aws +``` + +## Usage + +> TODO + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us on [gitter][gitter-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg +[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-resources +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-resources +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/resources +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fresources.svg + +[resource-semantic_conventions]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/resource/semantic_conventions diff --git a/packages/opentelemetry-resource-detector-aws/package.json b/packages/opentelemetry-resource-detector-aws/package.json new file mode 100644 index 00000000000..8cc341f78b2 --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/package.json @@ -0,0 +1,63 @@ +{ + "name": "@opentelemetry/resource-detector-aws", + "version": "0.10.2", + "description": "OpenTelemetry SDK resource detector for AWS", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "tdd": "npm run test -- --watch-extensions ts --watch", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "clean": "rimraf build/*", + "precompile": "tsc --version", + "version:update": "node ../../scripts/version-update.js", + "compile": "npm run version:update && tsc -p .", + "prepare": "npm run compile" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "resources", + "stats", + "profiling" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "8.0.1", + "@types/node": "14.0.27", + "@types/sinon": "9.0.4", + "codecov": "3.7.2", + "gts": "2.0.2", + "mocha": "7.2.0", + "nock": "12.0.3", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "sinon": "9.0.2", + "ts-mocha": "7.0.0", + "ts-node": "8.10.2", + "typescript": "3.9.7" + }, + "dependencies": { + "@opentelemetry/api": "^0.10.2", + "@opentelemetry/core": "^0.10.2", + "@opentelemetry/resources": "^0.10.2" + } +} diff --git a/packages/opentelemetry-resources/src/platform/node/detectors/AwsEc2Detector.ts b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts similarity index 92% rename from packages/opentelemetry-resources/src/platform/node/detectors/AwsEc2Detector.ts rename to packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts index 76fd11527ae..adf687a3999 100644 --- a/packages/opentelemetry-resources/src/platform/node/detectors/AwsEc2Detector.ts +++ b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts @@ -14,11 +14,13 @@ * limitations under the License. */ +import { + Detector, + Resource, + CLOUD_RESOURCE, + HOST_RESOURCE, +} from '@opentelemetry/resources'; import * as http from 'http'; -import { Resource } from '../../../Resource'; -import { CLOUD_RESOURCE, HOST_RESOURCE } from '../../../constants'; -import { Detector } from '../../../types'; -import { ResourceDetectionConfigWithLogger } from '../../../config'; /** * The AwsEc2Detector can be used to detect if a process is running in AWS EC2 @@ -42,7 +44,7 @@ class AwsEc2Detector implements Detector { * * @param config The resource detection config with a required logger */ - async detect(config: ResourceDetectionConfigWithLogger): Promise { + async detect(config: any): Promise { try { const { accountId, diff --git a/packages/opentelemetry-resources/src/platform/node/detectors/index.ts b/packages/opentelemetry-resource-detector-aws/src/detectors/index.ts similarity index 81% rename from packages/opentelemetry-resources/src/platform/node/detectors/index.ts rename to packages/opentelemetry-resource-detector-aws/src/detectors/index.ts index c0c3c37b2c8..215622744f8 100644 --- a/packages/opentelemetry-resources/src/platform/node/detectors/index.ts +++ b/packages/opentelemetry-resource-detector-aws/src/detectors/index.ts @@ -14,6 +14,4 @@ * limitations under the License. */ -export { awsEc2Detector } from './AwsEc2Detector'; -export { envDetector } from './EnvDetector'; -export { gcpDetector } from './GcpDetector'; +export * from './AwsEc2Detector'; diff --git a/packages/opentelemetry-resource-detector-aws/src/index.ts b/packages/opentelemetry-resource-detector-aws/src/index.ts new file mode 100644 index 00000000000..0acba8788cf --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/src/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './detectors'; diff --git a/packages/opentelemetry-resource-detector-aws/src/version.ts b/packages/opentelemetry-resource-detector-aws/src/version.ts new file mode 100644 index 00000000000..ea45ee2fc46 --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/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.10.2'; diff --git a/packages/opentelemetry-resources/test/detectors/AwsEc2Detector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts similarity index 95% rename from packages/opentelemetry-resources/test/detectors/AwsEc2Detector.test.ts rename to packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts index 9b9e6eb0355..3dc45c5a083 100644 --- a/packages/opentelemetry-resources/test/detectors/AwsEc2Detector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts @@ -17,8 +17,8 @@ import * as nock from 'nock'; import * as assert from 'assert'; import { URL } from 'url'; -import { Resource } from '../../src'; -import { awsEc2Detector } from '../../src/platform/node/detectors/AwsEc2Detector'; +import { Resource } from '@opentelemetry/resources'; +import { awsEc2Detector } from '../../src'; import { assertCloudResource, assertHostResource, diff --git a/packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts b/packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts new file mode 100644 index 00000000000..1b98b02eeb1 --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts @@ -0,0 +1,277 @@ +/* + * 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 { SDK_INFO } from '@opentelemetry/core'; +import * as assert from 'assert'; +import { + Resource, + CLOUD_RESOURCE, + CONTAINER_RESOURCE, + HOST_RESOURCE, + K8S_RESOURCE, + TELEMETRY_SDK_RESOURCE, + SERVICE_RESOURCE, +} from '@opentelemetry/resources'; + +/** + * Test utility method to validate a cloud resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertCloudResource = ( + resource: Resource, + validations: { + provider?: string; + accountId?: string; + region?: string; + zone?: string; + } +) => { + assertHasOneLabel(CLOUD_RESOURCE, resource); + if (validations.provider) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.PROVIDER], + validations.provider + ); + if (validations.accountId) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.ACCOUNT_ID], + validations.accountId + ); + if (validations.region) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.REGION], + validations.region + ); + if (validations.zone) + assert.strictEqual(resource.labels[CLOUD_RESOURCE.ZONE], validations.zone); +}; + +/** + * Test utility method to validate a container resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertContainerResource = ( + resource: Resource, + validations: { + name?: string; + imageName?: string; + imageTag?: string; + } +) => { + assertHasOneLabel(CONTAINER_RESOURCE, resource); + if (validations.name) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.NAME], + validations.name + ); + if (validations.imageName) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.IMAGE_NAME], + validations.imageName + ); + if (validations.imageTag) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.IMAGE_TAG], + validations.imageTag + ); +}; + +/** + * Test utility method to validate a host resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertHostResource = ( + resource: Resource, + validations: { + hostName?: string; + id?: string; + name?: string; + hostType?: string; + imageName?: string; + imageId?: string; + imageVersion?: string; + } +) => { + assertHasOneLabel(HOST_RESOURCE, resource); + if (validations.hostName) + assert.strictEqual( + resource.labels[HOST_RESOURCE.HOSTNAME], + validations.hostName + ); + if (validations.id) + assert.strictEqual(resource.labels[HOST_RESOURCE.ID], validations.id); + if (validations.name) + assert.strictEqual(resource.labels[HOST_RESOURCE.NAME], validations.name); + if (validations.hostType) + assert.strictEqual( + resource.labels[HOST_RESOURCE.TYPE], + validations.hostType + ); + if (validations.imageName) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_NAME], + validations.imageName + ); + if (validations.imageId) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_ID], + validations.imageId + ); + if (validations.imageVersion) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_VERSION], + validations.imageVersion + ); +}; + +/** + * Test utility method to validate a K8s resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertK8sResource = ( + resource: Resource, + validations: { + clusterName?: string; + namespaceName?: string; + podName?: string; + deploymentName?: string; + } +) => { + assertHasOneLabel(K8S_RESOURCE, resource); + if (validations.clusterName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.CLUSTER_NAME], + validations.clusterName + ); + if (validations.namespaceName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.NAMESPACE_NAME], + validations.namespaceName + ); + if (validations.podName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.POD_NAME], + validations.podName + ); + if (validations.deploymentName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.DEPLOYMENT_NAME], + validations.deploymentName + ); +}; + +/** + * Test utility method to validate a telemetry sdk resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertTelemetrySDKResource = ( + resource: Resource, + validations: { + name?: string; + language?: string; + version?: string; + } +) => { + const defaults = { + name: SDK_INFO.NAME, + language: SDK_INFO.LANGUAGE, + version: SDK_INFO.VERSION, + }; + validations = { ...defaults, ...validations }; + + if (validations.name) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.NAME], + validations.name + ); + if (validations.language) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.LANGUAGE], + validations.language + ); + if (validations.version) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.VERSION], + validations.version + ); +}; + +/** + * Test utility method to validate a service resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertServiceResource = ( + resource: Resource, + validations: { + name: string; + instanceId: string; + namespace?: string; + version?: string; + } +) => { + assert.strictEqual(resource.labels[SERVICE_RESOURCE.NAME], validations.name); + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.INSTANCE_ID], + validations.instanceId + ); + if (validations.namespace) + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.NAMESPACE], + validations.namespace + ); + if (validations.version) + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.VERSION], + validations.version + ); +}; + +/** + * Test utility method to validate an empty resource + * + * @param resource the Resource to validate + */ +export const assertEmptyResource = (resource: Resource) => { + assert.strictEqual(Object.keys(resource.labels).length, 0); +}; + +const assertHasOneLabel = ( + constants: { [key: string]: string }, + resource: Resource +): void => { + const hasOne = Object.values(constants).reduce( + // eslint-disable-next-line no-prototype-builtins + (found, key) => found || resource.labels.hasOwnProperty(key), + false + ); + assert.ok( + hasOne, + 'Resource must have one of the following labels: ' + + Object.values(constants).join(', ') + ); +}; diff --git a/packages/opentelemetry-resource-detector-aws/tsconfig.json b/packages/opentelemetry-resource-detector-aws/tsconfig.json new file mode 100644 index 00000000000..e4b3b29e6a2 --- /dev/null +++ b/packages/opentelemetry-resource-detector-aws/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +} diff --git a/packages/opentelemetry-resource-detector-env/.eslintignore b/packages/opentelemetry-resource-detector-env/.eslintignore new file mode 100644 index 00000000000..378eac25d31 --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/.eslintignore @@ -0,0 +1 @@ +build diff --git a/packages/opentelemetry-resource-detector-env/.eslintrc.js b/packages/opentelemetry-resource-detector-env/.eslintrc.js new file mode 100644 index 00000000000..9dfe62f9b8c --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/.eslintrc.js @@ -0,0 +1,9 @@ +module.exports = { + "env": { + "mocha": true, + "commonjs": true, + "node": true, + "browser": true + }, + ...require('../../eslint.config.js') +} diff --git a/packages/opentelemetry-resource-detector-env/.npmignore b/packages/opentelemetry-resource-detector-env/.npmignore new file mode 100644 index 00000000000..9505ba9450f --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/packages/opentelemetry-resource-detector-env/LICENSE b/packages/opentelemetry-resource-detector-env/LICENSE new file mode 100644 index 00000000000..b0e74c7d159 --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/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 [2020] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/opentelemetry-resource-detector-env/README.md b/packages/opentelemetry-resource-detector-env/README.md new file mode 100644 index 00000000000..b9f3cc60e8d --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/README.md @@ -0,0 +1,44 @@ +# OpenTelemetry Resource Detector for OpenTelemetry Environment Variables + +[![Gitter chat][gitter-image]][gitter-url] +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +The OpenTelemetry Resource is an immutable representation of the entity producing telemetry. For example, a process producing telemetry that is running in a container on Kubernetes has a Pod name, it is in a namespace and possibly is part of a Deployment which also has a name. All three of these attributes can be included in the `Resource`. + +[This document][resource-semantic_conventions] defines standard attributes for resources. + +## Installation + +```bash +npm install --save @opentelemetry/resource-detector-env +``` + +## Usage + +> TODO + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us on [gitter][gitter-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg +[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-resources +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-resources +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/resources +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fresources.svg + +[resource-semantic_conventions]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/resource/semantic_conventions diff --git a/packages/opentelemetry-resource-detector-env/package.json b/packages/opentelemetry-resource-detector-env/package.json new file mode 100644 index 00000000000..3fcef8abbe1 --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/package.json @@ -0,0 +1,63 @@ +{ + "name": "@opentelemetry/resource-detector-env", + "version": "0.10.2", + "description": "OpenTelemetry SDK resource detector - Environment", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "tdd": "npm run test -- --watch-extensions ts --watch", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "clean": "rimraf build/*", + "precompile": "tsc --version", + "version:update": "node ../../scripts/version-update.js", + "compile": "npm run version:update && tsc -p .", + "prepare": "npm run compile" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "resources", + "stats", + "profiling" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "8.0.1", + "@types/node": "14.0.27", + "@types/sinon": "9.0.4", + "codecov": "3.7.2", + "gts": "2.0.2", + "mocha": "7.2.0", + "nock": "12.0.3", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "sinon": "9.0.2", + "ts-mocha": "7.0.0", + "ts-node": "8.10.2", + "typescript": "3.9.7" + }, + "dependencies": { + "@opentelemetry/api": "^0.10.2", + "@opentelemetry/core": "^0.10.2", + "@opentelemetry/resources": "^0.10.2" + } +} diff --git a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts b/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts similarity index 96% rename from packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts rename to packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts index 718c566f126..ca0416ba3c3 100644 --- a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts +++ b/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts @@ -14,9 +14,12 @@ * limitations under the License. */ -import { Resource } from '../../../Resource'; -import { Detector, ResourceLabels } from '../../../types'; -import { ResourceDetectionConfigWithLogger } from '../../../config'; +import { + Detector, + Resource, + ResourceDetectionConfigWithLogger, + ResourceLabels, +} from '@opentelemetry/resources'; /** * EnvDetector can be used to detect the presence of and create a Resource diff --git a/packages/opentelemetry-resource-detector-env/src/detectors/index.ts b/packages/opentelemetry-resource-detector-env/src/detectors/index.ts new file mode 100644 index 00000000000..f2b4223be18 --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/src/detectors/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './EnvDetector'; diff --git a/packages/opentelemetry-resource-detector-env/src/index.ts b/packages/opentelemetry-resource-detector-env/src/index.ts new file mode 100644 index 00000000000..0acba8788cf --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/src/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './detectors'; diff --git a/packages/opentelemetry-resource-detector-env/src/version.ts b/packages/opentelemetry-resource-detector-env/src/version.ts new file mode 100644 index 00000000000..ea45ee2fc46 --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/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.10.2'; diff --git a/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts b/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts similarity index 91% rename from packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts rename to packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts index 894de6e8700..80a4e6bb5ce 100644 --- a/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts +++ b/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts @@ -14,14 +14,13 @@ * limitations under the License. */ -import { Resource } from '../../src/Resource'; -import { envDetector } from '../../src/platform/node/detectors/EnvDetector'; +import { envDetector } from '../../src'; +import { NoopLogger } from '@opentelemetry/core'; +import { Resource, K8S_RESOURCE } from '@opentelemetry/resources'; import { assertK8sResource, assertEmptyResource, } from '../util/resource-assertions'; -import { K8S_RESOURCE } from '../../src'; -import { NoopLogger } from '@opentelemetry/core'; describe('envDetector()', () => { describe('with valid env', () => { diff --git a/packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts b/packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts new file mode 100644 index 00000000000..1b98b02eeb1 --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts @@ -0,0 +1,277 @@ +/* + * 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 { SDK_INFO } from '@opentelemetry/core'; +import * as assert from 'assert'; +import { + Resource, + CLOUD_RESOURCE, + CONTAINER_RESOURCE, + HOST_RESOURCE, + K8S_RESOURCE, + TELEMETRY_SDK_RESOURCE, + SERVICE_RESOURCE, +} from '@opentelemetry/resources'; + +/** + * Test utility method to validate a cloud resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertCloudResource = ( + resource: Resource, + validations: { + provider?: string; + accountId?: string; + region?: string; + zone?: string; + } +) => { + assertHasOneLabel(CLOUD_RESOURCE, resource); + if (validations.provider) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.PROVIDER], + validations.provider + ); + if (validations.accountId) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.ACCOUNT_ID], + validations.accountId + ); + if (validations.region) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.REGION], + validations.region + ); + if (validations.zone) + assert.strictEqual(resource.labels[CLOUD_RESOURCE.ZONE], validations.zone); +}; + +/** + * Test utility method to validate a container resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertContainerResource = ( + resource: Resource, + validations: { + name?: string; + imageName?: string; + imageTag?: string; + } +) => { + assertHasOneLabel(CONTAINER_RESOURCE, resource); + if (validations.name) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.NAME], + validations.name + ); + if (validations.imageName) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.IMAGE_NAME], + validations.imageName + ); + if (validations.imageTag) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.IMAGE_TAG], + validations.imageTag + ); +}; + +/** + * Test utility method to validate a host resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertHostResource = ( + resource: Resource, + validations: { + hostName?: string; + id?: string; + name?: string; + hostType?: string; + imageName?: string; + imageId?: string; + imageVersion?: string; + } +) => { + assertHasOneLabel(HOST_RESOURCE, resource); + if (validations.hostName) + assert.strictEqual( + resource.labels[HOST_RESOURCE.HOSTNAME], + validations.hostName + ); + if (validations.id) + assert.strictEqual(resource.labels[HOST_RESOURCE.ID], validations.id); + if (validations.name) + assert.strictEqual(resource.labels[HOST_RESOURCE.NAME], validations.name); + if (validations.hostType) + assert.strictEqual( + resource.labels[HOST_RESOURCE.TYPE], + validations.hostType + ); + if (validations.imageName) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_NAME], + validations.imageName + ); + if (validations.imageId) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_ID], + validations.imageId + ); + if (validations.imageVersion) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_VERSION], + validations.imageVersion + ); +}; + +/** + * Test utility method to validate a K8s resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertK8sResource = ( + resource: Resource, + validations: { + clusterName?: string; + namespaceName?: string; + podName?: string; + deploymentName?: string; + } +) => { + assertHasOneLabel(K8S_RESOURCE, resource); + if (validations.clusterName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.CLUSTER_NAME], + validations.clusterName + ); + if (validations.namespaceName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.NAMESPACE_NAME], + validations.namespaceName + ); + if (validations.podName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.POD_NAME], + validations.podName + ); + if (validations.deploymentName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.DEPLOYMENT_NAME], + validations.deploymentName + ); +}; + +/** + * Test utility method to validate a telemetry sdk resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertTelemetrySDKResource = ( + resource: Resource, + validations: { + name?: string; + language?: string; + version?: string; + } +) => { + const defaults = { + name: SDK_INFO.NAME, + language: SDK_INFO.LANGUAGE, + version: SDK_INFO.VERSION, + }; + validations = { ...defaults, ...validations }; + + if (validations.name) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.NAME], + validations.name + ); + if (validations.language) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.LANGUAGE], + validations.language + ); + if (validations.version) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.VERSION], + validations.version + ); +}; + +/** + * Test utility method to validate a service resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertServiceResource = ( + resource: Resource, + validations: { + name: string; + instanceId: string; + namespace?: string; + version?: string; + } +) => { + assert.strictEqual(resource.labels[SERVICE_RESOURCE.NAME], validations.name); + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.INSTANCE_ID], + validations.instanceId + ); + if (validations.namespace) + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.NAMESPACE], + validations.namespace + ); + if (validations.version) + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.VERSION], + validations.version + ); +}; + +/** + * Test utility method to validate an empty resource + * + * @param resource the Resource to validate + */ +export const assertEmptyResource = (resource: Resource) => { + assert.strictEqual(Object.keys(resource.labels).length, 0); +}; + +const assertHasOneLabel = ( + constants: { [key: string]: string }, + resource: Resource +): void => { + const hasOne = Object.values(constants).reduce( + // eslint-disable-next-line no-prototype-builtins + (found, key) => found || resource.labels.hasOwnProperty(key), + false + ); + assert.ok( + hasOne, + 'Resource must have one of the following labels: ' + + Object.values(constants).join(', ') + ); +}; diff --git a/packages/opentelemetry-resource-detector-env/tsconfig.json b/packages/opentelemetry-resource-detector-env/tsconfig.json new file mode 100644 index 00000000000..e4b3b29e6a2 --- /dev/null +++ b/packages/opentelemetry-resource-detector-env/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +} diff --git a/packages/opentelemetry-resource-detector-gcp/.eslintignore b/packages/opentelemetry-resource-detector-gcp/.eslintignore new file mode 100644 index 00000000000..378eac25d31 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/.eslintignore @@ -0,0 +1 @@ +build diff --git a/packages/opentelemetry-resource-detector-gcp/.eslintrc.js b/packages/opentelemetry-resource-detector-gcp/.eslintrc.js new file mode 100644 index 00000000000..9dfe62f9b8c --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/.eslintrc.js @@ -0,0 +1,9 @@ +module.exports = { + "env": { + "mocha": true, + "commonjs": true, + "node": true, + "browser": true + }, + ...require('../../eslint.config.js') +} diff --git a/packages/opentelemetry-resource-detector-gcp/.npmignore b/packages/opentelemetry-resource-detector-gcp/.npmignore new file mode 100644 index 00000000000..9505ba9450f --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/packages/opentelemetry-resource-detector-gcp/LICENSE b/packages/opentelemetry-resource-detector-gcp/LICENSE new file mode 100644 index 00000000000..b0e74c7d159 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/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 [2020] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/opentelemetry-resource-detector-gcp/README.md b/packages/opentelemetry-resource-detector-gcp/README.md new file mode 100644 index 00000000000..ccb2af7b091 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/README.md @@ -0,0 +1,44 @@ +# OpenTelemetry Resource Detector for GCP + +[![Gitter chat][gitter-image]][gitter-url] +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +The OpenTelemetry Resource is an immutable representation of the entity producing telemetry. For example, a process producing telemetry that is running in a container on Kubernetes has a Pod name, it is in a namespace and possibly is part of a Deployment which also has a name. All three of these attributes can be included in the `Resource`. + +[This document][resource-semantic_conventions] defines standard attributes for resources. + +## Installation + +```bash +npm install --save @opentelemetry/resource-detector-gcp +``` + +## Usage + +> TODO + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us on [gitter][gitter-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg +[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-resources +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-resources +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/resources +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fresources.svg + +[resource-semantic_conventions]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/resource/semantic_conventions diff --git a/packages/opentelemetry-resource-detector-gcp/package.json b/packages/opentelemetry-resource-detector-gcp/package.json new file mode 100644 index 00000000000..c059e00f937 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/package.json @@ -0,0 +1,64 @@ +{ + "name": "@opentelemetry/resource-detector-gcp", + "version": "0.10.2", + "description": "OpenTelemetry SDK resource detector for GCP", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "tdd": "npm run test -- --watch-extensions ts --watch", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "clean": "rimraf build/*", + "precompile": "tsc --version", + "version:update": "node ../../scripts/version-update.js", + "compile": "npm run version:update && tsc -p .", + "prepare": "npm run compile" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "resources", + "stats", + "profiling" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "8.0.1", + "@types/node": "14.0.27", + "@types/sinon": "9.0.4", + "codecov": "3.7.2", + "gts": "2.0.2", + "mocha": "7.2.0", + "nock": "12.0.3", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "sinon": "9.0.2", + "ts-mocha": "7.0.0", + "ts-node": "8.10.2", + "typescript": "3.9.7" + }, + "dependencies": { + "@opentelemetry/api": "^0.10.2", + "@opentelemetry/core": "^0.10.2", + "@opentelemetry/resources": "^0.10.2", + "gcp-metadata": "^3.5.0" + } +} diff --git a/packages/opentelemetry-resources/src/platform/node/detectors/GcpDetector.ts b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts similarity index 94% rename from packages/opentelemetry-resources/src/platform/node/detectors/GcpDetector.ts rename to packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts index a93173d1a11..5b7599156f8 100644 --- a/packages/opentelemetry-resources/src/platform/node/detectors/GcpDetector.ts +++ b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts @@ -16,15 +16,16 @@ import * as os from 'os'; import * as gcpMetadata from 'gcp-metadata'; -import { Resource } from '../../../Resource'; -import { Detector, ResourceLabels } from '../../../types'; import { + Detector, + ResourceDetectionConfigWithLogger, + Resource, + ResourceLabels, CLOUD_RESOURCE, HOST_RESOURCE, K8S_RESOURCE, CONTAINER_RESOURCE, -} from '../../../constants'; -import { ResourceDetectionConfigWithLogger } from '../../../config'; +} from '@opentelemetry/resources'; /** * The GcpDetector can be used to detect if a process is running in the Google diff --git a/packages/opentelemetry-resource-detector-gcp/src/detectors/index.ts b/packages/opentelemetry-resource-detector-gcp/src/detectors/index.ts new file mode 100644 index 00000000000..9e856721bc4 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/src/detectors/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './GcpDetector'; diff --git a/packages/opentelemetry-resource-detector-gcp/src/index.ts b/packages/opentelemetry-resource-detector-gcp/src/index.ts new file mode 100644 index 00000000000..0acba8788cf --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/src/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './detectors'; diff --git a/packages/opentelemetry-resource-detector-gcp/src/version.ts b/packages/opentelemetry-resource-detector-gcp/src/version.ts new file mode 100644 index 00000000000..ea45ee2fc46 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/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.10.2'; diff --git a/packages/opentelemetry-resources/test/detectors/GcpDetector.test.ts b/packages/opentelemetry-resource-detector-gcp/test/detectors/GcpDetector.test.ts similarity index 97% rename from packages/opentelemetry-resources/test/detectors/GcpDetector.test.ts rename to packages/opentelemetry-resource-detector-gcp/test/detectors/GcpDetector.test.ts index c476feb5a7f..c7c5f0c84cc 100644 --- a/packages/opentelemetry-resources/test/detectors/GcpDetector.test.ts +++ b/packages/opentelemetry-resource-detector-gcp/test/detectors/GcpDetector.test.ts @@ -23,16 +23,16 @@ import { resetIsAvailableCache, } from 'gcp-metadata'; import * as nock from 'nock'; -import { Resource } from '../../src'; -import { gcpDetector } from '../../src/platform/node/detectors'; +import { gcpDetector } from '../../src'; import { assertCloudResource, assertHostResource, assertK8sResource, assertContainerResource, assertEmptyResource, -} from '../util/resource-assertions'; +} from '@opentelemetry/resources/test/util/resource-assertions'; import { NoopLogger } from '@opentelemetry/core'; +import { Resource } from '@opentelemetry/resources'; const HEADERS = { [HEADER_NAME.toLowerCase()]: HEADER_VALUE, diff --git a/packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts b/packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts new file mode 100644 index 00000000000..1b98b02eeb1 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts @@ -0,0 +1,277 @@ +/* + * 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 { SDK_INFO } from '@opentelemetry/core'; +import * as assert from 'assert'; +import { + Resource, + CLOUD_RESOURCE, + CONTAINER_RESOURCE, + HOST_RESOURCE, + K8S_RESOURCE, + TELEMETRY_SDK_RESOURCE, + SERVICE_RESOURCE, +} from '@opentelemetry/resources'; + +/** + * Test utility method to validate a cloud resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertCloudResource = ( + resource: Resource, + validations: { + provider?: string; + accountId?: string; + region?: string; + zone?: string; + } +) => { + assertHasOneLabel(CLOUD_RESOURCE, resource); + if (validations.provider) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.PROVIDER], + validations.provider + ); + if (validations.accountId) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.ACCOUNT_ID], + validations.accountId + ); + if (validations.region) + assert.strictEqual( + resource.labels[CLOUD_RESOURCE.REGION], + validations.region + ); + if (validations.zone) + assert.strictEqual(resource.labels[CLOUD_RESOURCE.ZONE], validations.zone); +}; + +/** + * Test utility method to validate a container resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertContainerResource = ( + resource: Resource, + validations: { + name?: string; + imageName?: string; + imageTag?: string; + } +) => { + assertHasOneLabel(CONTAINER_RESOURCE, resource); + if (validations.name) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.NAME], + validations.name + ); + if (validations.imageName) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.IMAGE_NAME], + validations.imageName + ); + if (validations.imageTag) + assert.strictEqual( + resource.labels[CONTAINER_RESOURCE.IMAGE_TAG], + validations.imageTag + ); +}; + +/** + * Test utility method to validate a host resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertHostResource = ( + resource: Resource, + validations: { + hostName?: string; + id?: string; + name?: string; + hostType?: string; + imageName?: string; + imageId?: string; + imageVersion?: string; + } +) => { + assertHasOneLabel(HOST_RESOURCE, resource); + if (validations.hostName) + assert.strictEqual( + resource.labels[HOST_RESOURCE.HOSTNAME], + validations.hostName + ); + if (validations.id) + assert.strictEqual(resource.labels[HOST_RESOURCE.ID], validations.id); + if (validations.name) + assert.strictEqual(resource.labels[HOST_RESOURCE.NAME], validations.name); + if (validations.hostType) + assert.strictEqual( + resource.labels[HOST_RESOURCE.TYPE], + validations.hostType + ); + if (validations.imageName) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_NAME], + validations.imageName + ); + if (validations.imageId) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_ID], + validations.imageId + ); + if (validations.imageVersion) + assert.strictEqual( + resource.labels[HOST_RESOURCE.IMAGE_VERSION], + validations.imageVersion + ); +}; + +/** + * Test utility method to validate a K8s resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertK8sResource = ( + resource: Resource, + validations: { + clusterName?: string; + namespaceName?: string; + podName?: string; + deploymentName?: string; + } +) => { + assertHasOneLabel(K8S_RESOURCE, resource); + if (validations.clusterName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.CLUSTER_NAME], + validations.clusterName + ); + if (validations.namespaceName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.NAMESPACE_NAME], + validations.namespaceName + ); + if (validations.podName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.POD_NAME], + validations.podName + ); + if (validations.deploymentName) + assert.strictEqual( + resource.labels[K8S_RESOURCE.DEPLOYMENT_NAME], + validations.deploymentName + ); +}; + +/** + * Test utility method to validate a telemetry sdk resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertTelemetrySDKResource = ( + resource: Resource, + validations: { + name?: string; + language?: string; + version?: string; + } +) => { + const defaults = { + name: SDK_INFO.NAME, + language: SDK_INFO.LANGUAGE, + version: SDK_INFO.VERSION, + }; + validations = { ...defaults, ...validations }; + + if (validations.name) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.NAME], + validations.name + ); + if (validations.language) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.LANGUAGE], + validations.language + ); + if (validations.version) + assert.strictEqual( + resource.labels[TELEMETRY_SDK_RESOURCE.VERSION], + validations.version + ); +}; + +/** + * Test utility method to validate a service resource + * + * @param resource the Resource to validate + * @param validations validations for the resource labels + */ +export const assertServiceResource = ( + resource: Resource, + validations: { + name: string; + instanceId: string; + namespace?: string; + version?: string; + } +) => { + assert.strictEqual(resource.labels[SERVICE_RESOURCE.NAME], validations.name); + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.INSTANCE_ID], + validations.instanceId + ); + if (validations.namespace) + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.NAMESPACE], + validations.namespace + ); + if (validations.version) + assert.strictEqual( + resource.labels[SERVICE_RESOURCE.VERSION], + validations.version + ); +}; + +/** + * Test utility method to validate an empty resource + * + * @param resource the Resource to validate + */ +export const assertEmptyResource = (resource: Resource) => { + assert.strictEqual(Object.keys(resource.labels).length, 0); +}; + +const assertHasOneLabel = ( + constants: { [key: string]: string }, + resource: Resource +): void => { + const hasOne = Object.values(constants).reduce( + // eslint-disable-next-line no-prototype-builtins + (found, key) => found || resource.labels.hasOwnProperty(key), + false + ); + assert.ok( + hasOne, + 'Resource must have one of the following labels: ' + + Object.values(constants).join(', ') + ); +}; diff --git a/packages/opentelemetry-resource-detector-gcp/tsconfig.json b/packages/opentelemetry-resource-detector-gcp/tsconfig.json new file mode 100644 index 00000000000..e4b3b29e6a2 --- /dev/null +++ b/packages/opentelemetry-resource-detector-gcp/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +} diff --git a/packages/opentelemetry-resources/src/Resource.ts b/packages/opentelemetry-resources/src/Resource.ts index f8dc503c1cb..849acd0beea 100644 --- a/packages/opentelemetry-resources/src/Resource.ts +++ b/packages/opentelemetry-resources/src/Resource.ts @@ -49,7 +49,12 @@ export class Resource { * about the entity as numbers, strings or booleans * TODO: Consider to add check/validation on labels. */ - readonly labels: ResourceLabels + readonly labels: ResourceLabels, + + /** + * Name of the resource detector that detected this resource + */ + readonly detector: string = 'Unknown detector' ) {} /** diff --git a/packages/opentelemetry-resources/src/config.ts b/packages/opentelemetry-resources/src/config.ts index 8eb9007eb6a..250d055f7ee 100644 --- a/packages/opentelemetry-resources/src/config.ts +++ b/packages/opentelemetry-resources/src/config.ts @@ -15,6 +15,7 @@ */ import { Logger } from '@opentelemetry/api'; +import type { Detector } from './types'; /** * ResourceDetectionConfig provides an interface for configuring resource auto-detection. @@ -22,6 +23,7 @@ import { Logger } from '@opentelemetry/api'; export interface ResourceDetectionConfig { /** Optional Logger. */ logger?: Logger; + detectors?: Array; } /** diff --git a/packages/opentelemetry-resources/src/index.ts b/packages/opentelemetry-resources/src/index.ts index f5a851015ae..2cfef2d182f 100644 --- a/packages/opentelemetry-resources/src/index.ts +++ b/packages/opentelemetry-resources/src/index.ts @@ -18,3 +18,4 @@ export * from './Resource'; export * from './platform'; export * from './constants'; export * from './types'; +export * from './config'; diff --git a/packages/opentelemetry-resources/src/platform/index.ts b/packages/opentelemetry-resources/src/platform/index.ts index a12506ffa92..cdaf8858ce5 100644 --- a/packages/opentelemetry-resources/src/platform/index.ts +++ b/packages/opentelemetry-resources/src/platform/index.ts @@ -13,4 +13,5 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + export * from './node'; diff --git a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts index ca7add14b22..69f8db49fff 100644 --- a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts +++ b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts @@ -15,8 +15,6 @@ */ import { Resource } from '../../Resource'; -import { envDetector, awsEc2Detector, gcpDetector } from './detectors'; -import { Detector } from '../../types'; import { ResourceDetectionConfig, ResourceDetectionConfigWithLogger, @@ -25,8 +23,6 @@ import { Logger } from '@opentelemetry/api'; import * as util from 'util'; import { NoopLogger } from '@opentelemetry/core'; -const DETECTORS: Array = [envDetector, awsEc2Detector, gcpDetector]; - /** * Runs all resource detectors and returns the results merged into a single * Resource. @@ -39,12 +35,12 @@ export const detectResources = async ( const internalConfig: ResourceDetectionConfigWithLogger = Object.assign( { logger: new NoopLogger(), - }, + } as ResourceDetectionConfigWithLogger, config ); const resources: Array = await Promise.all( - DETECTORS.map(d => { + (internalConfig.detectors || []).map(d => { try { return d.detect(internalConfig); } catch { @@ -69,7 +65,7 @@ export const detectResources = async ( * @param resources The array of {@link Resource} that should be logged. Empty entried will be ignored. */ const logResources = (logger: Logger, resources: Array) => { - resources.forEach((resource, index) => { + resources.forEach(resource => { // Print only populated resources if (Object.keys(resource.labels).length > 0) { const resourceDebugString = util.inspect(resource.labels, { @@ -78,9 +74,7 @@ const logResources = (logger: Logger, resources: Array) => { sorted: true, compact: false, }); - const detectorName = DETECTORS[index].constructor - ? DETECTORS[index].constructor.name - : 'Unknown detector'; + const detectorName = resource.detector; logger.debug(`${detectorName} found resource.`); logger.debug(resourceDebugString); } diff --git a/packages/opentelemetry-resources/test/detect-resources.test.ts b/packages/opentelemetry-resources/test/detect-resources.test.ts deleted file mode 100644 index b607efa0d69..00000000000 --- a/packages/opentelemetry-resources/test/detect-resources.test.ts +++ /dev/null @@ -1,275 +0,0 @@ -/* - * 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 nock from 'nock'; -import * as sinon from 'sinon'; -import * as assert from 'assert'; -import { URL } from 'url'; -import { Resource, detectResources } from '../src'; -import { awsEc2Detector } from '../src/platform/node/detectors'; -import { - assertServiceResource, - assertCloudResource, - assertHostResource, -} from './util/resource-assertions'; -import { - BASE_PATH, - HEADER_NAME, - HEADER_VALUE, - HOST_ADDRESS, - SECONDARY_HOST_ADDRESS, - resetIsAvailableCache, -} from 'gcp-metadata'; - -const HEADERS = { - [HEADER_NAME.toLowerCase()]: HEADER_VALUE, -}; -const INSTANCE_PATH = BASE_PATH + '/instance'; -const INSTANCE_ID_PATH = BASE_PATH + '/instance/id'; -const PROJECT_ID_PATH = BASE_PATH + '/project/project-id'; -const ZONE_PATH = BASE_PATH + '/instance/zone'; -const CLUSTER_NAME_PATH = BASE_PATH + '/instance/attributes/cluster-name'; - -const { origin: AWS_HOST, pathname: AWS_PATH } = new URL( - awsEc2Detector.AWS_INSTANCE_IDENTITY_DOCUMENT_URI -); - -const mockedAwsResponse = { - instanceId: 'my-instance-id', - instanceType: 'my-instance-type', - accountId: 'my-account-id', - region: 'my-region', - availabilityZone: 'my-zone', -}; - -describe('detectResources', async () => { - beforeEach(() => { - nock.disableNetConnect(); - process.env.OTEL_RESOURCE_LABELS = - 'service.instance.id=627cc493,service.name=my-service,service.namespace=default,service.version=0.0.1'; - }); - - afterEach(() => { - nock.cleanAll(); - nock.enableNetConnect(); - delete process.env.OTEL_RESOURCE_LABELS; - }); - - describe('in GCP environment', () => { - after(() => { - resetIsAvailableCache(); - }); - - it('returns a merged resource', async () => { - const gcpScope = nock(HOST_ADDRESS) - .get(INSTANCE_PATH) - .reply(200, {}, HEADERS) - .get(INSTANCE_ID_PATH) - .reply(200, () => 452003179927758, HEADERS) - .get(PROJECT_ID_PATH) - .reply(200, () => 'my-project-id', HEADERS) - .get(ZONE_PATH) - .reply(200, () => 'project/zone/my-zone', HEADERS) - .get(CLUSTER_NAME_PATH) - .reply(404); - const gcpSecondaryScope = nock(SECONDARY_HOST_ADDRESS) - .get(INSTANCE_PATH) - .reply(200, {}, HEADERS); - const awsScope = nock(AWS_HOST) - .get(AWS_PATH) - .replyWithError({ code: 'ENOTFOUND' }); - const resource: Resource = await detectResources(); - awsScope.done(); - gcpSecondaryScope.done(); - gcpScope.done(); - - assertCloudResource(resource, { - provider: 'gcp', - accountId: 'my-project-id', - zone: 'my-zone', - }); - assertHostResource(resource, { id: '452003179927758' }); - assertServiceResource(resource, { - instanceId: '627cc493', - name: 'my-service', - namespace: 'default', - version: '0.0.1', - }); - }); - }); - - describe('in AWS environment', () => { - it('returns a merged resource', async () => { - const gcpScope = nock(HOST_ADDRESS).get(INSTANCE_PATH).replyWithError({ - code: 'ENOTFOUND', - }); - const gcpSecondaryScope = nock(SECONDARY_HOST_ADDRESS) - .get(INSTANCE_PATH) - .replyWithError({ - code: 'ENOTFOUND', - }); - const awsScope = nock(AWS_HOST) - .get(AWS_PATH) - .reply(200, () => mockedAwsResponse); - const resource: Resource = await detectResources(); - gcpSecondaryScope.done(); - gcpScope.done(); - awsScope.done(); - - assertCloudResource(resource, { - provider: 'aws', - accountId: 'my-account-id', - region: 'my-region', - zone: 'my-zone', - }); - assertHostResource(resource, { - id: 'my-instance-id', - hostType: 'my-instance-type', - }); - assertServiceResource(resource, { - instanceId: '627cc493', - name: 'my-service', - namespace: 'default', - version: '0.0.1', - }); - }); - }); - - describe('with a buggy detector', () => { - it('returns a merged resource', async () => { - const stub = sinon.stub(awsEc2Detector, 'detect').throws(); - const resource: Resource = await detectResources(); - - assertServiceResource(resource, { - instanceId: '627cc493', - name: 'my-service', - namespace: 'default', - version: '0.0.1', - }); - - stub.restore(); - }); - }); - - describe('with a debug logger', () => { - // Local functions to test if a mocked method is ever called with a specific argument or regex matching for an argument. - // Needed because of race condition with parallel detectors. - const callArgsContains = ( - mockedFunction: sinon.SinonSpy, - arg: any - ): boolean => { - return mockedFunction.getCalls().some(call => { - return call.args.some(callarg => arg === callarg); - }); - }; - const callArgsMatches = ( - mockedFunction: sinon.SinonSpy, - regex: RegExp - ): boolean => { - return mockedFunction.getCalls().some(call => { - return regex.test(call.args.toString()); - }); - }; - - it('prints detected resources and debug messages to the logger', async () => { - // This test depends on the env detector to be functioning as intended - const mockedLoggerMethod = sinon.fake(); - await detectResources({ - logger: { - debug: mockedLoggerMethod, - info: sinon.fake(), - warn: sinon.fake(), - error: sinon.fake(), - }, - }); - - // Test for AWS and GCP Detector failure - assert.ok( - callArgsContains( - mockedLoggerMethod, - 'GcpDetector failed: GCP Metadata unavailable.' - ) - ); - assert.ok( - callArgsContains( - mockedLoggerMethod, - 'AwsEc2Detector failed: Nock: Disallowed net connect for "169.254.169.254:80/latest/dynamic/instance-identity/document"' - ) - ); - // Test that the Env Detector successfully found its resource and populated it with the right values. - assert.ok( - callArgsContains(mockedLoggerMethod, 'EnvDetector found resource.') - ); - // Regex formatting accounts for whitespace variations in util.inspect output over different node versions - assert.ok( - callArgsMatches( - mockedLoggerMethod, - /{\s+'service\.instance\.id':\s+'627cc493',\s+'service\.name':\s+'my-service',\s+'service\.namespace':\s+'default',\s+'service\.version':\s+'0\.0\.1'\s+}\s*/ - ) - ); - }); - - describe('with missing environemnt variable', () => { - beforeEach(() => { - delete process.env.OTEL_RESOURCE_LABELS; - }); - - it('prints correct error messages when EnvDetector has no env variable', async () => { - const mockedLoggerMethod = sinon.fake(); - await detectResources({ - logger: { - debug: mockedLoggerMethod, - info: sinon.fake(), - warn: sinon.fake(), - error: sinon.fake(), - }, - }); - - assert.ok( - callArgsContains( - mockedLoggerMethod, - 'EnvDetector failed: Environment variable "OTEL_RESOURCE_LABELS" is missing.' - ) - ); - }); - }); - - describe('with a faulty environment variable', () => { - beforeEach(() => { - process.env.OTEL_RESOURCE_LABELS = 'bad=~label'; - }); - - it('prints correct error messages when EnvDetector has an invalid variable', async () => { - const mockedLoggerMethod = sinon.fake(); - await detectResources({ - logger: { - debug: mockedLoggerMethod, - info: sinon.fake(), - warn: sinon.fake(), - error: sinon.fake(), - }, - }); - - assert.ok( - callArgsContains( - mockedLoggerMethod, - 'EnvDetector failed: Label value should be a ASCII string with a length not exceed 255 characters.' - ) - ); - }); - }); - }); -}); diff --git a/packages/opentelemetry-resources/test/util/sample-detector.ts b/packages/opentelemetry-resources/test/util/sample-detector.ts new file mode 100644 index 00000000000..1ed6f258efd --- /dev/null +++ b/packages/opentelemetry-resources/test/util/sample-detector.ts @@ -0,0 +1,32 @@ +/* + * 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 { Detector, Resource, CLOUD_RESOURCE, HOST_RESOURCE } from '../../src'; + +class SampleDetector implements Detector { + async detect(): Promise { + return new Resource({ + [CLOUD_RESOURCE.PROVIDER]: 'provider', + [CLOUD_RESOURCE.ACCOUNT_ID]: 'accountId', + [CLOUD_RESOURCE.REGION]: 'region', + [CLOUD_RESOURCE.ZONE]: 'zone', + [HOST_RESOURCE.ID]: 'instanceId', + [HOST_RESOURCE.TYPE]: 'instanceType', + }); + } +} + +export const sampleDetector = new SampleDetector(); diff --git a/packages/opentelemetry-sdk-node/package.json b/packages/opentelemetry-sdk-node/package.json index 8f79ccaf658..a9c8d814444 100644 --- a/packages/opentelemetry-sdk-node/package.json +++ b/packages/opentelemetry-sdk-node/package.json @@ -48,7 +48,11 @@ "@opentelemetry/metrics": "^0.10.2", "@opentelemetry/node": "^0.10.2", "@opentelemetry/resources": "^0.10.2", - "@opentelemetry/tracing": "^0.10.2" + "@opentelemetry/tracing": "^0.10.2", + "@opentelemetry/resource-detector-aws": "^0.10.2", + "@opentelemetry/resource-detector-gcp": "^0.10.2", + "@opentelemetry/resource-detector-env": "^0.10.2", + "nock": "12.0.3" }, "devDependencies": { "@opentelemetry/context-async-hooks": "^0.10.2", @@ -56,6 +60,7 @@ "@types/node": "14.0.27", "@types/sinon": "9.0.4", "codecov": "3.7.2", + "gcp-metadata": "^3.5.0", "gts": "2.0.2", "istanbul-instrumenter-loader": "3.0.1", "mocha": "7.2.0", diff --git a/packages/opentelemetry-sdk-node/src/sdk.ts b/packages/opentelemetry-sdk-node/src/sdk.ts index 3b27e1331ec..ae75223b760 100644 --- a/packages/opentelemetry-sdk-node/src/sdk.ts +++ b/packages/opentelemetry-sdk-node/src/sdk.ts @@ -18,9 +18,12 @@ import { HttpTextPropagator, metrics } from '@opentelemetry/api'; import { ContextManager } from '@opentelemetry/context-base'; import { MeterConfig, MeterProvider } from '@opentelemetry/metrics'; import { NodeTracerConfig, NodeTracerProvider } from '@opentelemetry/node'; -import { detectResources, Resource } from '@opentelemetry/resources'; +import { detectResources, Resource, ResourceDetectionConfig } from '@opentelemetry/resources'; import { BatchSpanProcessor, SpanProcessor } from '@opentelemetry/tracing'; import { NodeSDKConfiguration } from './types'; +import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; +import { gcpDetector } from '@opentelemetry/resource-detector-gcp'; +import { envDetector } from '@opentelemetry/resource-detector-env'; /** This class represents everything needed to register a fully configured OpenTelemetry Node.js SDK */ export class NodeSDK { @@ -119,8 +122,13 @@ export class NodeSDK { } /** Detect resource attributes */ - public async detectResources() { - this.addResource(await detectResources()); + public async detectResources(config?: ResourceDetectionConfig) { + const internalConfig: ResourceDetectionConfig = { + ...config, + detectors: [awsEc2Detector, gcpDetector, envDetector], + }; + + this.addResource(await detectResources(internalConfig)); } /** Manually add a resource */ diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index 083a7681fb3..ae338df577e 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +import * as nock from 'nock'; import { context, metrics, @@ -36,6 +37,44 @@ import * as assert from 'assert'; import { NodeSDK } from '../src'; import * as NodeConfig from '@opentelemetry/node/build/src/config'; import * as Sinon from 'sinon'; +import sinon = require('sinon'); +import { Resource, detectResources } from '@opentelemetry/resources'; +import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; + +import { + assertServiceResource, + assertCloudResource, + assertHostResource, +} from '@opentelemetry/resources/test/util/resource-assertions'; +import { + BASE_PATH, + HEADER_NAME, + HEADER_VALUE, + HOST_ADDRESS, + SECONDARY_HOST_ADDRESS, + resetIsAvailableCache, +} from 'gcp-metadata'; + +const HEADERS = { + [HEADER_NAME.toLowerCase()]: HEADER_VALUE, +}; +const INSTANCE_PATH = BASE_PATH + '/instance'; +const INSTANCE_ID_PATH = BASE_PATH + '/instance/id'; +const PROJECT_ID_PATH = BASE_PATH + '/project/project-id'; +const ZONE_PATH = BASE_PATH + '/instance/zone'; +const CLUSTER_NAME_PATH = BASE_PATH + '/instance/attributes/cluster-name'; + +const { origin: AWS_HOST, pathname: AWS_PATH } = new URL( + awsEc2Detector.AWS_INSTANCE_IDENTITY_DOCUMENT_URI +); + +const mockedAwsResponse = { + instanceId: 'my-instance-id', + instanceType: 'my-instance-type', + accountId: 'my-account-id', + region: 'my-region', + availabilityZone: 'my-zone', +}; describe('Node SDK', () => { before(() => { @@ -128,4 +167,114 @@ describe('Node SDK', () => { assert.ok(metrics.getMeterProvider() instanceof MeterProvider); }); }); + + describe('detectResources', async () => { + beforeEach(() => { + nock.disableNetConnect(); + process.env.OTEL_RESOURCE_LABELS = + 'service.instance.id=627cc493,service.name=my-service,service.namespace=default,service.version=0.0.1'; + }); + + afterEach(() => { + nock.cleanAll(); + nock.enableNetConnect(); + delete process.env.OTEL_RESOURCE_LABELS; + }); + + describe('in GCP environment', () => { + after(() => { + resetIsAvailableCache(); + }); + + it('returns a merged resource', async () => { + const gcpScope = nock(HOST_ADDRESS) + .get(INSTANCE_PATH) + .reply(200, {}, HEADERS) + .get(INSTANCE_ID_PATH) + .reply(200, () => 452003179927758, HEADERS) + .get(PROJECT_ID_PATH) + .reply(200, () => 'my-project-id', HEADERS) + .get(ZONE_PATH) + .reply(200, () => 'project/zone/my-zone', HEADERS) + .get(CLUSTER_NAME_PATH) + .reply(404); + const gcpSecondaryScope = nock(SECONDARY_HOST_ADDRESS) + .get(INSTANCE_PATH) + .reply(200, {}, HEADERS); + const awsScope = nock(AWS_HOST) + .get(AWS_PATH) + .replyWithError({ code: 'ENOTFOUND' }); + const resource: Resource = await detectResources(); + awsScope.done(); + gcpSecondaryScope.done(); + gcpScope.done(); + + assertCloudResource(resource, { + provider: 'gcp', + accountId: 'my-project-id', + zone: 'my-zone', + }); + assertHostResource(resource, { id: '452003179927758' }); + assertServiceResource(resource, { + instanceId: '627cc493', + name: 'my-service', + namespace: 'default', + version: '0.0.1', + }); + }); + }); + + describe('in AWS environment', () => { + it('returns a merged resource', async () => { + const gcpScope = nock(HOST_ADDRESS).get(INSTANCE_PATH).replyWithError({ + code: 'ENOTFOUND', + }); + const gcpSecondaryScope = nock(SECONDARY_HOST_ADDRESS) + .get(INSTANCE_PATH) + .replyWithError({ + code: 'ENOTFOUND', + }); + const awsScope = nock(AWS_HOST) + .get(AWS_PATH) + .reply(200, () => mockedAwsResponse); + const resource: Resource = await detectResources(); + gcpSecondaryScope.done(); + gcpScope.done(); + awsScope.done(); + + assertCloudResource(resource, { + provider: 'aws', + accountId: 'my-account-id', + region: 'my-region', + zone: 'my-zone', + }); + assertHostResource(resource, { + id: 'my-instance-id', + hostType: 'my-instance-type', + }); + assertServiceResource(resource, { + instanceId: '627cc493', + name: 'my-service', + namespace: 'default', + version: '0.0.1', + }); + }); + }); + + describe('with a buggy detector', () => { + it('returns a merged resource', async () => { + const stub = sinon.stub(awsEc2Detector, 'detect').throws(); + const resource: Resource = await detectResources(); + + assertServiceResource(resource, { + instanceId: '627cc493', + name: 'my-service', + namespace: 'default', + version: '0.0.1', + }); + + stub.restore(); + }); + }); + }); }); From 639b2ce0438e3da303367affad89c63b3010ad46 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Wed, 12 Aug 2020 19:12:26 -0700 Subject: [PATCH 02/15] fix: add missing URL import --- packages/opentelemetry-sdk-node/src/sdk.ts | 6 +++++- packages/opentelemetry-sdk-node/test/sdk.test.ts | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/opentelemetry-sdk-node/src/sdk.ts b/packages/opentelemetry-sdk-node/src/sdk.ts index ae75223b760..98154082154 100644 --- a/packages/opentelemetry-sdk-node/src/sdk.ts +++ b/packages/opentelemetry-sdk-node/src/sdk.ts @@ -18,7 +18,11 @@ import { HttpTextPropagator, metrics } from '@opentelemetry/api'; import { ContextManager } from '@opentelemetry/context-base'; import { MeterConfig, MeterProvider } from '@opentelemetry/metrics'; import { NodeTracerConfig, NodeTracerProvider } from '@opentelemetry/node'; -import { detectResources, Resource, ResourceDetectionConfig } from '@opentelemetry/resources'; +import { + detectResources, + Resource, + ResourceDetectionConfig, +} from '@opentelemetry/resources'; import { BatchSpanProcessor, SpanProcessor } from '@opentelemetry/tracing'; import { NodeSDKConfiguration } from './types'; import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index ae338df577e..a63621ae974 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -15,6 +15,7 @@ */ import * as nock from 'nock'; +import { URL } from 'url'; import { context, metrics, From e96ff75b88bfeae4f42a35a61ca6ef7e192af1ae Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Wed, 12 Aug 2020 19:23:14 -0700 Subject: [PATCH 03/15] refactor: share duped test utils --- .../test/detectors/AwsEc2Detector.test.ts | 2 +- .../test/util/resource-assertions.ts | 277 ------------------ .../test/detectors/EnvDetector.test.ts | 2 +- .../test/util/resource-assertions.ts | 277 ------------------ .../test/util/resource-assertions.ts | 277 ------------------ 5 files changed, 2 insertions(+), 833 deletions(-) delete mode 100644 packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts delete mode 100644 packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts delete mode 100644 packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts diff --git a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts index 3dc45c5a083..a00d37ffd0a 100644 --- a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts @@ -23,7 +23,7 @@ import { assertCloudResource, assertHostResource, assertEmptyResource, -} from '../util/resource-assertions'; +} from '@opentelemetry/resources/test/util/resource-assertions'; import { NoopLogger } from '@opentelemetry/core'; const { origin: AWS_HOST, pathname: AWS_PATH } = new URL( diff --git a/packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts b/packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts deleted file mode 100644 index 1b98b02eeb1..00000000000 --- a/packages/opentelemetry-resource-detector-aws/test/util/resource-assertions.ts +++ /dev/null @@ -1,277 +0,0 @@ -/* - * 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 { SDK_INFO } from '@opentelemetry/core'; -import * as assert from 'assert'; -import { - Resource, - CLOUD_RESOURCE, - CONTAINER_RESOURCE, - HOST_RESOURCE, - K8S_RESOURCE, - TELEMETRY_SDK_RESOURCE, - SERVICE_RESOURCE, -} from '@opentelemetry/resources'; - -/** - * Test utility method to validate a cloud resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertCloudResource = ( - resource: Resource, - validations: { - provider?: string; - accountId?: string; - region?: string; - zone?: string; - } -) => { - assertHasOneLabel(CLOUD_RESOURCE, resource); - if (validations.provider) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.PROVIDER], - validations.provider - ); - if (validations.accountId) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.ACCOUNT_ID], - validations.accountId - ); - if (validations.region) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.REGION], - validations.region - ); - if (validations.zone) - assert.strictEqual(resource.labels[CLOUD_RESOURCE.ZONE], validations.zone); -}; - -/** - * Test utility method to validate a container resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertContainerResource = ( - resource: Resource, - validations: { - name?: string; - imageName?: string; - imageTag?: string; - } -) => { - assertHasOneLabel(CONTAINER_RESOURCE, resource); - if (validations.name) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.NAME], - validations.name - ); - if (validations.imageName) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.IMAGE_NAME], - validations.imageName - ); - if (validations.imageTag) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.IMAGE_TAG], - validations.imageTag - ); -}; - -/** - * Test utility method to validate a host resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertHostResource = ( - resource: Resource, - validations: { - hostName?: string; - id?: string; - name?: string; - hostType?: string; - imageName?: string; - imageId?: string; - imageVersion?: string; - } -) => { - assertHasOneLabel(HOST_RESOURCE, resource); - if (validations.hostName) - assert.strictEqual( - resource.labels[HOST_RESOURCE.HOSTNAME], - validations.hostName - ); - if (validations.id) - assert.strictEqual(resource.labels[HOST_RESOURCE.ID], validations.id); - if (validations.name) - assert.strictEqual(resource.labels[HOST_RESOURCE.NAME], validations.name); - if (validations.hostType) - assert.strictEqual( - resource.labels[HOST_RESOURCE.TYPE], - validations.hostType - ); - if (validations.imageName) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_NAME], - validations.imageName - ); - if (validations.imageId) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_ID], - validations.imageId - ); - if (validations.imageVersion) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_VERSION], - validations.imageVersion - ); -}; - -/** - * Test utility method to validate a K8s resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertK8sResource = ( - resource: Resource, - validations: { - clusterName?: string; - namespaceName?: string; - podName?: string; - deploymentName?: string; - } -) => { - assertHasOneLabel(K8S_RESOURCE, resource); - if (validations.clusterName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.CLUSTER_NAME], - validations.clusterName - ); - if (validations.namespaceName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.NAMESPACE_NAME], - validations.namespaceName - ); - if (validations.podName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.POD_NAME], - validations.podName - ); - if (validations.deploymentName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.DEPLOYMENT_NAME], - validations.deploymentName - ); -}; - -/** - * Test utility method to validate a telemetry sdk resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertTelemetrySDKResource = ( - resource: Resource, - validations: { - name?: string; - language?: string; - version?: string; - } -) => { - const defaults = { - name: SDK_INFO.NAME, - language: SDK_INFO.LANGUAGE, - version: SDK_INFO.VERSION, - }; - validations = { ...defaults, ...validations }; - - if (validations.name) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.NAME], - validations.name - ); - if (validations.language) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.LANGUAGE], - validations.language - ); - if (validations.version) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.VERSION], - validations.version - ); -}; - -/** - * Test utility method to validate a service resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertServiceResource = ( - resource: Resource, - validations: { - name: string; - instanceId: string; - namespace?: string; - version?: string; - } -) => { - assert.strictEqual(resource.labels[SERVICE_RESOURCE.NAME], validations.name); - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.INSTANCE_ID], - validations.instanceId - ); - if (validations.namespace) - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.NAMESPACE], - validations.namespace - ); - if (validations.version) - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.VERSION], - validations.version - ); -}; - -/** - * Test utility method to validate an empty resource - * - * @param resource the Resource to validate - */ -export const assertEmptyResource = (resource: Resource) => { - assert.strictEqual(Object.keys(resource.labels).length, 0); -}; - -const assertHasOneLabel = ( - constants: { [key: string]: string }, - resource: Resource -): void => { - const hasOne = Object.values(constants).reduce( - // eslint-disable-next-line no-prototype-builtins - (found, key) => found || resource.labels.hasOwnProperty(key), - false - ); - assert.ok( - hasOne, - 'Resource must have one of the following labels: ' + - Object.values(constants).join(', ') - ); -}; diff --git a/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts b/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts index 80a4e6bb5ce..334372cd4da 100644 --- a/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts +++ b/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts @@ -20,7 +20,7 @@ import { Resource, K8S_RESOURCE } from '@opentelemetry/resources'; import { assertK8sResource, assertEmptyResource, -} from '../util/resource-assertions'; +} from '@opentelemetry/resources/test/util/resource-assertions'; describe('envDetector()', () => { describe('with valid env', () => { diff --git a/packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts b/packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts deleted file mode 100644 index 1b98b02eeb1..00000000000 --- a/packages/opentelemetry-resource-detector-env/test/util/resource-assertions.ts +++ /dev/null @@ -1,277 +0,0 @@ -/* - * 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 { SDK_INFO } from '@opentelemetry/core'; -import * as assert from 'assert'; -import { - Resource, - CLOUD_RESOURCE, - CONTAINER_RESOURCE, - HOST_RESOURCE, - K8S_RESOURCE, - TELEMETRY_SDK_RESOURCE, - SERVICE_RESOURCE, -} from '@opentelemetry/resources'; - -/** - * Test utility method to validate a cloud resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertCloudResource = ( - resource: Resource, - validations: { - provider?: string; - accountId?: string; - region?: string; - zone?: string; - } -) => { - assertHasOneLabel(CLOUD_RESOURCE, resource); - if (validations.provider) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.PROVIDER], - validations.provider - ); - if (validations.accountId) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.ACCOUNT_ID], - validations.accountId - ); - if (validations.region) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.REGION], - validations.region - ); - if (validations.zone) - assert.strictEqual(resource.labels[CLOUD_RESOURCE.ZONE], validations.zone); -}; - -/** - * Test utility method to validate a container resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertContainerResource = ( - resource: Resource, - validations: { - name?: string; - imageName?: string; - imageTag?: string; - } -) => { - assertHasOneLabel(CONTAINER_RESOURCE, resource); - if (validations.name) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.NAME], - validations.name - ); - if (validations.imageName) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.IMAGE_NAME], - validations.imageName - ); - if (validations.imageTag) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.IMAGE_TAG], - validations.imageTag - ); -}; - -/** - * Test utility method to validate a host resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertHostResource = ( - resource: Resource, - validations: { - hostName?: string; - id?: string; - name?: string; - hostType?: string; - imageName?: string; - imageId?: string; - imageVersion?: string; - } -) => { - assertHasOneLabel(HOST_RESOURCE, resource); - if (validations.hostName) - assert.strictEqual( - resource.labels[HOST_RESOURCE.HOSTNAME], - validations.hostName - ); - if (validations.id) - assert.strictEqual(resource.labels[HOST_RESOURCE.ID], validations.id); - if (validations.name) - assert.strictEqual(resource.labels[HOST_RESOURCE.NAME], validations.name); - if (validations.hostType) - assert.strictEqual( - resource.labels[HOST_RESOURCE.TYPE], - validations.hostType - ); - if (validations.imageName) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_NAME], - validations.imageName - ); - if (validations.imageId) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_ID], - validations.imageId - ); - if (validations.imageVersion) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_VERSION], - validations.imageVersion - ); -}; - -/** - * Test utility method to validate a K8s resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertK8sResource = ( - resource: Resource, - validations: { - clusterName?: string; - namespaceName?: string; - podName?: string; - deploymentName?: string; - } -) => { - assertHasOneLabel(K8S_RESOURCE, resource); - if (validations.clusterName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.CLUSTER_NAME], - validations.clusterName - ); - if (validations.namespaceName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.NAMESPACE_NAME], - validations.namespaceName - ); - if (validations.podName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.POD_NAME], - validations.podName - ); - if (validations.deploymentName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.DEPLOYMENT_NAME], - validations.deploymentName - ); -}; - -/** - * Test utility method to validate a telemetry sdk resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertTelemetrySDKResource = ( - resource: Resource, - validations: { - name?: string; - language?: string; - version?: string; - } -) => { - const defaults = { - name: SDK_INFO.NAME, - language: SDK_INFO.LANGUAGE, - version: SDK_INFO.VERSION, - }; - validations = { ...defaults, ...validations }; - - if (validations.name) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.NAME], - validations.name - ); - if (validations.language) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.LANGUAGE], - validations.language - ); - if (validations.version) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.VERSION], - validations.version - ); -}; - -/** - * Test utility method to validate a service resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertServiceResource = ( - resource: Resource, - validations: { - name: string; - instanceId: string; - namespace?: string; - version?: string; - } -) => { - assert.strictEqual(resource.labels[SERVICE_RESOURCE.NAME], validations.name); - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.INSTANCE_ID], - validations.instanceId - ); - if (validations.namespace) - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.NAMESPACE], - validations.namespace - ); - if (validations.version) - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.VERSION], - validations.version - ); -}; - -/** - * Test utility method to validate an empty resource - * - * @param resource the Resource to validate - */ -export const assertEmptyResource = (resource: Resource) => { - assert.strictEqual(Object.keys(resource.labels).length, 0); -}; - -const assertHasOneLabel = ( - constants: { [key: string]: string }, - resource: Resource -): void => { - const hasOne = Object.values(constants).reduce( - // eslint-disable-next-line no-prototype-builtins - (found, key) => found || resource.labels.hasOwnProperty(key), - false - ); - assert.ok( - hasOne, - 'Resource must have one of the following labels: ' + - Object.values(constants).join(', ') - ); -}; diff --git a/packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts b/packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts deleted file mode 100644 index 1b98b02eeb1..00000000000 --- a/packages/opentelemetry-resource-detector-gcp/test/util/resource-assertions.ts +++ /dev/null @@ -1,277 +0,0 @@ -/* - * 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 { SDK_INFO } from '@opentelemetry/core'; -import * as assert from 'assert'; -import { - Resource, - CLOUD_RESOURCE, - CONTAINER_RESOURCE, - HOST_RESOURCE, - K8S_RESOURCE, - TELEMETRY_SDK_RESOURCE, - SERVICE_RESOURCE, -} from '@opentelemetry/resources'; - -/** - * Test utility method to validate a cloud resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertCloudResource = ( - resource: Resource, - validations: { - provider?: string; - accountId?: string; - region?: string; - zone?: string; - } -) => { - assertHasOneLabel(CLOUD_RESOURCE, resource); - if (validations.provider) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.PROVIDER], - validations.provider - ); - if (validations.accountId) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.ACCOUNT_ID], - validations.accountId - ); - if (validations.region) - assert.strictEqual( - resource.labels[CLOUD_RESOURCE.REGION], - validations.region - ); - if (validations.zone) - assert.strictEqual(resource.labels[CLOUD_RESOURCE.ZONE], validations.zone); -}; - -/** - * Test utility method to validate a container resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertContainerResource = ( - resource: Resource, - validations: { - name?: string; - imageName?: string; - imageTag?: string; - } -) => { - assertHasOneLabel(CONTAINER_RESOURCE, resource); - if (validations.name) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.NAME], - validations.name - ); - if (validations.imageName) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.IMAGE_NAME], - validations.imageName - ); - if (validations.imageTag) - assert.strictEqual( - resource.labels[CONTAINER_RESOURCE.IMAGE_TAG], - validations.imageTag - ); -}; - -/** - * Test utility method to validate a host resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertHostResource = ( - resource: Resource, - validations: { - hostName?: string; - id?: string; - name?: string; - hostType?: string; - imageName?: string; - imageId?: string; - imageVersion?: string; - } -) => { - assertHasOneLabel(HOST_RESOURCE, resource); - if (validations.hostName) - assert.strictEqual( - resource.labels[HOST_RESOURCE.HOSTNAME], - validations.hostName - ); - if (validations.id) - assert.strictEqual(resource.labels[HOST_RESOURCE.ID], validations.id); - if (validations.name) - assert.strictEqual(resource.labels[HOST_RESOURCE.NAME], validations.name); - if (validations.hostType) - assert.strictEqual( - resource.labels[HOST_RESOURCE.TYPE], - validations.hostType - ); - if (validations.imageName) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_NAME], - validations.imageName - ); - if (validations.imageId) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_ID], - validations.imageId - ); - if (validations.imageVersion) - assert.strictEqual( - resource.labels[HOST_RESOURCE.IMAGE_VERSION], - validations.imageVersion - ); -}; - -/** - * Test utility method to validate a K8s resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertK8sResource = ( - resource: Resource, - validations: { - clusterName?: string; - namespaceName?: string; - podName?: string; - deploymentName?: string; - } -) => { - assertHasOneLabel(K8S_RESOURCE, resource); - if (validations.clusterName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.CLUSTER_NAME], - validations.clusterName - ); - if (validations.namespaceName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.NAMESPACE_NAME], - validations.namespaceName - ); - if (validations.podName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.POD_NAME], - validations.podName - ); - if (validations.deploymentName) - assert.strictEqual( - resource.labels[K8S_RESOURCE.DEPLOYMENT_NAME], - validations.deploymentName - ); -}; - -/** - * Test utility method to validate a telemetry sdk resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertTelemetrySDKResource = ( - resource: Resource, - validations: { - name?: string; - language?: string; - version?: string; - } -) => { - const defaults = { - name: SDK_INFO.NAME, - language: SDK_INFO.LANGUAGE, - version: SDK_INFO.VERSION, - }; - validations = { ...defaults, ...validations }; - - if (validations.name) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.NAME], - validations.name - ); - if (validations.language) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.LANGUAGE], - validations.language - ); - if (validations.version) - assert.strictEqual( - resource.labels[TELEMETRY_SDK_RESOURCE.VERSION], - validations.version - ); -}; - -/** - * Test utility method to validate a service resource - * - * @param resource the Resource to validate - * @param validations validations for the resource labels - */ -export const assertServiceResource = ( - resource: Resource, - validations: { - name: string; - instanceId: string; - namespace?: string; - version?: string; - } -) => { - assert.strictEqual(resource.labels[SERVICE_RESOURCE.NAME], validations.name); - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.INSTANCE_ID], - validations.instanceId - ); - if (validations.namespace) - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.NAMESPACE], - validations.namespace - ); - if (validations.version) - assert.strictEqual( - resource.labels[SERVICE_RESOURCE.VERSION], - validations.version - ); -}; - -/** - * Test utility method to validate an empty resource - * - * @param resource the Resource to validate - */ -export const assertEmptyResource = (resource: Resource) => { - assert.strictEqual(Object.keys(resource.labels).length, 0); -}; - -const assertHasOneLabel = ( - constants: { [key: string]: string }, - resource: Resource -): void => { - const hasOne = Object.values(constants).reduce( - // eslint-disable-next-line no-prototype-builtins - (found, key) => found || resource.labels.hasOwnProperty(key), - false - ); - assert.ok( - hasOne, - 'Resource must have one of the following labels: ' + - Object.values(constants).join(', ') - ); -}; From 637823b1ceb4cfe2f06ea6f6cbe569ab31e23c09 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Wed, 12 Aug 2020 23:00:57 -0700 Subject: [PATCH 04/15] fix: failing tests --- .../src/detectors/AwsEc2Detector.ts | 19 +-- .../src/detectors/EnvDetector.ts | 2 +- .../src/detectors/GcpDetector.ts | 2 +- .../opentelemetry-resources/src/Resource.ts | 2 +- .../src/platform/node/detect-resources.ts | 2 +- .../opentelemetry-sdk-node/test/sdk.test.ts | 136 ++++++++++++++++-- 6 files changed, 143 insertions(+), 20 deletions(-) diff --git a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts index adf687a3999..4316ec07bc3 100644 --- a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts +++ b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts @@ -53,14 +53,17 @@ class AwsEc2Detector implements Detector { region, availabilityZone, } = await this._awsMetadataAccessor(); - return new Resource({ - [CLOUD_RESOURCE.PROVIDER]: 'aws', - [CLOUD_RESOURCE.ACCOUNT_ID]: accountId, - [CLOUD_RESOURCE.REGION]: region, - [CLOUD_RESOURCE.ZONE]: availabilityZone, - [HOST_RESOURCE.ID]: instanceId, - [HOST_RESOURCE.TYPE]: instanceType, - }); + return new Resource( + { + [CLOUD_RESOURCE.PROVIDER]: 'aws', + [CLOUD_RESOURCE.ACCOUNT_ID]: accountId, + [CLOUD_RESOURCE.REGION]: region, + [CLOUD_RESOURCE.ZONE]: availabilityZone, + [HOST_RESOURCE.ID]: instanceId, + [HOST_RESOURCE.TYPE]: instanceType, + }, + this.constructor.name + ); } catch (e) { config.logger.debug(`AwsEc2Detector failed: ${e.message}`); return Resource.empty(); diff --git a/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts b/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts index ca0416ba3c3..8e20678934b 100644 --- a/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts +++ b/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts @@ -64,7 +64,7 @@ class EnvDetector implements Detector { const labels = this._parseResourceLabels( process.env.OTEL_RESOURCE_LABELS ); - return new Resource(labels); + return new Resource(labels, this.constructor.name); } catch (e) { config.logger.debug(`EnvDetector failed: ${e.message}`); return Resource.empty(); diff --git a/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts index 5b7599156f8..328830981d5 100644 --- a/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts +++ b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts @@ -63,7 +63,7 @@ class GcpDetector implements Detector { if (process.env.KUBERNETES_SERVICE_HOST) this._addK8sLabels(labels, clusterName); - return new Resource(labels); + return new Resource(labels, this.constructor.name); } /** Add resource labels for K8s */ diff --git a/packages/opentelemetry-resources/src/Resource.ts b/packages/opentelemetry-resources/src/Resource.ts index 849acd0beea..3d801d09a68 100644 --- a/packages/opentelemetry-resources/src/Resource.ts +++ b/packages/opentelemetry-resources/src/Resource.ts @@ -54,7 +54,7 @@ export class Resource { /** * Name of the resource detector that detected this resource */ - readonly detector: string = 'Unknown detector' + readonly detectedBy: string = 'Unknown detector' ) {} /** diff --git a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts index 69f8db49fff..70379745fd6 100644 --- a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts +++ b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts @@ -74,7 +74,7 @@ const logResources = (logger: Logger, resources: Array) => { sorted: true, compact: false, }); - const detectorName = resource.detector; + const detectorName = resource.detectedBy; logger.debug(`${detectorName} found resource.`); logger.debug(resourceDebugString); } diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index a63621ae974..a04611836f3 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -39,7 +39,7 @@ import { NodeSDK } from '../src'; import * as NodeConfig from '@opentelemetry/node/build/src/config'; import * as Sinon from 'sinon'; import sinon = require('sinon'); -import { Resource, detectResources } from '@opentelemetry/resources'; +import { Resource } from '@opentelemetry/resources'; import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; import { @@ -55,6 +55,7 @@ import { SECONDARY_HOST_ADDRESS, resetIsAvailableCache, } from 'gcp-metadata'; +import { resetIsAvailableCache as otherResetIsAvailableCache } from '@opentelemetry/resource-detector-gcp/node_modules/gcp-metadata'; const HEADERS = { [HEADER_NAME.toLowerCase()]: HEADER_VALUE, @@ -170,6 +171,10 @@ describe('Node SDK', () => { }); describe('detectResources', async () => { + const sdk = new NodeSDK({ + autoDetectResources: true, + }); + beforeEach(() => { nock.disableNetConnect(); process.env.OTEL_RESOURCE_LABELS = @@ -177,16 +182,15 @@ describe('Node SDK', () => { }); afterEach(() => { + sdk['_resource'] = Resource.empty(); + resetIsAvailableCache(); + otherResetIsAvailableCache(); nock.cleanAll(); nock.enableNetConnect(); delete process.env.OTEL_RESOURCE_LABELS; }); describe('in GCP environment', () => { - after(() => { - resetIsAvailableCache(); - }); - it('returns a merged resource', async () => { const gcpScope = nock(HOST_ADDRESS) .get(INSTANCE_PATH) @@ -205,7 +209,9 @@ describe('Node SDK', () => { const awsScope = nock(AWS_HOST) .get(AWS_PATH) .replyWithError({ code: 'ENOTFOUND' }); - const resource: Resource = await detectResources(); + await sdk.detectResources(); + const resource: Resource = sdk['_resource']; + awsScope.done(); gcpSecondaryScope.done(); gcpScope.done(); @@ -238,7 +244,10 @@ describe('Node SDK', () => { const awsScope = nock(AWS_HOST) .get(AWS_PATH) .reply(200, () => mockedAwsResponse); - const resource: Resource = await detectResources(); + + await sdk.detectResources(); + const resource: Resource = sdk['_resource']; + gcpSecondaryScope.done(); gcpScope.done(); awsScope.done(); @@ -265,7 +274,9 @@ describe('Node SDK', () => { describe('with a buggy detector', () => { it('returns a merged resource', async () => { const stub = sinon.stub(awsEc2Detector, 'detect').throws(); - const resource: Resource = await detectResources(); + + await sdk.detectResources(); + const resource: Resource = sdk['_resource']; assertServiceResource(resource, { instanceId: '627cc493', @@ -277,5 +288,114 @@ describe('Node SDK', () => { stub.restore(); }); }); + + describe('with a debug logger', () => { + // Local functions to test if a mocked method is ever called with a specific argument or regex matching for an argument. + // Needed because of race condition with parallel detectors. + const callArgsContains = ( + mockedFunction: sinon.SinonSpy, + arg: any + ): boolean => { + return mockedFunction.getCalls().some(call => { + return call.args.some(callarg => arg === callarg); + }); + }; + const callArgsMatches = ( + mockedFunction: sinon.SinonSpy, + regex: RegExp + ): boolean => { + return mockedFunction.getCalls().some(call => { + return regex.test(call.args.toString()); + }); + }; + + it('prints detected resources and debug messages to the logger', async () => { + // This test depends on the env detector to be functioning as intended + const mockedLoggerMethod = sinon.fake(); + await sdk.detectResources({ + logger: { + debug: mockedLoggerMethod, + info: sinon.fake(), + warn: sinon.fake(), + error: sinon.fake(), + }, + }); + + // Test for AWS and GCP Detector failure + assert.ok( + callArgsContains( + mockedLoggerMethod, + 'GcpDetector failed: GCP Metadata unavailable.' + ) + ); + assert.ok( + callArgsContains( + mockedLoggerMethod, + 'AwsEc2Detector failed: Nock: Disallowed net connect for "169.254.169.254:80/latest/dynamic/instance-identity/document"' + ) + ); + // Test that the Env Detector successfully found its resource and populated it with the right values. + assert.ok( + callArgsContains(mockedLoggerMethod, 'EnvDetector found resource.') + ); + // Regex formatting accounts for whitespace variations in util.inspect output over different node versions + assert.ok( + callArgsMatches( + mockedLoggerMethod, + /{\s+'service\.instance\.id':\s+'627cc493',\s+'service\.name':\s+'my-service',\s+'service\.namespace':\s+'default',\s+'service\.version':\s+'0\.0\.1'\s+}\s*/ + ) + ); + }); + + describe('with missing environemnt variable', () => { + beforeEach(() => { + delete process.env.OTEL_RESOURCE_LABELS; + }); + + it('prints correct error messages when EnvDetector has no env variable', async () => { + const mockedLoggerMethod = sinon.fake(); + await sdk.detectResources({ + logger: { + debug: mockedLoggerMethod, + info: sinon.fake(), + warn: sinon.fake(), + error: sinon.fake(), + }, + }); + + assert.ok( + callArgsContains( + mockedLoggerMethod, + 'EnvDetector failed: Environment variable "OTEL_RESOURCE_LABELS" is missing.' + ) + ); + }); + }); + + describe('with a faulty environment variable', () => { + beforeEach(() => { + process.env.OTEL_RESOURCE_LABELS = 'bad=~label'; + }); + + it('prints correct error messages when EnvDetector has an invalid variable', async () => { + const mockedLoggerMethod = sinon.fake(); + await sdk.detectResources({ + logger: { + debug: mockedLoggerMethod, + info: sinon.fake(), + warn: sinon.fake(), + error: sinon.fake(), + }, + }); + + assert.ok( + callArgsContains( + mockedLoggerMethod, + 'EnvDetector failed: Label value should be a ASCII string with a length not exceed 255 characters.' + ) + ); + }); + }); + }); }); }); From 7dbec35aa29aa9393c1b381715e052d5f08aa5d6 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Thu, 13 Aug 2020 09:35:00 -0700 Subject: [PATCH 05/15] chore: remove duped sinon --- packages/opentelemetry-resources/package.json | 3 +- .../opentelemetry-sdk-node/test/sdk.test.ts | 33 +++++++++---------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/packages/opentelemetry-resources/package.json b/packages/opentelemetry-resources/package.json index 27e0e1d4184..0e35360e42c 100644 --- a/packages/opentelemetry-resources/package.json +++ b/packages/opentelemetry-resources/package.json @@ -61,7 +61,6 @@ }, "dependencies": { "@opentelemetry/api": "^0.10.2", - "@opentelemetry/core": "^0.10.2", - "gcp-metadata": "^3.5.0" + "@opentelemetry/core": "^0.10.2" } } diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index a04611836f3..b7852ecc6d4 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -37,8 +37,7 @@ import { import * as assert from 'assert'; import { NodeSDK } from '../src'; import * as NodeConfig from '@opentelemetry/node/build/src/config'; -import * as Sinon from 'sinon'; -import sinon = require('sinon'); +import * as Sinon from 'Sinon'; import { Resource } from '@opentelemetry/resources'; import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; @@ -273,7 +272,7 @@ describe('Node SDK', () => { describe('with a buggy detector', () => { it('returns a merged resource', async () => { - const stub = sinon.stub(awsEc2Detector, 'detect').throws(); + const stub = Sinon.stub(awsEc2Detector, 'detect').throws(); await sdk.detectResources(); const resource: Resource = sdk['_resource']; @@ -293,7 +292,7 @@ describe('Node SDK', () => { // Local functions to test if a mocked method is ever called with a specific argument or regex matching for an argument. // Needed because of race condition with parallel detectors. const callArgsContains = ( - mockedFunction: sinon.SinonSpy, + mockedFunction: Sinon.SinonSpy, arg: any ): boolean => { return mockedFunction.getCalls().some(call => { @@ -301,7 +300,7 @@ describe('Node SDK', () => { }); }; const callArgsMatches = ( - mockedFunction: sinon.SinonSpy, + mockedFunction: Sinon.SinonSpy, regex: RegExp ): boolean => { return mockedFunction.getCalls().some(call => { @@ -311,13 +310,13 @@ describe('Node SDK', () => { it('prints detected resources and debug messages to the logger', async () => { // This test depends on the env detector to be functioning as intended - const mockedLoggerMethod = sinon.fake(); + const mockedLoggerMethod = Sinon.fake(); await sdk.detectResources({ logger: { debug: mockedLoggerMethod, - info: sinon.fake(), - warn: sinon.fake(), - error: sinon.fake(), + info: Sinon.fake(), + warn: Sinon.fake(), + error: Sinon.fake(), }, }); @@ -353,13 +352,13 @@ describe('Node SDK', () => { }); it('prints correct error messages when EnvDetector has no env variable', async () => { - const mockedLoggerMethod = sinon.fake(); + const mockedLoggerMethod = Sinon.fake(); await sdk.detectResources({ logger: { debug: mockedLoggerMethod, - info: sinon.fake(), - warn: sinon.fake(), - error: sinon.fake(), + info: Sinon.fake(), + warn: Sinon.fake(), + error: Sinon.fake(), }, }); @@ -378,13 +377,13 @@ describe('Node SDK', () => { }); it('prints correct error messages when EnvDetector has an invalid variable', async () => { - const mockedLoggerMethod = sinon.fake(); + const mockedLoggerMethod = Sinon.fake(); await sdk.detectResources({ logger: { debug: mockedLoggerMethod, - info: sinon.fake(), - warn: sinon.fake(), - error: sinon.fake(), + info: Sinon.fake(), + warn: Sinon.fake(), + error: Sinon.fake(), }, }); From 2e8251a0488c82b4cf37adb076415d0692fd93cf Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Thu, 13 Aug 2020 09:58:22 -0700 Subject: [PATCH 06/15] fix: sinon typo --- packages/opentelemetry-sdk-node/test/sdk.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index b7852ecc6d4..e661fd898c9 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -37,7 +37,7 @@ import { import * as assert from 'assert'; import { NodeSDK } from '../src'; import * as NodeConfig from '@opentelemetry/node/build/src/config'; -import * as Sinon from 'Sinon'; +import * as Sinon from 'sinon'; import { Resource } from '@opentelemetry/resources'; import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; From 2816099bd777d24499c6b6b6792bd67e0276d7e9 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Thu, 13 Aug 2020 15:19:39 -0700 Subject: [PATCH 07/15] refactor: migrate env detector --- .../LICENSE | 2 +- .../.eslintignore | 1 - .../.eslintrc.js | 9 - .../.npmignore | 4 - .../LICENSE | 201 ------------------ .../README.md | 44 ---- .../package.json | 63 ------ .../src/index.ts | 17 -- .../src/version.ts | 18 -- .../tsconfig.json | 8 - .../LICENSE | 2 +- packages/opentelemetry-resources/LICENSE | 2 +- .../platform/node}/detectors/EnvDetector.ts | 2 +- .../src/platform/node}/detectors/index.ts | 0 .../src/platform/node/index.ts | 1 + .../test/detectors/EnvDetector.test.ts | 8 +- 16 files changed, 7 insertions(+), 375 deletions(-) delete mode 100644 packages/opentelemetry-resource-detector-env/.eslintignore delete mode 100644 packages/opentelemetry-resource-detector-env/.eslintrc.js delete mode 100644 packages/opentelemetry-resource-detector-env/.npmignore delete mode 100644 packages/opentelemetry-resource-detector-env/LICENSE delete mode 100644 packages/opentelemetry-resource-detector-env/README.md delete mode 100644 packages/opentelemetry-resource-detector-env/package.json delete mode 100644 packages/opentelemetry-resource-detector-env/src/index.ts delete mode 100644 packages/opentelemetry-resource-detector-env/src/version.ts delete mode 100644 packages/opentelemetry-resource-detector-env/tsconfig.json rename packages/{opentelemetry-resource-detector-env/src => opentelemetry-resources/src/platform/node}/detectors/EnvDetector.ts (99%) rename packages/{opentelemetry-resource-detector-env/src => opentelemetry-resources/src/platform/node}/detectors/index.ts (100%) rename packages/{opentelemetry-resource-detector-env => opentelemetry-resources}/test/detectors/EnvDetector.test.ts (87%) diff --git a/packages/opentelemetry-resource-detector-aws/LICENSE b/packages/opentelemetry-resource-detector-aws/LICENSE index b0e74c7d159..6b91a297c81 100644 --- a/packages/opentelemetry-resource-detector-aws/LICENSE +++ b/packages/opentelemetry-resource-detector-aws/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [2020] [name of copyright owner] + Copyright [2020] OpenTelemetry Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/opentelemetry-resource-detector-env/.eslintignore b/packages/opentelemetry-resource-detector-env/.eslintignore deleted file mode 100644 index 378eac25d31..00000000000 --- a/packages/opentelemetry-resource-detector-env/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -build diff --git a/packages/opentelemetry-resource-detector-env/.eslintrc.js b/packages/opentelemetry-resource-detector-env/.eslintrc.js deleted file mode 100644 index 9dfe62f9b8c..00000000000 --- a/packages/opentelemetry-resource-detector-env/.eslintrc.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = { - "env": { - "mocha": true, - "commonjs": true, - "node": true, - "browser": true - }, - ...require('../../eslint.config.js') -} diff --git a/packages/opentelemetry-resource-detector-env/.npmignore b/packages/opentelemetry-resource-detector-env/.npmignore deleted file mode 100644 index 9505ba9450f..00000000000 --- a/packages/opentelemetry-resource-detector-env/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -/bin -/coverage -/doc -/test diff --git a/packages/opentelemetry-resource-detector-env/LICENSE b/packages/opentelemetry-resource-detector-env/LICENSE deleted file mode 100644 index b0e74c7d159..00000000000 --- a/packages/opentelemetry-resource-detector-env/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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 [2020] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/packages/opentelemetry-resource-detector-env/README.md b/packages/opentelemetry-resource-detector-env/README.md deleted file mode 100644 index b9f3cc60e8d..00000000000 --- a/packages/opentelemetry-resource-detector-env/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# OpenTelemetry Resource Detector for OpenTelemetry Environment Variables - -[![Gitter chat][gitter-image]][gitter-url] -[![NPM Published Version][npm-img]][npm-url] -[![dependencies][dependencies-image]][dependencies-url] -[![devDependencies][devDependencies-image]][devDependencies-url] -[![Apache License][license-image]][license-image] - -The OpenTelemetry Resource is an immutable representation of the entity producing telemetry. For example, a process producing telemetry that is running in a container on Kubernetes has a Pod name, it is in a namespace and possibly is part of a Deployment which also has a name. All three of these attributes can be included in the `Resource`. - -[This document][resource-semantic_conventions] defines standard attributes for resources. - -## Installation - -```bash -npm install --save @opentelemetry/resource-detector-env -``` - -## Usage - -> TODO - -## Useful links - -- For more information on OpenTelemetry, visit: -- For more about OpenTelemetry JavaScript: -- For help or feedback on this project, join us on [gitter][gitter-url] - -## License - -Apache 2.0 - See [LICENSE][license-url] for more information. - -[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg -[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge -[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE -[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat -[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-resources -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-resources -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-resources&type=dev -[npm-url]: https://www.npmjs.com/package/@opentelemetry/resources -[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fresources.svg - -[resource-semantic_conventions]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/resource/semantic_conventions diff --git a/packages/opentelemetry-resource-detector-env/package.json b/packages/opentelemetry-resource-detector-env/package.json deleted file mode 100644 index 3fcef8abbe1..00000000000 --- a/packages/opentelemetry-resource-detector-env/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "name": "@opentelemetry/resource-detector-env", - "version": "0.10.2", - "description": "OpenTelemetry SDK resource detector - Environment", - "main": "build/src/index.js", - "types": "build/src/index.d.ts", - "repository": "open-telemetry/opentelemetry-js", - "scripts": { - "lint": "eslint . --ext .ts", - "lint:fix": "eslint . --ext .ts --fix", - "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", - "tdd": "npm run test -- --watch-extensions ts --watch", - "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", - "clean": "rimraf build/*", - "precompile": "tsc --version", - "version:update": "node ../../scripts/version-update.js", - "compile": "npm run version:update && tsc -p .", - "prepare": "npm run compile" - }, - "keywords": [ - "opentelemetry", - "nodejs", - "resources", - "stats", - "profiling" - ], - "author": "OpenTelemetry Authors", - "license": "Apache-2.0", - "engines": { - "node": ">=8.0.0" - }, - "files": [ - "build/src/**/*.js", - "build/src/**/*.js.map", - "build/src/**/*.d.ts", - "doc", - "LICENSE", - "README.md" - ], - "publishConfig": { - "access": "public" - }, - "devDependencies": { - "@types/mocha": "8.0.1", - "@types/node": "14.0.27", - "@types/sinon": "9.0.4", - "codecov": "3.7.2", - "gts": "2.0.2", - "mocha": "7.2.0", - "nock": "12.0.3", - "nyc": "15.1.0", - "rimraf": "3.0.2", - "sinon": "9.0.2", - "ts-mocha": "7.0.0", - "ts-node": "8.10.2", - "typescript": "3.9.7" - }, - "dependencies": { - "@opentelemetry/api": "^0.10.2", - "@opentelemetry/core": "^0.10.2", - "@opentelemetry/resources": "^0.10.2" - } -} diff --git a/packages/opentelemetry-resource-detector-env/src/index.ts b/packages/opentelemetry-resource-detector-env/src/index.ts deleted file mode 100644 index 0acba8788cf..00000000000 --- a/packages/opentelemetry-resource-detector-env/src/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export * from './detectors'; diff --git a/packages/opentelemetry-resource-detector-env/src/version.ts b/packages/opentelemetry-resource-detector-env/src/version.ts deleted file mode 100644 index ea45ee2fc46..00000000000 --- a/packages/opentelemetry-resource-detector-env/src/version.ts +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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.10.2'; diff --git a/packages/opentelemetry-resource-detector-env/tsconfig.json b/packages/opentelemetry-resource-detector-env/tsconfig.json deleted file mode 100644 index e4b3b29e6a2..00000000000 --- a/packages/opentelemetry-resource-detector-env/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../tsconfig.base", - "compilerOptions": { - "rootDir": ".", - "outDir": "build" - }, - "include": ["src/**/*.ts", "test/**/*.ts"] -} diff --git a/packages/opentelemetry-resource-detector-gcp/LICENSE b/packages/opentelemetry-resource-detector-gcp/LICENSE index b0e74c7d159..6b91a297c81 100644 --- a/packages/opentelemetry-resource-detector-gcp/LICENSE +++ b/packages/opentelemetry-resource-detector-gcp/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [2020] [name of copyright owner] + Copyright [2020] OpenTelemetry Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/opentelemetry-resources/LICENSE b/packages/opentelemetry-resources/LICENSE index b0e74c7d159..6b91a297c81 100644 --- a/packages/opentelemetry-resources/LICENSE +++ b/packages/opentelemetry-resources/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [2020] [name of copyright owner] + Copyright [2020] OpenTelemetry Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts similarity index 99% rename from packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts rename to packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts index 8e20678934b..f1f8ddb711e 100644 --- a/packages/opentelemetry-resource-detector-env/src/detectors/EnvDetector.ts +++ b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts @@ -19,7 +19,7 @@ import { Resource, ResourceDetectionConfigWithLogger, ResourceLabels, -} from '@opentelemetry/resources'; +} from '../../../'; /** * EnvDetector can be used to detect the presence of and create a Resource diff --git a/packages/opentelemetry-resource-detector-env/src/detectors/index.ts b/packages/opentelemetry-resources/src/platform/node/detectors/index.ts similarity index 100% rename from packages/opentelemetry-resource-detector-env/src/detectors/index.ts rename to packages/opentelemetry-resources/src/platform/node/detectors/index.ts diff --git a/packages/opentelemetry-resources/src/platform/node/index.ts b/packages/opentelemetry-resources/src/platform/node/index.ts index f90eb34a5fe..7e82a09dd5d 100644 --- a/packages/opentelemetry-resources/src/platform/node/index.ts +++ b/packages/opentelemetry-resources/src/platform/node/index.ts @@ -15,3 +15,4 @@ */ export * from './detect-resources'; +export * from './detectors'; diff --git a/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts b/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts similarity index 87% rename from packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts rename to packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts index 334372cd4da..b502a672563 100644 --- a/packages/opentelemetry-resource-detector-env/test/detectors/EnvDetector.test.ts +++ b/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts @@ -14,13 +14,9 @@ * limitations under the License. */ -import { envDetector } from '../../src'; +import { envDetector, K8S_RESOURCE, Resource } from '../../src'; +import { assertK8sResource, assertEmptyResource } from '../util/resource-assertions'; import { NoopLogger } from '@opentelemetry/core'; -import { Resource, K8S_RESOURCE } from '@opentelemetry/resources'; -import { - assertK8sResource, - assertEmptyResource, -} from '@opentelemetry/resources/test/util/resource-assertions'; describe('envDetector()', () => { describe('with valid env', () => { From 81a07e2437f55e5f4e22e2508682da667cebbcab Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Thu, 13 Aug 2020 15:55:34 -0700 Subject: [PATCH 08/15] refactor: move detectedBy logging --- .../src/detectors/AwsEc2Detector.ts | 5 +++-- .../src/detectors/GcpDetector.ts | 5 ++++- packages/opentelemetry-resources/src/Resource.ts | 5 ----- .../src/platform/node/detect-resources.ts | 2 -- .../src/platform/node/detectors/EnvDetector.ts | 4 +++- packages/opentelemetry-sdk-node/package.json | 1 - packages/opentelemetry-sdk-node/src/sdk.ts | 2 +- 7 files changed, 11 insertions(+), 13 deletions(-) diff --git a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts index 4316ec07bc3..9279c778f8f 100644 --- a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts +++ b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts @@ -53,7 +53,7 @@ class AwsEc2Detector implements Detector { region, availabilityZone, } = await this._awsMetadataAccessor(); - return new Resource( + const resource = new Resource( { [CLOUD_RESOURCE.PROVIDER]: 'aws', [CLOUD_RESOURCE.ACCOUNT_ID]: accountId, @@ -62,8 +62,9 @@ class AwsEc2Detector implements Detector { [HOST_RESOURCE.ID]: instanceId, [HOST_RESOURCE.TYPE]: instanceType, }, - this.constructor.name ); + config.logger.debug(`${this.constructor.name} found resource.`); + return resource; } catch (e) { config.logger.debug(`AwsEc2Detector failed: ${e.message}`); return Resource.empty(); diff --git a/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts index 328830981d5..17c2f3b175e 100644 --- a/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts +++ b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts @@ -63,7 +63,10 @@ class GcpDetector implements Detector { if (process.env.KUBERNETES_SERVICE_HOST) this._addK8sLabels(labels, clusterName); - return new Resource(labels, this.constructor.name); + const resource = new Resource(labels); + config.logger.debug(`${this.constructor.name} found resource.`); + + return resource; } /** Add resource labels for K8s */ diff --git a/packages/opentelemetry-resources/src/Resource.ts b/packages/opentelemetry-resources/src/Resource.ts index 3d801d09a68..6e2c9f4b6ac 100644 --- a/packages/opentelemetry-resources/src/Resource.ts +++ b/packages/opentelemetry-resources/src/Resource.ts @@ -50,11 +50,6 @@ export class Resource { * TODO: Consider to add check/validation on labels. */ readonly labels: ResourceLabels, - - /** - * Name of the resource detector that detected this resource - */ - readonly detectedBy: string = 'Unknown detector' ) {} /** diff --git a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts index 70379745fd6..fb786ea9495 100644 --- a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts +++ b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts @@ -74,8 +74,6 @@ const logResources = (logger: Logger, resources: Array) => { sorted: true, compact: false, }); - const detectorName = resource.detectedBy; - logger.debug(`${detectorName} found resource.`); logger.debug(resourceDebugString); } }); diff --git a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts index f1f8ddb711e..22a162544e9 100644 --- a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts +++ b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts @@ -64,7 +64,9 @@ class EnvDetector implements Detector { const labels = this._parseResourceLabels( process.env.OTEL_RESOURCE_LABELS ); - return new Resource(labels, this.constructor.name); + const resource = new Resource(labels); + config.logger.debug(`${this.constructor.name} found resource.`); + return resource; } catch (e) { config.logger.debug(`EnvDetector failed: ${e.message}`); return Resource.empty(); diff --git a/packages/opentelemetry-sdk-node/package.json b/packages/opentelemetry-sdk-node/package.json index a9c8d814444..acd07f48074 100644 --- a/packages/opentelemetry-sdk-node/package.json +++ b/packages/opentelemetry-sdk-node/package.json @@ -51,7 +51,6 @@ "@opentelemetry/tracing": "^0.10.2", "@opentelemetry/resource-detector-aws": "^0.10.2", "@opentelemetry/resource-detector-gcp": "^0.10.2", - "@opentelemetry/resource-detector-env": "^0.10.2", "nock": "12.0.3" }, "devDependencies": { diff --git a/packages/opentelemetry-sdk-node/src/sdk.ts b/packages/opentelemetry-sdk-node/src/sdk.ts index 98154082154..0ed393f69d3 100644 --- a/packages/opentelemetry-sdk-node/src/sdk.ts +++ b/packages/opentelemetry-sdk-node/src/sdk.ts @@ -22,12 +22,12 @@ import { detectResources, Resource, ResourceDetectionConfig, + envDetector, } from '@opentelemetry/resources'; import { BatchSpanProcessor, SpanProcessor } from '@opentelemetry/tracing'; import { NodeSDKConfiguration } from './types'; import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; import { gcpDetector } from '@opentelemetry/resource-detector-gcp'; -import { envDetector } from '@opentelemetry/resource-detector-env'; /** This class represents everything needed to register a fully configured OpenTelemetry Node.js SDK */ export class NodeSDK { From 6a06ef8a8b8a4840202902518391d6eff90bd19c Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Fri, 14 Aug 2020 09:08:57 -0700 Subject: [PATCH 09/15] style: fx misc type assertions --- .../src/detectors/AwsEc2Detector.ts | 3 ++- .../src/platform/node/detect-resources.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts index 9279c778f8f..13b9ebd5747 100644 --- a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts +++ b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts @@ -19,6 +19,7 @@ import { Resource, CLOUD_RESOURCE, HOST_RESOURCE, + ResourceDetectionConfigWithLogger, } from '@opentelemetry/resources'; import * as http from 'http'; @@ -44,7 +45,7 @@ class AwsEc2Detector implements Detector { * * @param config The resource detection config with a required logger */ - async detect(config: any): Promise { + async detect(config: ResourceDetectionConfigWithLogger): Promise { try { const { accountId, diff --git a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts index fb786ea9495..88c328c1fa4 100644 --- a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts +++ b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts @@ -35,7 +35,7 @@ export const detectResources = async ( const internalConfig: ResourceDetectionConfigWithLogger = Object.assign( { logger: new NoopLogger(), - } as ResourceDetectionConfigWithLogger, + }, config ); From b295d8df512687b99880c1d55b61e448a818a46d Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Fri, 14 Aug 2020 09:50:23 -0700 Subject: [PATCH 10/15] refactor: mv detector logging to detect-resources --- .../src/detectors/AwsEc2Detector.ts | 43 ++++++++----------- .../src/detectors/GcpDetector.ts | 8 ++-- .../src/index.ts | 3 ++ .../src/platform/node/detect-resources.ts | 9 ++-- .../platform/node/detectors/EnvDetector.ts | 23 ++++------ .../opentelemetry-sdk-node/test/sdk.test.ts | 5 +-- 6 files changed, 39 insertions(+), 52 deletions(-) diff --git a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts index 13b9ebd5747..b26e3703dcd 100644 --- a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts +++ b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts @@ -45,31 +45,24 @@ class AwsEc2Detector implements Detector { * * @param config The resource detection config with a required logger */ - async detect(config: ResourceDetectionConfigWithLogger): Promise { - try { - const { - accountId, - instanceId, - instanceType, - region, - availabilityZone, - } = await this._awsMetadataAccessor(); - const resource = new Resource( - { - [CLOUD_RESOURCE.PROVIDER]: 'aws', - [CLOUD_RESOURCE.ACCOUNT_ID]: accountId, - [CLOUD_RESOURCE.REGION]: region, - [CLOUD_RESOURCE.ZONE]: availabilityZone, - [HOST_RESOURCE.ID]: instanceId, - [HOST_RESOURCE.TYPE]: instanceType, - }, - ); - config.logger.debug(`${this.constructor.name} found resource.`); - return resource; - } catch (e) { - config.logger.debug(`AwsEc2Detector failed: ${e.message}`); - return Resource.empty(); - } + async detect(_config: ResourceDetectionConfigWithLogger): Promise { + const { + accountId, + instanceId, + instanceType, + region, + availabilityZone, + } = await this._awsMetadataAccessor(); + return new Resource( + { + [CLOUD_RESOURCE.PROVIDER]: 'aws', + [CLOUD_RESOURCE.ACCOUNT_ID]: accountId, + [CLOUD_RESOURCE.REGION]: region, + [CLOUD_RESOURCE.ZONE]: availabilityZone, + [HOST_RESOURCE.ID]: instanceId, + [HOST_RESOURCE.TYPE]: instanceType, + }, + ); } /** diff --git a/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts index 17c2f3b175e..b85f5519b69 100644 --- a/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts +++ b/packages/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts @@ -60,13 +60,11 @@ class GcpDetector implements Detector { labels[CLOUD_RESOURCE.ZONE] = zoneId; labels[CLOUD_RESOURCE.PROVIDER] = 'gcp'; - if (process.env.KUBERNETES_SERVICE_HOST) + if (process.env.KUBERNETES_SERVICE_HOST) { this._addK8sLabels(labels, clusterName); + } - const resource = new Resource(labels); - config.logger.debug(`${this.constructor.name} found resource.`); - - return resource; + return new Resource(labels); } /** Add resource labels for K8s */ diff --git a/packages/opentelemetry-resource-detector-gcp/src/index.ts b/packages/opentelemetry-resource-detector-gcp/src/index.ts index 0acba8788cf..f281d4fdcdf 100644 --- a/packages/opentelemetry-resource-detector-gcp/src/index.ts +++ b/packages/opentelemetry-resource-detector-gcp/src/index.ts @@ -15,3 +15,6 @@ */ export * from './detectors'; + +// Internal - used for tests only +export { resetIsAvailableCache } from 'gcp-metadata'; diff --git a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts index 88c328c1fa4..2bc0634d3b3 100644 --- a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts +++ b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts @@ -40,10 +40,13 @@ export const detectResources = async ( ); const resources: Array = await Promise.all( - (internalConfig.detectors || []).map(d => { + (internalConfig.detectors || []).map(async (d) => { try { - return d.detect(internalConfig); - } catch { + const resource = await d.detect(internalConfig); + config.logger?.debug(`${d.constructor.name} found resource.`, resource); + return resource; + } catch (e) { + config.logger?.debug(`${d.constructor.name} failed: ${e.message}`); return Resource.empty(); } }) diff --git a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts index 22a162544e9..c1fadcd771b 100644 --- a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts +++ b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts @@ -53,24 +53,17 @@ class EnvDetector implements Detector { * @param config The resource detection config with a required logger */ async detect(config: ResourceDetectionConfigWithLogger): Promise { - try { - const labelString = process.env.OTEL_RESOURCE_LABELS; - if (!labelString) { - config.logger.debug( - 'EnvDetector failed: Environment variable "OTEL_RESOURCE_LABELS" is missing.' - ); - return Resource.empty(); - } - const labels = this._parseResourceLabels( - process.env.OTEL_RESOURCE_LABELS + const labelString = process.env.OTEL_RESOURCE_LABELS; + if (!labelString) { + config.logger.debug( + 'EnvDetector failed: Environment variable "OTEL_RESOURCE_LABELS" is missing.' ); - const resource = new Resource(labels); - config.logger.debug(`${this.constructor.name} found resource.`); - return resource; - } catch (e) { - config.logger.debug(`EnvDetector failed: ${e.message}`); return Resource.empty(); } + const labels = this._parseResourceLabels( + process.env.OTEL_RESOURCE_LABELS + ); + return new Resource(labels); } /** diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index e661fd898c9..df18b5a6521 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -40,7 +40,7 @@ import * as NodeConfig from '@opentelemetry/node/build/src/config'; import * as Sinon from 'sinon'; import { Resource } from '@opentelemetry/resources'; import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; - +import { resetIsAvailableCache } from '@opentelemetry/resource-detector-gcp'; import { assertServiceResource, assertCloudResource, @@ -52,9 +52,7 @@ import { HEADER_VALUE, HOST_ADDRESS, SECONDARY_HOST_ADDRESS, - resetIsAvailableCache, } from 'gcp-metadata'; -import { resetIsAvailableCache as otherResetIsAvailableCache } from '@opentelemetry/resource-detector-gcp/node_modules/gcp-metadata'; const HEADERS = { [HEADER_NAME.toLowerCase()]: HEADER_VALUE, @@ -183,7 +181,6 @@ describe('Node SDK', () => { afterEach(() => { sdk['_resource'] = Resource.empty(); resetIsAvailableCache(); - otherResetIsAvailableCache(); nock.cleanAll(); nock.enableNetConnect(); delete process.env.OTEL_RESOURCE_LABELS; From 47b5d1dbc8925bb73cb29d08b4df2aa20fe0c1d3 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Fri, 14 Aug 2020 15:12:34 -0700 Subject: [PATCH 11/15] fix: resolve merge conflict --- .../opentelemetry-sdk-node/test/sdk.test.ts | 55 ++++++++++++------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index df18b5a6521..72e9ecdb5e9 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -38,7 +38,6 @@ import * as assert from 'assert'; import { NodeSDK } from '../src'; import * as NodeConfig from '@opentelemetry/node/build/src/config'; import * as Sinon from 'sinon'; -import { Resource } from '@opentelemetry/resources'; import { awsEc2Detector } from '@opentelemetry/resource-detector-aws'; import { resetIsAvailableCache } from '@opentelemetry/resource-detector-gcp'; import { @@ -167,27 +166,29 @@ describe('Node SDK', () => { }); }); - describe('detectResources', async () => { - const sdk = new NodeSDK({ - autoDetectResources: true, - }); + describe('detectResources', async () => { beforeEach(() => { nock.disableNetConnect(); - process.env.OTEL_RESOURCE_LABELS = + process.env.OTEL_RESOURCE_ATTRIBUTES = 'service.instance.id=627cc493,service.name=my-service,service.namespace=default,service.version=0.0.1'; }); afterEach(() => { - sdk['_resource'] = Resource.empty(); - resetIsAvailableCache(); nock.cleanAll(); nock.enableNetConnect(); - delete process.env.OTEL_RESOURCE_LABELS; + delete process.env.OTEL_RESOURCE_ATTRIBUTES; }); describe('in GCP environment', () => { + after(() => { + resetIsAvailableCache(); + }); + it('returns a merged resource', async () => { + const sdk = new NodeSDK({ + autoDetectResources: true, + }); const gcpScope = nock(HOST_ADDRESS) .get(INSTANCE_PATH) .reply(200, {}, HEADERS) @@ -206,7 +207,7 @@ describe('Node SDK', () => { .get(AWS_PATH) .replyWithError({ code: 'ENOTFOUND' }); await sdk.detectResources(); - const resource: Resource = sdk['_resource']; + const resource = sdk["_resource"]; awsScope.done(); gcpSecondaryScope.done(); @@ -229,6 +230,9 @@ describe('Node SDK', () => { describe('in AWS environment', () => { it('returns a merged resource', async () => { + const sdk = new NodeSDK({ + autoDetectResources: true, + }); const gcpScope = nock(HOST_ADDRESS).get(INSTANCE_PATH).replyWithError({ code: 'ENOTFOUND', }); @@ -240,10 +244,8 @@ describe('Node SDK', () => { const awsScope = nock(AWS_HOST) .get(AWS_PATH) .reply(200, () => mockedAwsResponse); - await sdk.detectResources(); - const resource: Resource = sdk['_resource']; - + const resource = sdk["_resource"]; gcpSecondaryScope.done(); gcpScope.done(); awsScope.done(); @@ -269,10 +271,12 @@ describe('Node SDK', () => { describe('with a buggy detector', () => { it('returns a merged resource', async () => { + const sdk = new NodeSDK({ + autoDetectResources: true, + }); const stub = Sinon.stub(awsEc2Detector, 'detect').throws(); - await sdk.detectResources(); - const resource: Resource = sdk['_resource']; + const resource = sdk["_resource"]; assertServiceResource(resource, { instanceId: '627cc493', @@ -289,7 +293,7 @@ describe('Node SDK', () => { // Local functions to test if a mocked method is ever called with a specific argument or regex matching for an argument. // Needed because of race condition with parallel detectors. const callArgsContains = ( - mockedFunction: Sinon.SinonSpy, + mockedFunction: sinon.SinonSpy, arg: any ): boolean => { return mockedFunction.getCalls().some(call => { @@ -297,7 +301,7 @@ describe('Node SDK', () => { }); }; const callArgsMatches = ( - mockedFunction: Sinon.SinonSpy, + mockedFunction: sinon.SinonSpy, regex: RegExp ): boolean => { return mockedFunction.getCalls().some(call => { @@ -306,6 +310,9 @@ describe('Node SDK', () => { }; it('prints detected resources and debug messages to the logger', async () => { + const sdk = new NodeSDK({ + autoDetectResources: true, + }); // This test depends on the env detector to be functioning as intended const mockedLoggerMethod = Sinon.fake(); await sdk.detectResources({ @@ -345,10 +352,13 @@ describe('Node SDK', () => { describe('with missing environemnt variable', () => { beforeEach(() => { - delete process.env.OTEL_RESOURCE_LABELS; + delete process.env.OTEL_RESOURCE_ATTRIBUTES; }); it('prints correct error messages when EnvDetector has no env variable', async () => { + const sdk = new NodeSDK({ + autoDetectResources: true, + }); const mockedLoggerMethod = Sinon.fake(); await sdk.detectResources({ logger: { @@ -362,7 +372,7 @@ describe('Node SDK', () => { assert.ok( callArgsContains( mockedLoggerMethod, - 'EnvDetector failed: Environment variable "OTEL_RESOURCE_LABELS" is missing.' + 'EnvDetector failed: Environment variable "OTEL_RESOURCE_ATTRIBUTES" is missing.' ) ); }); @@ -370,10 +380,13 @@ describe('Node SDK', () => { describe('with a faulty environment variable', () => { beforeEach(() => { - process.env.OTEL_RESOURCE_LABELS = 'bad=~label'; + process.env.OTEL_RESOURCE_ATTRIBUTES = 'bad=~attribute'; }); it('prints correct error messages when EnvDetector has an invalid variable', async () => { + const sdk = new NodeSDK({ + autoDetectResources: true, + }); const mockedLoggerMethod = Sinon.fake(); await sdk.detectResources({ logger: { @@ -387,7 +400,7 @@ describe('Node SDK', () => { assert.ok( callArgsContains( mockedLoggerMethod, - 'EnvDetector failed: Label value should be a ASCII string with a length not exceed 255 characters.' + 'EnvDetector failed: Attribute value should be a ASCII string with a length not exceed 255 characters.' ) ); }); From 8d11fd217c86f96dd5b7d871b8a84d2edee4e7a3 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Fri, 14 Aug 2020 17:07:00 -0700 Subject: [PATCH 12/15] fix: failing tests --- .../src/detectors/AwsEc2Detector.ts | 18 ++++++------- .../test/detectors/AwsEc2Detector.test.ts | 16 ----------- .../src/platform/node/detect-resources.ts | 2 +- .../platform/node/detectors/EnvDetector.ts | 4 +-- .../test/detectors/EnvDetector.test.ts | 5 +++- packages/opentelemetry-sdk-node/src/sdk.ts | 2 +- .../opentelemetry-sdk-node/test/sdk.test.ts | 27 +++++++++++++++---- 7 files changed, 38 insertions(+), 36 deletions(-) diff --git a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts index bf7f599fb19..a3f1f38f0a0 100644 --- a/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts +++ b/packages/opentelemetry-resource-detector-aws/src/detectors/AwsEc2Detector.ts @@ -53,16 +53,14 @@ class AwsEc2Detector implements Detector { region, availabilityZone, } = await this._awsMetadataAccessor(); - return new Resource( - { - [CLOUD_RESOURCE.PROVIDER]: 'aws', - [CLOUD_RESOURCE.ACCOUNT_ID]: accountId, - [CLOUD_RESOURCE.REGION]: region, - [CLOUD_RESOURCE.ZONE]: availabilityZone, - [HOST_RESOURCE.ID]: instanceId, - [HOST_RESOURCE.TYPE]: instanceType, - }, - ); + return new Resource({ + [CLOUD_RESOURCE.PROVIDER]: 'aws', + [CLOUD_RESOURCE.ACCOUNT_ID]: accountId, + [CLOUD_RESOURCE.REGION]: region, + [CLOUD_RESOURCE.ZONE]: availabilityZone, + [HOST_RESOURCE.ID]: instanceId, + [HOST_RESOURCE.TYPE]: instanceType, + }); } /** diff --git a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts index a00d37ffd0a..c92d7fcbbe0 100644 --- a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts @@ -22,7 +22,6 @@ import { awsEc2Detector } from '../../src'; import { assertCloudResource, assertHostResource, - assertEmptyResource, } from '@opentelemetry/resources/test/util/resource-assertions'; import { NoopLogger } from '@opentelemetry/core'; @@ -71,19 +70,4 @@ describe('awsEc2Detector', () => { }); }); }); - - describe('with failing request', () => { - it('should return empty resource', async () => { - const scope = nock(AWS_HOST).get(AWS_PATH).replyWithError({ - code: 'ENOTFOUND', - }); - const resource: Resource = await awsEc2Detector.detect({ - logger: new NoopLogger(), - }); - scope.done(); - - assert.ok(resource); - assertEmptyResource(resource); - }); - }); }); diff --git a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts index bb37a79e060..37fa35278d5 100644 --- a/packages/opentelemetry-resources/src/platform/node/detect-resources.ts +++ b/packages/opentelemetry-resources/src/platform/node/detect-resources.ts @@ -40,7 +40,7 @@ export const detectResources = async ( ); const resources: Array = await Promise.all( - (internalConfig.detectors || []).map(async (d) => { + (internalConfig.detectors || []).map(async d => { try { const resource = await d.detect(internalConfig); config.logger?.debug(`${d.constructor.name} found resource.`, resource); diff --git a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts index 47c4e280680..a448a11d1f0 100644 --- a/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts +++ b/packages/opentelemetry-resources/src/platform/node/detectors/EnvDetector.ts @@ -106,10 +106,10 @@ class EnvDetector implements Detector { key = key.trim(); value = value.trim().split('^"|"$').join(''); if (!this._isValidAndNotEmpty(key)) { - throw new Error(`Label key ${this._ERROR_MESSAGE_INVALID_CHARS}`); + throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`); } if (!this._isValid(value)) { - throw new Error(`Label value ${this._ERROR_MESSAGE_INVALID_VALUE}`); + throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`); } attributes[key] = value; } diff --git a/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts b/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts index 281c8ed68aa..df45725cb9d 100644 --- a/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts +++ b/packages/opentelemetry-resources/test/detectors/EnvDetector.test.ts @@ -15,7 +15,10 @@ */ import { envDetector, K8S_RESOURCE, Resource } from '../../src'; -import { assertK8sResource, assertEmptyResource } from '../util/resource-assertions'; +import { + assertK8sResource, + assertEmptyResource, +} from '../util/resource-assertions'; import { NoopLogger } from '@opentelemetry/core'; describe('envDetector()', () => { diff --git a/packages/opentelemetry-sdk-node/src/sdk.ts b/packages/opentelemetry-sdk-node/src/sdk.ts index 0ed393f69d3..3ab7d614e2a 100644 --- a/packages/opentelemetry-sdk-node/src/sdk.ts +++ b/packages/opentelemetry-sdk-node/src/sdk.ts @@ -128,8 +128,8 @@ export class NodeSDK { /** Detect resource attributes */ public async detectResources(config?: ResourceDetectionConfig) { const internalConfig: ResourceDetectionConfig = { - ...config, detectors: [awsEc2Detector, gcpDetector, envDetector], + ...config, }; this.addResource(await detectResources(internalConfig)); diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index 72e9ecdb5e9..17886e1bc47 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -52,6 +52,7 @@ import { HOST_ADDRESS, SECONDARY_HOST_ADDRESS, } from 'gcp-metadata'; +import { Resource } from '@opentelemetry/resources'; const HEADERS = { [HEADER_NAME.toLowerCase()]: HEADER_VALUE, @@ -166,7 +167,6 @@ describe('Node SDK', () => { }); }); - describe('detectResources', async () => { beforeEach(() => { nock.disableNetConnect(); @@ -207,7 +207,7 @@ describe('Node SDK', () => { .get(AWS_PATH) .replyWithError({ code: 'ENOTFOUND' }); await sdk.detectResources(); - const resource = sdk["_resource"]; + const resource = sdk['_resource']; awsScope.done(); gcpSecondaryScope.done(); @@ -245,7 +245,7 @@ describe('Node SDK', () => { .get(AWS_PATH) .reply(200, () => mockedAwsResponse); await sdk.detectResources(); - const resource = sdk["_resource"]; + const resource = sdk['_resource']; gcpSecondaryScope.done(); gcpScope.done(); awsScope.done(); @@ -267,6 +267,23 @@ describe('Node SDK', () => { version: '0.0.1', }); }); + + it('should return empty resource', async () => { + const scope = nock(AWS_HOST).get(AWS_PATH).replyWithError({ + code: 'ENOTFOUND', + }); + const sdk = new NodeSDK({ + autoDetectResources: true, + }); + await sdk.detectResources({ + detectors: [awsEc2Detector], + }); + const resource: Resource = sdk['_resource']; + scope.done(); + + assert.ok(resource); + assert.deepStrictEqual(resource, Resource.createTelemetrySDKResource()); + }); }); describe('with a buggy detector', () => { @@ -276,7 +293,7 @@ describe('Node SDK', () => { }); const stub = Sinon.stub(awsEc2Detector, 'detect').throws(); await sdk.detectResources(); - const resource = sdk["_resource"]; + const resource = sdk['_resource']; assertServiceResource(resource, { instanceId: '627cc493', @@ -350,7 +367,7 @@ describe('Node SDK', () => { ); }); - describe('with missing environemnt variable', () => { + describe('with missing environment variable', () => { beforeEach(() => { delete process.env.OTEL_RESOURCE_ATTRIBUTES; }); From 229f6d5f579e77bc871feb5b9a7920fd073a7ab7 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Tue, 18 Aug 2020 10:51:43 -0700 Subject: [PATCH 13/15] fix: failing sdk test --- .../opentelemetry-sdk-node/test/sdk.test.ts | 44 +++++++++++++------ 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index 17886e1bc47..0cb51a898ef 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -15,7 +15,6 @@ */ import * as nock from 'nock'; -import { URL } from 'url'; import { context, metrics, @@ -63,17 +62,22 @@ const PROJECT_ID_PATH = BASE_PATH + '/project/project-id'; const ZONE_PATH = BASE_PATH + '/instance/zone'; const CLUSTER_NAME_PATH = BASE_PATH + '/instance/attributes/cluster-name'; -const { origin: AWS_HOST, pathname: AWS_PATH } = new URL( - awsEc2Detector.AWS_INSTANCE_IDENTITY_DOCUMENT_URI -); +const AWS_HOST = 'http://' + awsEc2Detector.AWS_IDMS_ENDPOINT; +const AWS_TOKEN_PATH = awsEc2Detector.AWS_INSTANCE_TOKEN_DOCUMENT_PATH; +const AWS_IDENTITY_PATH = awsEc2Detector.AWS_INSTANCE_IDENTITY_DOCUMENT_PATH; +const AWS_HOST_PATH = awsEc2Detector.AWS_INSTANCE_HOST_DOCUMENT_PATH; +const AWS_METADATA_TTL_HEADER = awsEc2Detector.AWS_METADATA_TTL_HEADER; +const AWS_METADATA_TOKEN_HEADER = awsEc2Detector.AWS_METADATA_TOKEN_HEADER; -const mockedAwsResponse = { +const mockedTokenResponse = 'my-token'; +const mockedIdentityResponse = { instanceId: 'my-instance-id', instanceType: 'my-instance-type', accountId: 'my-account-id', region: 'my-region', availabilityZone: 'my-zone', }; +const mockedHostResponse = 'my-hostname'; describe('Node SDK', () => { before(() => { @@ -204,7 +208,9 @@ describe('Node SDK', () => { .get(INSTANCE_PATH) .reply(200, {}, HEADERS); const awsScope = nock(AWS_HOST) - .get(AWS_PATH) + .persist() + .put(AWS_TOKEN_PATH) + .matchHeader(AWS_METADATA_TTL_HEADER, '60') .replyWithError({ code: 'ENOTFOUND' }); await sdk.detectResources(); const resource = sdk['_resource']; @@ -242,10 +248,18 @@ describe('Node SDK', () => { code: 'ENOTFOUND', }); const awsScope = nock(AWS_HOST) - .get(AWS_PATH) - .reply(200, () => mockedAwsResponse); + .persist() + .put(AWS_TOKEN_PATH) + .matchHeader(AWS_METADATA_TTL_HEADER, '60') + .reply(200, () => mockedTokenResponse) + .get(AWS_IDENTITY_PATH) + .matchHeader(AWS_METADATA_TOKEN_HEADER, mockedTokenResponse) + .reply(200, () => mockedIdentityResponse) + .get(AWS_HOST_PATH) + .matchHeader(AWS_METADATA_TOKEN_HEADER, mockedTokenResponse) + .reply(200, () => mockedHostResponse); await sdk.detectResources(); - const resource = sdk['_resource']; + const resource: Resource = sdk['_resource']; gcpSecondaryScope.done(); gcpScope.done(); awsScope.done(); @@ -259,6 +273,8 @@ describe('Node SDK', () => { assertHostResource(resource, { id: 'my-instance-id', hostType: 'my-instance-type', + name: 'my-hostname', + hostName: 'my-hostname', }); assertServiceResource(resource, { instanceId: '627cc493', @@ -267,9 +283,11 @@ describe('Node SDK', () => { version: '0.0.1', }); }); + }); + describe('in no environment', () => { it('should return empty resource', async () => { - const scope = nock(AWS_HOST).get(AWS_PATH).replyWithError({ + const scope = nock(AWS_HOST).put(AWS_TOKEN_PATH).replyWithError({ code: 'ENOTFOUND', }); const sdk = new NodeSDK({ @@ -279,10 +297,10 @@ describe('Node SDK', () => { detectors: [awsEc2Detector], }); const resource: Resource = sdk['_resource']; - scope.done(); - assert.ok(resource); assert.deepStrictEqual(resource, Resource.createTelemetrySDKResource()); + + scope.done(); }); }); @@ -351,7 +369,7 @@ describe('Node SDK', () => { assert.ok( callArgsContains( mockedLoggerMethod, - 'AwsEc2Detector failed: Nock: Disallowed net connect for "169.254.169.254:80/latest/dynamic/instance-identity/document"' + 'AwsEc2Detector failed: Nock: Disallowed net connect for "169.254.169.254:80/latest/api/token"' ) ); // Test that the Env Detector successfully found its resource and populated it with the right values. From 209c32be53eb377b0a58cb0b79adf20b213583c3 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Tue, 18 Aug 2020 11:30:31 -0700 Subject: [PATCH 14/15] fix: aws detector tests --- .../test/detectors/AwsEc2Detector.test.ts | 55 +++++++++++-------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts index 698508fe94c..7f650e519dc 100644 --- a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts @@ -89,7 +89,8 @@ describe('awsEc2Detector', () => { }); describe('with unsuccessful request', () => { - it('should return empty resource when receiving error response code', async () => { + it('should throw when receiving error response code', async () => { + const expectedError = new Error('Failed to load page, status code: 404'); const scope = nock(AWS_HOST) .persist() .put(AWS_TOKEN_PATH) @@ -100,19 +101,22 @@ describe('awsEc2Detector', () => { .reply(200, () => mockedIdentityResponse) .get(AWS_HOST_PATH) .matchHeader(AWS_METADATA_TOKEN_HEADER, mockedTokenResponse) - .reply(404, () => new Error('NOT FOUND')); + .reply(404, () => new Error()); - const resource: Resource = await awsEc2Detector.detect({ - logger: new NoopLogger(), - }); + try { + await awsEc2Detector.detect({ + logger: new NoopLogger(), + }); + assert.ok(false, 'Expected to throw'); + } catch (err) { + assert.deepStrictEqual(err, expectedError); + } scope.done(); - - assert.ok(resource); - assertEmptyResource(resource); }); - it('should return empty resource when timeout', async () => { + it('should throw when timed out', async () => { + const expectedError = new Error('EC2 metadata api request timed out.'); const scope = nock(AWS_HOST) .put(AWS_TOKEN_PATH) .matchHeader(AWS_METADATA_TTL_HEADER, '60') @@ -125,33 +129,38 @@ describe('awsEc2Detector', () => { .delayConnection(2000) .reply(200, () => mockedHostResponse); - const resource: Resource = await awsEc2Detector.detect({ - logger: new NoopLogger(), - }); + try { + await awsEc2Detector.detect({ + logger: new NoopLogger(), + }); + assert.ok(false, 'Expected to throw'); + } catch (err) { + assert.deepStrictEqual(err, expectedError); + } scope.done(); - - assert.ok(resource); - assertEmptyResource(resource); }); - it('should return empty resource when replied Error', async () => { + it('should throw when replied with an Error', async () => { + const expectedError = new Error('NOT FOUND'); const scope = nock(AWS_HOST) .put(AWS_TOKEN_PATH) .matchHeader(AWS_METADATA_TTL_HEADER, '60') .reply(200, () => mockedTokenResponse) .get(AWS_IDENTITY_PATH) .matchHeader(AWS_METADATA_TOKEN_HEADER, mockedTokenResponse) - .replyWithError('NOT FOUND'); + .replyWithError(expectedError.message); - const resource: Resource = await awsEc2Detector.detect({ - logger: new NoopLogger(), - }); + try { + await awsEc2Detector.detect({ + logger: new NoopLogger(), + }); + assert.ok(false, 'Expected to throw'); + } catch (err) { + assert.deepStrictEqual(err, expectedError); + } scope.done(); - - assert.ok(resource); - assertEmptyResource(resource); }); }); }); From 650137dea3e80627cf65f16b22fed49e490bbdea Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Tue, 18 Aug 2020 12:08:27 -0700 Subject: [PATCH 15/15] fix: linting --- .../test/detectors/AwsEc2Detector.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts index 7f650e519dc..99461164fd1 100644 --- a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts @@ -21,7 +21,6 @@ import { awsEc2Detector } from '../../src'; import { assertCloudResource, assertHostResource, - assertEmptyResource, } from '@opentelemetry/resources/test/util/resource-assertions'; import { NoopLogger } from '@opentelemetry/core';