From 1b0caa61972d969e3baea6a7db365e66dafe0c5d Mon Sep 17 00:00:00 2001 From: Jackson Weber <47067795+JacksonWeber@users.noreply.github.com> Date: Fri, 27 Oct 2023 11:32:25 -0700 Subject: [PATCH] feat: Add Azure App Service, Azure Functions, and VM Resource Detectors (#1740) * Implement app service detector. * Finish vm detector. * feat(azure-resource-detector): Fix Azure VM detector. * feat(azure-resource-detector) Add readme. * Add changelog entry. * feat(azure-resource-detector): Add azure functions detector. * fix(azure-resource-detectors): Clean up typos, deps and lint. * fix(azure-resource-detector): Add types file. * update(azure-resource-detectors): Update component owners. * Update release-please config. * Update release-please manifest. * Fix lint errors. --- .github/component_owners.yml | 3 + .release-please-manifest.json | 2 +- .../.eslintignore | 1 + .../.eslintrc.js | 7 + .../.npmignore | 3 + .../CHANGELOG.md | 7 + .../LICENSE | 201 +++++++++ .../README.md | 77 ++++ .../package.json | 53 +++ .../src/detectors/AzureAppServiceDetector.ts | 104 +++++ .../src/detectors/AzureFunctionsDetector.ts | 97 ++++ .../src/detectors/AzureVmDetector.ts | 106 +++++ .../src/detectors/index.ts | 17 + .../src/index.ts | 17 + .../src/types.ts | 182 ++++++++ .../detectors/AzureAppServiceDetector.test.ts | 151 +++++++ .../detectors/AzureFunctionsDetector.test.ts | 70 +++ .../test/detectors/AzureVmDetector.test.ts | 418 ++++++++++++++++++ .../tsconfig.json | 11 + release-please-config.json | 1 + 20 files changed, 1527 insertions(+), 1 deletion(-) create mode 100644 detectors/node/opentelemetry-resource-detector-azure/.eslintignore create mode 100644 detectors/node/opentelemetry-resource-detector-azure/.eslintrc.js create mode 100644 detectors/node/opentelemetry-resource-detector-azure/.npmignore create mode 100644 detectors/node/opentelemetry-resource-detector-azure/CHANGELOG.md create mode 100644 detectors/node/opentelemetry-resource-detector-azure/LICENSE create mode 100644 detectors/node/opentelemetry-resource-detector-azure/README.md create mode 100644 detectors/node/opentelemetry-resource-detector-azure/package.json create mode 100644 detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureAppServiceDetector.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureFunctionsDetector.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/src/detectors/index.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/src/index.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/src/types.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts create mode 100644 detectors/node/opentelemetry-resource-detector-azure/tsconfig.json diff --git a/.github/component_owners.yml b/.github/component_owners.yml index a3ad46b401..880c784403 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -4,6 +4,9 @@ components: - legendecas detectors/node/opentelemetry-resource-detector-aws: - carolabadeer + detectors/node/opentelemetry-resource-detector-azure: + - jacksonweber + - hectorhdzg detectors/node/opentelemetry-resource-detector-container: - abhee11 detectors/node/opentelemetry-resource-detector-gcp: diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0f570774ed..9436b24cd1 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1 +1 @@ -{"detectors/node/opentelemetry-resource-detector-alibaba-cloud":"0.28.2","detectors/node/opentelemetry-resource-detector-aws":"1.3.2","detectors/node/opentelemetry-resource-detector-container":"0.3.2","detectors/node/opentelemetry-resource-detector-gcp":"0.29.2","detectors/node/opentelemetry-resource-detector-github":"0.28.1","detectors/node/opentelemetry-resource-detector-instana":"0.5.2","metapackages/auto-instrumentations-node":"0.39.4","metapackages/auto-instrumentations-web":"0.33.2","packages/opentelemetry-host-metrics":"0.33.1","packages/opentelemetry-id-generator-aws-xray":"1.2.1","packages/opentelemetry-propagation-utils":"0.30.2","packages/opentelemetry-redis-common":"0.36.1","packages/opentelemetry-sql-common":"0.40.0","packages/opentelemetry-test-utils":"0.34.2","plugins/node/instrumentation-amqplib":"0.33.2","plugins/node/instrumentation-cucumber":"0.1.1","plugins/node/instrumentation-dataloader":"0.5.2","plugins/node/instrumentation-fs":"0.8.2","plugins/node/instrumentation-lru-memoizer":"0.33.2","plugins/node/instrumentation-mongoose":"0.33.2","plugins/node/instrumentation-socket.io":"0.34.2","plugins/node/instrumentation-tedious":"0.6.2","plugins/node/opentelemetry-instrumentation-aws-lambda":"0.37.1","plugins/node/opentelemetry-instrumentation-aws-sdk":"0.36.1","plugins/node/opentelemetry-instrumentation-bunyan":"0.32.2","plugins/node/opentelemetry-instrumentation-cassandra":"0.33.2","plugins/node/opentelemetry-instrumentation-connect":"0.32.2","plugins/node/opentelemetry-instrumentation-dns":"0.32.3","plugins/node/opentelemetry-instrumentation-express":"0.33.2","plugins/node/opentelemetry-instrumentation-fastify":"0.32.3","plugins/node/opentelemetry-instrumentation-generic-pool":"0.32.3","plugins/node/opentelemetry-instrumentation-graphql":"0.35.2","plugins/node/opentelemetry-instrumentation-hapi":"0.33.1","plugins/node/opentelemetry-instrumentation-ioredis":"0.35.2","plugins/node/opentelemetry-instrumentation-knex":"0.32.2","plugins/node/opentelemetry-instrumentation-koa":"0.36.1","plugins/node/opentelemetry-instrumentation-memcached":"0.32.2","plugins/node/opentelemetry-instrumentation-mongodb":"0.37.1","plugins/node/opentelemetry-instrumentation-mysql":"0.34.2","plugins/node/opentelemetry-instrumentation-mysql2":"0.34.2","plugins/node/opentelemetry-instrumentation-nestjs-core":"0.33.2","plugins/node/opentelemetry-instrumentation-net":"0.32.2","plugins/node/opentelemetry-instrumentation-pg":"0.36.2","plugins/node/opentelemetry-instrumentation-pino":"0.34.2","plugins/node/opentelemetry-instrumentation-redis":"0.35.2","plugins/node/opentelemetry-instrumentation-redis-4":"0.35.3","plugins/node/opentelemetry-instrumentation-restify":"0.34.1","plugins/node/opentelemetry-instrumentation-router":"0.33.2","plugins/node/opentelemetry-instrumentation-winston":"0.32.2","plugins/web/opentelemetry-instrumentation-document-load":"0.33.2","plugins/web/opentelemetry-instrumentation-long-task":"0.33.2","plugins/web/opentelemetry-instrumentation-user-interaction":"0.33.2","plugins/web/opentelemetry-plugin-react-load":"0.29.1","propagators/opentelemetry-propagator-aws-xray":"1.3.1","propagators/opentelemetry-propagator-grpc-census-binary":"0.27.1","propagators/opentelemetry-propagator-instana":"0.3.1","propagators/opentelemetry-propagator-ot-trace":"0.27.1"} +{"detectors/node/opentelemetry-resource-detector-alibaba-cloud":"0.28.2","detectors/node/opentelemetry-resource-detector-aws":"1.3.2","detectors/node/opentelemetry-resource-detector-azure":"0.1.0","detectors/node/opentelemetry-resource-detector-container":"0.3.2","detectors/node/opentelemetry-resource-detector-gcp":"0.29.2","detectors/node/opentelemetry-resource-detector-github":"0.28.1","detectors/node/opentelemetry-resource-detector-instana":"0.5.2","metapackages/auto-instrumentations-node":"0.39.4","metapackages/auto-instrumentations-web":"0.33.2","packages/opentelemetry-host-metrics":"0.33.1","packages/opentelemetry-id-generator-aws-xray":"1.2.1","packages/opentelemetry-propagation-utils":"0.30.2","packages/opentelemetry-redis-common":"0.36.1","packages/opentelemetry-sql-common":"0.40.0","packages/opentelemetry-test-utils":"0.34.2","plugins/node/instrumentation-amqplib":"0.33.2","plugins/node/instrumentation-cucumber":"0.1.1","plugins/node/instrumentation-dataloader":"0.5.2","plugins/node/instrumentation-fs":"0.8.2","plugins/node/instrumentation-lru-memoizer":"0.33.2","plugins/node/instrumentation-mongoose":"0.33.2","plugins/node/instrumentation-socket.io":"0.34.2","plugins/node/instrumentation-tedious":"0.6.2","plugins/node/opentelemetry-instrumentation-aws-lambda":"0.37.1","plugins/node/opentelemetry-instrumentation-aws-sdk":"0.36.1","plugins/node/opentelemetry-instrumentation-bunyan":"0.32.2","plugins/node/opentelemetry-instrumentation-cassandra":"0.33.2","plugins/node/opentelemetry-instrumentation-connect":"0.32.2","plugins/node/opentelemetry-instrumentation-dns":"0.32.3","plugins/node/opentelemetry-instrumentation-express":"0.33.2","plugins/node/opentelemetry-instrumentation-fastify":"0.32.3","plugins/node/opentelemetry-instrumentation-generic-pool":"0.32.3","plugins/node/opentelemetry-instrumentation-graphql":"0.35.2","plugins/node/opentelemetry-instrumentation-hapi":"0.33.1","plugins/node/opentelemetry-instrumentation-ioredis":"0.35.2","plugins/node/opentelemetry-instrumentation-knex":"0.32.2","plugins/node/opentelemetry-instrumentation-koa":"0.36.1","plugins/node/opentelemetry-instrumentation-memcached":"0.32.2","plugins/node/opentelemetry-instrumentation-mongodb":"0.37.1","plugins/node/opentelemetry-instrumentation-mysql":"0.34.2","plugins/node/opentelemetry-instrumentation-mysql2":"0.34.2","plugins/node/opentelemetry-instrumentation-nestjs-core":"0.33.2","plugins/node/opentelemetry-instrumentation-net":"0.32.2","plugins/node/opentelemetry-instrumentation-pg":"0.36.2","plugins/node/opentelemetry-instrumentation-pino":"0.34.2","plugins/node/opentelemetry-instrumentation-redis":"0.35.2","plugins/node/opentelemetry-instrumentation-redis-4":"0.35.3","plugins/node/opentelemetry-instrumentation-restify":"0.34.1","plugins/node/opentelemetry-instrumentation-router":"0.33.2","plugins/node/opentelemetry-instrumentation-winston":"0.32.2","plugins/web/opentelemetry-instrumentation-document-load":"0.33.2","plugins/web/opentelemetry-instrumentation-long-task":"0.33.2","plugins/web/opentelemetry-instrumentation-user-interaction":"0.33.2","plugins/web/opentelemetry-plugin-react-load":"0.29.1","propagators/opentelemetry-propagator-aws-xray":"1.3.1","propagators/opentelemetry-propagator-grpc-census-binary":"0.27.1","propagators/opentelemetry-propagator-instana":"0.3.1","propagators/opentelemetry-propagator-ot-trace":"0.27.1"} diff --git a/detectors/node/opentelemetry-resource-detector-azure/.eslintignore b/detectors/node/opentelemetry-resource-detector-azure/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/.eslintignore @@ -0,0 +1 @@ +build diff --git a/detectors/node/opentelemetry-resource-detector-azure/.eslintrc.js b/detectors/node/opentelemetry-resource-detector-azure/.eslintrc.js new file mode 100644 index 0000000000..029ade4634 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + env: { + mocha: true, + node: true, + }, + ...require("../../../eslint.config.js"), +}; diff --git a/detectors/node/opentelemetry-resource-detector-azure/.npmignore b/detectors/node/opentelemetry-resource-detector-azure/.npmignore new file mode 100644 index 0000000000..42eabef04c --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/.npmignore @@ -0,0 +1,3 @@ +/bin +/coverage +/test diff --git a/detectors/node/opentelemetry-resource-detector-azure/CHANGELOG.md b/detectors/node/opentelemetry-resource-detector-azure/CHANGELOG.md new file mode 100644 index 0000000000..c3dae7b4c9 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## [0.1.0]() () + +### Features + +* Added resource detectors for Azure App Services and VMs ([#1740](https://github.com/open-telemetry/opentelemetry-js-contrib/pull/1740)) diff --git a/detectors/node/opentelemetry-resource-detector-azure/LICENSE b/detectors/node/opentelemetry-resource-detector-azure/LICENSE new file mode 100644 index 0000000000..6f13cd2fe6 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/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] 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 + + 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/detectors/node/opentelemetry-resource-detector-azure/README.md b/detectors/node/opentelemetry-resource-detector-azure/README.md new file mode 100644 index 0000000000..ea4efc6862 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/README.md @@ -0,0 +1,77 @@ +# OpenTelemetry Resource Detector for Azure + +[![NPM Published Version][npm-img]][npm-url] +[![Apache License][license-image]][license-image] + +[component owners](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/.github/component_owners.yml): @JacksonWeber + +Resource detector for Azure. + +## Installation + +```bash +npm install --save @opentelemetry/resource-detector-azure +``` + +## Usage + +```typescript +import { detectResources } from '@opentelemetry/resources'; +import { azureAppServiceDetector } from '@opentelemetry/resource-detector-azure'; +const resource = detectResourcesSync({ + detectors: [azureAppServiceDetector], +}); + +const tracerProvider = new NodeTracerProvider({ resource }); +``` + +## Available Detectors + +### App Service Resource Detector + +| Attribute | Description | +|-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| azure.app.service.stamp | The specific "stamp" cluster within Azure where the App Service is running, e.g., "waws-prod-sn1-001". | +| cloud.platform | The cloud platform. Here, it's always "azure_app_service". | +| cloud.provider | The cloud service provider. In this context, it's always "azure". | +| cloud.resource_id | The Azure Resource Manager URI uniquely identifying the Azure App Service. Typically in the format "/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Web/sites/{siteName}". | +| cloud.region | The Azure region where the App Service is hosted, e.g., "East US", "West Europe", etc. | +| deployment.environment | The deployment slot where the Azure App Service is running, such as "staging", "production", etc. | +| host.id | The primary hostname for the app, excluding any custom hostnames. | +| service.instance.id | The specific instance of the Azure App Service, useful in a scaled-out configuration. | +| service.name | The name of the Azure App Service. | + +### VM Resource Detector + +| Attribute | Description | +|--------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| azure.vm.scaleset.name | The name of the Virtual Machine Scale Set if the VM is part of one. | +| azure.vm.sku | The SKU of the Azure Virtual Machine's operating system. For instance, for a VM running Windows Server 2019 Datacenter edition, this value would be "2019-Datacenter". | +| cloud.platform | The cloud platform, which is always set to "azure_vm" in this context. | +| cloud.provider | The cloud service provider, which is always set to "azure" in this context. | +| cloud.region | The Azure region where the Virtual Machine is hosted, such as "East US", "West Europe", etc. | +| cloud.resource_id | The Azure Resource Manager URI uniquely identifying the Azure Virtual Machine. It typically follows this format: "/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Compute/virtualMachines/{vmName}". | +| host.id | A unique identifier for the VM host, for instance, "02aab8a4-74ef-476e-8182-f6d2ba4166a6". | +| host.name | The name of the host machine. | +| host.type | The size of the VM instance, for example, "Standard_D2s_v3". | +| os.type | The type of operating system running on the VM, such as "Linux" or "Windows". | +| os.version | The version of the operating system running on the VM. | +| service.instance.id | An identifier for a specific instance of the service running on the Azure VM, for example, "02aab8a4-74ef-476e-8182-f6d2ba4166a6". | + +### Azure Functions Resource Detector + +| Attribute | Description | +|-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| cloud.platform | The cloud platform. Here, it's always "azure_functions". | +| cloud.provider | The cloud service provider. In this context, it's always "azure". | +| cloud.region | The Azure region where the Azure Function is hosted, e.g., "East US", "West Europe", etc. | +| faas.instance | The specific instance of the Azure App Service, useful in a scaled-out configuration. | +| faas.name | The name of the Azure App Service. | +| faas.version | The version of the Azure Function being executed, e.g., "~4". | +| faas.max_memory | The amount of memory available to the Azure Function expressed in MiB. | + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] diff --git a/detectors/node/opentelemetry-resource-detector-azure/package.json b/detectors/node/opentelemetry-resource-detector-azure/package.json new file mode 100644 index 0000000000..6b47e05fba --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/package.json @@ -0,0 +1,53 @@ +{ + "name": "@opentelemetry/resource-detector-azure", + "version": "0.1.0", + "description": "OpenTelemetry SDK resource detector for Azure", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js-contrib", + "scripts": { + "clean": "rimraf build/*", + "compile": "tsc -p .", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "precompile": "tsc --version && lerna run version:update --scope @opentelemetry/resource-detector-azure --include-dependencies", + "prewatch": "npm run precompile", + "prepare": "npm run compile", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "tdd": "npm run test -- --watch-extensions ts --watch", + "watch": "tsc -w" + }, + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@opentelemetry/api": "^1.0.0", + "@opentelemetry/contrib-test-utils": "^0.34.1", + "@types/mocha": "8.2.3", + "@types/node": "18.6.5", + "@types/sinon": "10.0.18", + "mocha": "7.2.0", + "nock": "13.3.3", + "nyc": "15.1.0", + "rimraf": "5.0.5", + "ts-mocha": "10.0.0", + "typescript": "4.4.4" + }, + "dependencies": { + "@opentelemetry/resources": "^1.10.1", + "@opentelemetry/semantic-conventions": "^1.0.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/detectors/node/opentelemetry-resource-detector-azure#readme" +} diff --git a/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureAppServiceDetector.ts b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureAppServiceDetector.ts new file mode 100644 index 0000000000..8fe785fa82 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureAppServiceDetector.ts @@ -0,0 +1,104 @@ +/* + * 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 { DetectorSync, IResource, Resource } from '@opentelemetry/resources'; +import { + AZURE_APP_SERVICE_STAMP_RESOURCE_ATTRIBUTE, + REGION_NAME, + WEBSITE_HOME_STAMPNAME, + WEBSITE_HOSTNAME, + WEBSITE_INSTANCE_ID, + WEBSITE_OWNER_NAME, + WEBSITE_RESOURCE_GROUP, + WEBSITE_SITE_NAME, + WEBSITE_SLOT_NAME, + CLOUD_RESOURCE_ID_RESOURCE_ATTRIBUTE, +} from '../types'; +import { + CloudProviderValues, + CloudPlatformValues, + SemanticResourceAttributes, +} from '@opentelemetry/semantic-conventions'; + +const APP_SERVICE_ATTRIBUTE_ENV_VARS = { + [SemanticResourceAttributes.CLOUD_REGION]: REGION_NAME, + [SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]: WEBSITE_SLOT_NAME, + [SemanticResourceAttributes.HOST_ID]: WEBSITE_HOSTNAME, + [SemanticResourceAttributes.SERVICE_INSTANCE_ID]: WEBSITE_INSTANCE_ID, + [AZURE_APP_SERVICE_STAMP_RESOURCE_ATTRIBUTE]: WEBSITE_HOME_STAMPNAME, +}; + +/** + * The AzureAppServiceDetector can be used to detect if a process is running in an Azure App Service + * @returns a {@link Resource} populated with data about the environment or an empty Resource if detection fails. + */ +class AzureAppServiceDetector implements DetectorSync { + detect(): IResource { + let attributes = {}; + const websiteSiteName = process.env[WEBSITE_SITE_NAME]; + if (websiteSiteName) { + attributes = { + ...attributes, + [SemanticResourceAttributes.SERVICE_NAME]: websiteSiteName, + }; + attributes = { + ...attributes, + [SemanticResourceAttributes.CLOUD_PROVIDER]: CloudProviderValues.AZURE, + }; + attributes = { + ...attributes, + [SemanticResourceAttributes.CLOUD_PLATFORM]: + CloudPlatformValues.AZURE_APP_SERVICE, + }; + + const azureResourceUri = this.getAzureResourceUri(websiteSiteName); + if (azureResourceUri) { + attributes = { + ...attributes, + ...{ [CLOUD_RESOURCE_ID_RESOURCE_ATTRIBUTE]: azureResourceUri }, + }; + } + + for (const [key, value] of Object.entries( + APP_SERVICE_ATTRIBUTE_ENV_VARS + )) { + const envVar = process.env[value]; + if (envVar) { + attributes = { ...attributes, ...{ [key]: envVar } }; + } + } + } + return new Resource(attributes); + } + + private getAzureResourceUri(websiteSiteName: string): string | undefined { + const websiteResourceGroup = process.env[WEBSITE_RESOURCE_GROUP]; + const websiteOwnerName = process.env[WEBSITE_OWNER_NAME]; + + let subscriptionId = websiteOwnerName; + if (websiteOwnerName && websiteOwnerName.indexOf('+') !== -1) { + subscriptionId = websiteOwnerName.split('+')[0]; + } + + if (!subscriptionId && !websiteOwnerName) { + return undefined; + } + + return `/subscriptions/${subscriptionId}/resourceGroups/${websiteResourceGroup}/providers/Microsoft.Web/sites/${websiteSiteName}`; + } +} + +export const azureAppServiceDetector = new AzureAppServiceDetector(); diff --git a/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureFunctionsDetector.ts b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureFunctionsDetector.ts new file mode 100644 index 0000000000..8cd601edb3 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureFunctionsDetector.ts @@ -0,0 +1,97 @@ +/* + * 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 { DetectorSync, IResource, Resource } from '@opentelemetry/resources'; + +import { + CloudProviderValues, + CloudPlatformValues, + SemanticResourceAttributes, +} from '@opentelemetry/semantic-conventions'; +import { + WEBSITE_SITE_NAME, + FUNCTIONS_VERSION, + WEBSITE_INSTANCE_ID, + FUNCTIONS_MEM_LIMIT, + REGION_NAME, +} from '../types'; + +const AZURE_FUNCTIONS_ATTRIBUTE_ENV_VARS = { + [SemanticResourceAttributes.FAAS_NAME]: WEBSITE_SITE_NAME, + [SemanticResourceAttributes.FAAS_VERSION]: FUNCTIONS_VERSION, + [SemanticResourceAttributes.FAAS_INSTANCE]: WEBSITE_INSTANCE_ID, + [SemanticResourceAttributes.FAAS_MAX_MEMORY]: FUNCTIONS_MEM_LIMIT, +}; + +/** + * The AzureFunctionsDetector can be used to detect if a process is running in Azure Functions + * @returns a {@link Resource} populated with data about the environment or an empty Resource if detection fails. + */ +class AzureFunctionsDetector implements DetectorSync { + detect(): IResource { + let attributes = {}; + const functionName = process.env[WEBSITE_SITE_NAME]; + if (functionName) { + const functionVersion = process.env[FUNCTIONS_VERSION]; + const functionInstance = process.env[WEBSITE_INSTANCE_ID]; + const functionMemLimit = process.env[FUNCTIONS_MEM_LIMIT]; + + attributes = { + [SemanticResourceAttributes.CLOUD_PROVIDER]: CloudProviderValues.AZURE, + [SemanticResourceAttributes.CLOUD_PLATFORM]: + CloudPlatformValues.AZURE_FUNCTIONS, + [SemanticResourceAttributes.CLOUD_REGION]: process.env[REGION_NAME], + }; + + if (functionName) { + attributes = { + ...attributes, + [SemanticResourceAttributes.FAAS_NAME]: functionName, + }; + } + if (functionVersion) { + attributes = { + ...attributes, + [SemanticResourceAttributes.FAAS_VERSION]: functionVersion, + }; + } + if (functionInstance) { + attributes = { + ...attributes, + [SemanticResourceAttributes.FAAS_INSTANCE]: functionInstance, + }; + } + if (functionMemLimit) { + attributes = { + ...attributes, + [SemanticResourceAttributes.FAAS_MAX_MEMORY]: functionMemLimit, + }; + } + + for (const [key, value] of Object.entries( + AZURE_FUNCTIONS_ATTRIBUTE_ENV_VARS + )) { + const envVar = process.env[value]; + if (envVar) { + attributes = { ...attributes, ...{ [key]: envVar } }; + } + } + } + return new Resource(attributes); + } +} + +export const azureFunctionsDetector = new AzureFunctionsDetector(); diff --git a/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts new file mode 100644 index 0000000000..9de9bc330b --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts @@ -0,0 +1,106 @@ +/* + * 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 http from 'http'; +import { + DetectorSync, + IResource, + Resource, + ResourceAttributes, +} from '@opentelemetry/resources'; +import { + CloudPlatformValues, + CloudProviderValues, + SemanticResourceAttributes, +} from '@opentelemetry/semantic-conventions'; +import { + CLOUD_RESOURCE_ID_RESOURCE_ATTRIBUTE, + AZURE_VM_METADATA_HOST, + AZURE_VM_METADATA_PATH, + AZURE_VM_SCALE_SET_NAME_ATTRIBUTE, + AZURE_VM_SKU_ATTRIBUTE, + AzureVmMetadata, +} from '../types'; + +/** + * The AzureVmDetector can be used to detect if a process is running in an Azure VM. + * @returns a {@link Resource} populated with data about the environment or an empty Resource if detection fails. + */ +class AzureVmResourceDetector implements DetectorSync { + detect(): IResource { + return new Resource({}, this.getAzureVmMetadata()); + } + + async getAzureVmMetadata(): Promise { + const options = { + host: AZURE_VM_METADATA_HOST, + path: AZURE_VM_METADATA_PATH, + method: 'GET', + timeout: 5000, + headers: { + Metadata: 'True', + }, + }; + const metadata: AzureVmMetadata = await new Promise((resolve, reject) => { + const timeoutId = setTimeout(() => { + req.destroy(); + reject(new Error('Azure metadata service request timed out.')); + }, 1000); + + const req = http.request(options, res => { + clearTimeout(timeoutId); + const { statusCode } = res; + res.setEncoding('utf8'); + let rawData = ''; + res.on('data', chunk => (rawData += chunk)); + res.on('end', () => { + if (statusCode && statusCode >= 200 && statusCode < 300) { + try { + resolve(JSON.parse(rawData)); + } catch (error) { + reject(error); + } + } else { + reject( + new Error('Failed to load page, status code: ' + statusCode) + ); + } + }); + }); + req.on('error', err => { + clearTimeout(timeoutId); + reject(err); + }); + req.end(); + }); + + const attributes = { + [AZURE_VM_SCALE_SET_NAME_ATTRIBUTE]: metadata['vmScaleSetName'], + [AZURE_VM_SKU_ATTRIBUTE]: metadata['sku'], + [SemanticResourceAttributes.CLOUD_PLATFORM]: CloudPlatformValues.AZURE_VM, + [SemanticResourceAttributes.CLOUD_PROVIDER]: CloudProviderValues.AZURE, + [SemanticResourceAttributes.CLOUD_REGION]: metadata['location'], + [CLOUD_RESOURCE_ID_RESOURCE_ATTRIBUTE]: metadata['resourceId'], + [SemanticResourceAttributes.HOST_ID]: metadata['vmId'], + [SemanticResourceAttributes.HOST_NAME]: metadata['name'], + [SemanticResourceAttributes.HOST_TYPE]: metadata['vmSize'], + [SemanticResourceAttributes.OS_VERSION]: metadata['version'], + }; + return attributes; + } +} + +export const azureVmDetector = new AzureVmResourceDetector(); diff --git a/detectors/node/opentelemetry-resource-detector-azure/src/detectors/index.ts b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/index.ts new file mode 100644 index 0000000000..be8f84fa2c --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/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 './AzureAppServiceDetector'; diff --git a/detectors/node/opentelemetry-resource-detector-azure/src/index.ts b/detectors/node/opentelemetry-resource-detector-azure/src/index.ts new file mode 100644 index 0000000000..0acba8788c --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/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/detectors/node/opentelemetry-resource-detector-azure/src/types.ts b/detectors/node/opentelemetry-resource-detector-azure/src/types.ts new file mode 100644 index 0000000000..645b4b7073 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/src/types.ts @@ -0,0 +1,182 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const AZURE_APP_SERVICE_STAMP_RESOURCE_ATTRIBUTE = + 'azure.app.service.stamp'; +export const CLOUD_RESOURCE_ID_RESOURCE_ATTRIBUTE = 'cloud.resource_id'; +export const REGION_NAME = 'REGION_NAME'; +export const WEBSITE_HOME_STAMPNAME = 'WEBSITE_HOME_STAMPNAME'; +export const WEBSITE_HOSTNAME = 'WEBSITE_HOSTNAME'; +export const WEBSITE_INSTANCE_ID = 'WEBSITE_INSTANCE_ID'; +export const WEBSITE_OWNER_NAME = 'WEBSITE_OWNER_NAME'; +export const WEBSITE_RESOURCE_GROUP = 'WEBSITE_RESOURCE_GROUP'; +export const WEBSITE_SITE_NAME = 'WEBSITE_SITE_NAME'; +export const WEBSITE_SLOT_NAME = 'WEBSITE_SLOT_NAME'; + +export const FUNCTIONS_VERSION = 'FUNCTIONS_EXTENSION_VERSION'; +export const FUNCTIONS_MEM_LIMIT = 'WEBSITE_MEMORY_LIMIT_MB'; + +export const AZURE_VM_METADATA_HOST = '169.254.169.254'; +export const AZURE_VM_METADATA_PATH = + '/metadata/instance/compute?api-version=2021-12-13&format=json'; +export const AZURE_VM_SCALE_SET_NAME_ATTRIBUTE = 'azure.vm.scaleset.name'; +export const AZURE_VM_SKU_ATTRIBUTE = 'azure.vm.sku'; + +export interface AzureVmMetadata { + azEnvironment?: string; + additionalCapabilities?: { + hibernationEnabled?: string; + }; + hostGroup?: { + id?: string; + }; + host?: { + id?: string; + }; + extendedLocation?: { + type?: string; + name?: string; + }; + evictionPolicy?: string; + isHostCompatibilityLayerVm?: string; + licenseType?: string; + location: string; + name: string; + offer?: string; + osProfile?: { + adminUsername?: string; + computerName?: string; + disablePasswordAuthentication?: string; + }; + osType?: string; + placementGroupId?: string; + plan?: { + name?: string; + product?: string; + publisher?: string; + }; + platformFaultDomain?: string; + platformSubFaultDomain?: string; + platformUpdateDomain?: string; + priority?: string; + provider?: string; + publicKeys?: [ + { + keyData?: string; + path?: string; + }, + { + keyData?: string; + path?: string; + } + ]; + publisher?: string; + resourceGroupName?: string; + resourceId: string; + securityProfile?: { + secureBootEnabled?: string; + virtualTpmEnabled?: string; + encryptionAtHost?: string; + securityType?: string; + }; + sku: string; + storageProfile?: { + dataDisks?: [ + { + bytesPerSecondThrottle?: string; + caching?: string; + createOption?: string; + diskCapacityBytes?: string; + diskSizeGB?: string; + image?: { + uri?: string; + }; + isSharedDisk?: string; + isUltraDisk?: string; + lun?: string; + managedDisk?: { + id?: string; + storageAccountType?: string; + }; + name: string; + opsPerSecondThrottle?: string; + vhd?: { + uri?: string; + }; + writeAcceleratorEnabled?: string; + } + ]; + imageReference?: { + id?: string; + offer?: string; + publisher?: string; + sku?: string; + version?: string; + }; + osDisk?: { + caching?: string; + createOption?: string; + diskSizeGB?: string; + diffDiskSettings?: { + option?: string; + }; + encryptionSettings?: { + enabled?: string; + diskEncryptionKey?: { + sourceVault?: { + id?: string; + }; + secretUrl?: string; + }; + keyEncryptionKey?: { + sourceVault?: { + id?: string; + }; + keyUrl?: string; + }; + }; + image?: { + uri?: string; + }; + managedDisk?: { + id?: string; + storageAccountType?: string; + }; + name?: string; + osType?: string; + vhd?: { + uri?: string; + }; + writeAcceleratorEnabled?: string; + }; + resourceDisk?: { + size?: string; + }; + }; + subscriptionId?: string; + tags?: string; + tagsList?: object[]; + customData?: string; + userData?: string; + version: string; + virtualMachineScaleSet?: { + id?: string; + }; + vmId: string; + vmScaleSetName: string; + vmSize: string; + zone?: string; +} diff --git a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts new file mode 100644 index 0000000000..9c74ecf7d4 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts @@ -0,0 +1,151 @@ +/* + * 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 assert from 'assert'; +import { azureAppServiceDetector } from '../../src/detectors/AzureAppServiceDetector'; +import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'; + +describe('AzureAppServiceDetector', () => { + let originalEnv: NodeJS.ProcessEnv; + beforeEach(() => { + originalEnv = process.env; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + it('should test on appService', () => { + process.env.WEBSITE_SITE_NAME = 'test-site'; + process.env.REGION_NAME = 'test-region'; + process.env.WEBSITE_SLOT_NAME = 'test-slot'; + process.env.WEBSITE_HOSTNAME = 'test-hostname'; + process.env.WEBSITE_INSTANCE_ID = 'test-instance-id'; + process.env.WEBSITE_HOME_STAMPNAME = 'test-home-stamp'; + process.env.WEBSITE_RESOURCE_GROUP = 'test-resource-group'; + process.env.WEBSITE_OWNER_NAME = 'test-owner-name'; + + const resource = azureAppServiceDetector.detect(); + assert.ok(resource); + const attributes = resource.attributes; + assert.strictEqual( + attributes[SemanticResourceAttributes.SERVICE_NAME], + 'test-site' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_PROVIDER], + 'azure' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_PLATFORM], + 'azure_app_service' + ); + assert.strictEqual( + attributes['cloud.resource_id'], + `/subscriptions/${process.env.WEBSITE_OWNER_NAME}/resourceGroups/${process.env.WEBSITE_RESOURCE_GROUP}/providers/Microsoft.Web/sites/${process.env.WEBSITE_SITE_NAME}` + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_REGION], + 'test-region' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT], + 'test-slot' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.HOST_ID], + 'test-hostname' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.SERVICE_INSTANCE_ID], + 'test-instance-id' + ); + assert.strictEqual( + attributes['azure.app.service.stamp'], + 'test-home-stamp' + ); + }); + + it('should test with no resource group', () => { + process.env.WEBSITE_SITE_NAME = 'test-site'; + process.env.REGION_NAME = 'test-region'; + process.env.WEBSITE_SLOT_NAME = 'test-slot'; + process.env.WEBSITE_HOSTNAME = 'test-hostname'; + process.env.WEBSITE_INSTANCE_ID = 'test-instance-id'; + process.env.WEBSITE_HOME_STAMPNAME = 'test-home-stamp'; + process.env.WEBSITE_OWNER_NAME = 'test-owner-name'; + + const resource = azureAppServiceDetector.detect(); + assert.ok(resource); + const attributes = resource.attributes; + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_REGION], + 'test-region' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT], + 'test-slot' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.HOST_ID], + 'test-hostname' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.SERVICE_INSTANCE_ID], + 'test-instance-id' + ); + assert.strictEqual( + attributes['azure.app.service.stamp'], + 'test-home-stamp' + ); + }); + + it('should test with no owner name', () => { + process.env.WEBSITE_SITE_NAME = 'test-site'; + process.env.REGION_NAME = 'test-region'; + process.env.WEBSITE_SLOT_NAME = 'test-slot'; + process.env.WEBSITE_HOSTNAME = 'test-hostname'; + process.env.WEBSITE_INSTANCE_ID = 'test-instance-id'; + process.env.WEBSITE_HOME_STAMPNAME = 'test-home-stamp'; + process.env.WEBSITE_RESOURCE_GROUP = 'test-resource-group'; + delete process.env.WEBSITE_OWNER_NAME; + + const resource = azureAppServiceDetector.detect(); + assert.ok(resource); + const attributes = resource.attributes; + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_REGION], + 'test-region' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT], + 'test-slot' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.HOST_ID], + 'test-hostname' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.SERVICE_INSTANCE_ID], + 'test-instance-id' + ); + assert.strictEqual( + attributes['azure.app.service.stamp'], + 'test-home-stamp' + ); + assert.strictEqual(attributes['cloud.resource_id'], undefined); + }); +}); diff --git a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts new file mode 100644 index 0000000000..9e14426090 --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts @@ -0,0 +1,70 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as assert from 'assert'; +import { azureFunctionsDetector } from '../../src/detectors/AzureFunctionsDetector'; +import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'; + +describe('AzureFunctionsDetector', () => { + let originalEnv: NodeJS.ProcessEnv; + beforeEach(() => { + originalEnv = process.env; + }); + + afterEach(() => { + process.env = originalEnv; + }); + + it('should test functions values', () => { + process.env.WEBSITE_SITE_NAME = 'test-function'; + process.env.REGION_NAME = 'test-region'; + process.env.WEBSITE_INSTANCE_ID = 'test-instance-id'; + process.env.FUNCTIONS_EXTENSION_VERSION = '~4'; + process.env.WEBSITE_MEMORY_LIMIT_MB = '1000'; + + const resource = azureFunctionsDetector.detect(); + assert.ok(resource); + const attributes = resource.attributes; + assert.strictEqual( + attributes[SemanticResourceAttributes.FAAS_NAME], + 'test-function' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_PROVIDER], + 'azure' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_PLATFORM], + 'azure_functions' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.CLOUD_REGION], + 'test-region' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.FAAS_INSTANCE], + 'test-instance-id' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.FAAS_MAX_MEMORY], + '1000' + ); + assert.strictEqual( + attributes[SemanticResourceAttributes.FAAS_VERSION], + '~4' + ); + }); +}); diff --git a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts new file mode 100644 index 0000000000..a795adb27f --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts @@ -0,0 +1,418 @@ +/* + * 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 assert from 'assert'; +import * as nock from 'nock'; +import { azureVmDetector } from '../../src/detectors/AzureVmDetector'; +import { IResource } from '@opentelemetry/resources'; +import { AzureVmMetadata } from '../../src/types'; + +const linuxTestResponse: AzureVmMetadata = { + additionalCapabilities: { + hibernationEnabled: 'false', + }, + azEnvironment: 'AzurePublicCloud', + customData: '', + evictionPolicy: '', + extendedLocation: { + name: '', + type: '', + }, + host: { + id: '', + }, + hostGroup: { + id: '', + }, + isHostCompatibilityLayerVm: 'true', + licenseType: '', + location: 'westus', + name: 'examplevmname', + offer: '0001-com-ubuntu-server-focal', + osProfile: { + adminUsername: 'azureuser', + computerName: 'examplevmname', + disablePasswordAuthentication: 'true', + }, + osType: 'Linux', + placementGroupId: '', + plan: { + name: '', + product: '', + publisher: '', + }, + platformFaultDomain: '0', + platformSubFaultDomain: '', + platformUpdateDomain: '0', + priority: '', + provider: 'Microsoft.Compute', + publicKeys: [ + { + keyData: 'ssh-rsa 0', + path: '/home/user/.ssh/authorized_keys0', + }, + { + keyData: 'ssh-rsa 1', + path: '/home/user/.ssh/authorized_keys1', + }, + ], + publisher: 'canonical', + resourceGroupName: 'macikgo-test-may-23', + resourceId: + '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname', + securityProfile: { + encryptionAtHost: 'false', + secureBootEnabled: 'true', + securityType: 'TrustedLaunch', + virtualTpmEnabled: 'true', + }, + sku: '20_04-lts-gen2', + storageProfile: { + dataDisks: [ + { + bytesPerSecondThrottle: '979202048', + caching: 'None', + createOption: 'Empty', + diskCapacityBytes: '274877906944', + diskSizeGB: '1024', + image: { + uri: '', + }, + isSharedDisk: 'false', + isUltraDisk: 'true', + lun: '0', + managedDisk: { + id: '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampledatadiskname', + storageAccountType: 'StandardSSD_LRS', + }, + name: 'exampledatadiskname', + opsPerSecondThrottle: '65280', + vhd: { + uri: '', + }, + writeAcceleratorEnabled: 'false', + }, + ], + imageReference: { + id: '', + offer: '0001-com-ubuntu-server-focal', + publisher: 'canonical', + sku: '20_04-lts-gen2', + version: 'latest', + }, + osDisk: { + caching: 'ReadWrite', + createOption: 'FromImage', + diffDiskSettings: { + option: '', + }, + diskSizeGB: '30', + encryptionSettings: { + enabled: 'false', + diskEncryptionKey: { + sourceVault: { + id: '/subscriptions/test-source-guid/resourceGroups/testrg/providers/Microsoft.KeyVault/vaults/test-kv', + }, + secretUrl: + 'https://test-disk.vault.azure.net/secrets/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx', + }, + keyEncryptionKey: { + sourceVault: { + id: '/subscriptions/test-key-guid/resourceGroups/testrg/providers/Microsoft.KeyVault/vaults/test-kv', + }, + keyUrl: + 'https://test-key.vault.azure.net/secrets/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx', + }, + }, + image: { + uri: '', + }, + managedDisk: { + id: '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampleosdiskname', + storageAccountType: 'StandardSSD_LRS', + }, + name: 'exampledatadiskname', + osType: 'Linux', + vhd: { + uri: '', + }, + writeAcceleratorEnabled: 'false', + }, + resourceDisk: { + size: '16384', + }, + }, + subscriptionId: 'xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx', + tags: 'azsecpack:nonprod;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true', + tagsList: [ + { + name: 'azsecpack', + value: 'nonprod', + }, + { + name: 'platformsettings.host_environment.service.platform_optedin_for_rootcerts', + value: 'true', + }, + ], + userData: '', + version: '20.04.202307240', + virtualMachineScaleSet: { + id: '/subscriptions/xxxxxxxx-xxxxx-xxx-xxx-xxxx/resourceGroups/resource-group-name/providers/Microsoft.Compute/virtualMachineScaleSets/virtual-machine-scale-set-name', + }, + vmId: '02aab8a4-74ef-476e-8182-f6d2ba4166a6', + vmScaleSetName: 'crpteste9vflji9', + vmSize: 'Standard_A3', + zone: '1', +}; + +const windowsTestResponse: AzureVmMetadata = { + additionalCapabilities: { + hibernationEnabled: 'false', + }, + azEnvironment: 'AzurePublicCloud', + customData: '', + evictionPolicy: '', + extendedLocation: { + name: '', + type: '', + }, + host: { + id: '', + }, + hostGroup: { + id: '', + }, + isHostCompatibilityLayerVm: 'true', + licenseType: 'Windows_Client', + location: 'westus', + name: 'examplevmname', + offer: 'WindowsServer', + osProfile: { + adminUsername: 'azureuser', + computerName: 'examplevmname', + disablePasswordAuthentication: 'true', + }, + osType: 'Windows', + placementGroupId: '', + plan: { + name: '', + product: '', + publisher: '', + }, + platformFaultDomain: '0', + platformSubFaultDomain: '', + platformUpdateDomain: '0', + priority: '', + provider: 'Microsoft.Compute', + publicKeys: [ + { + keyData: 'ssh-rsa 0', + path: '/home/user/.ssh/authorized_keys0', + }, + { + keyData: 'ssh-rsa 1', + path: '/home/user/.ssh/authorized_keys1', + }, + ], + publisher: 'RDFE-Test-Microsoft-Windows-Server-Group', + resourceGroupName: 'macikgo-test-may-23', + resourceId: + '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname', + securityProfile: { + encryptionAtHost: 'false', + secureBootEnabled: 'true', + securityType: 'TrustedLaunch', + virtualTpmEnabled: 'true', + }, + sku: '2019-Datacenter', + storageProfile: { + dataDisks: [ + { + bytesPerSecondThrottle: '979202048', + caching: 'None', + createOption: 'Empty', + diskCapacityBytes: '274877906944', + diskSizeGB: '1024', + image: { + uri: '', + }, + isSharedDisk: 'false', + isUltraDisk: 'true', + lun: '0', + managedDisk: { + id: '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampledatadiskname', + storageAccountType: 'StandardSSD_LRS', + }, + name: 'exampledatadiskname', + opsPerSecondThrottle: '65280', + vhd: { + uri: '', + }, + writeAcceleratorEnabled: 'false', + }, + ], + imageReference: { + id: '', + offer: 'WindowsServer', + publisher: 'MicrosoftWindowsServer', + sku: '2019-Datacenter', + version: 'latest', + }, + osDisk: { + caching: 'ReadWrite', + createOption: 'FromImage', + diffDiskSettings: { + option: '', + }, + diskSizeGB: '30', + encryptionSettings: { + enabled: 'false', + diskEncryptionKey: { + sourceVault: { + id: '/subscriptions/test-source-guid/resourceGroups/testrg/providers/Microsoft.KeyVault/vaults/test-kv', + }, + secretUrl: + 'https://test-disk.vault.azure.net/secrets/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx', + }, + keyEncryptionKey: { + sourceVault: { + id: '/subscriptions/test-key-guid/resourceGroups/testrg/providers/Microsoft.KeyVault/vaults/test-kv', + }, + keyUrl: + 'https://test-key.vault.azure.net/secrets/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx', + }, + }, + image: { + uri: '', + }, + managedDisk: { + id: '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampleosdiskname', + storageAccountType: 'StandardSSD_LRS', + }, + name: 'exampledatadiskname', + osType: 'Windows', + vhd: { + uri: '', + }, + writeAcceleratorEnabled: 'false', + }, + resourceDisk: { + size: '16384', + }, + }, + subscriptionId: 'xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx', + tags: 'azsecpack:nonprod;platformsettings.host_environment.service.platform_optedin_for_rootcerts:true', + userData: 'Zm9vYmFy', + tagsList: [ + { + name: 'azsecpack', + value: 'nonprod', + }, + { + name: 'platformsettings.host_environment.service.platform_optedin_for_rootcerts', + value: 'true', + }, + ], + version: '20.04.202307240', + virtualMachineScaleSet: { + id: '/subscriptions/xxxxxxxx-xxxxx-xxx-xxx-xxxx/resourceGroups/resource-group-name/providers/Microsoft.Compute/virtualMachineScaleSets/virtual-machine-scale-set-name', + }, + vmId: '02aab8a4-74ef-476e-8182-f6d2ba4166a6', + vmScaleSetName: 'crpteste9vflji9', + vmSize: 'Standard_A3', + zone: '1', +}; + +const linuxAttributes: any = { + 'azure.vm.scaleset.name': 'crpteste9vflji9', + 'azure.vm.sku': '20_04-lts-gen2', + 'cloud.platform': 'azure_vm', + 'cloud.provider': 'azure', + 'cloud.region': 'westus', + 'cloud.resource_id': + '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname', + 'host.id': '02aab8a4-74ef-476e-8182-f6d2ba4166a6', + 'host.name': 'examplevmname', + 'host.type': 'Standard_A3', + 'os.type': 'Linux', + 'os.version': '20.04.202307240', + 'service.instance.id': '02aab8a4-74ef-476e-8182-f6d2ba4166a6', +}; + +const windowsAttributes: any = { + 'azure.vm.scaleset.name': 'crpteste9vflji9', + 'azure.vm.sku': '2019-Datacenter', + 'cloud.platform': 'azure_vm', + 'cloud.provider': 'azure', + 'cloud.region': 'westus', + 'cloud.resource_id': + '/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname', + 'host.id': '02aab8a4-74ef-476e-8182-f6d2ba4166a6', + 'host.name': 'examplevmname', + 'host.type': 'Standard_A3', + 'os.type': 'Windows', + 'os.version': '20.04.202307240', + 'service.instance.id': '02aab8a4-74ef-476e-8182-f6d2ba4166a6', +}; + +const AZURE_VM_METADATA_HOST = 'http://169.254.169.254'; +const AZURE_VM_METADATA_PATH = + '/metadata/instance/compute?api-version=2021-12-13&format=json'; + +describe('AzureAppServiceDetector', () => { + beforeEach(() => { + nock.disableNetConnect(); + nock.cleanAll(); + }); + + afterEach(() => { + nock.enableNetConnect(); + }); + + it('should get linux virtual machine attributes', async () => { + const scope = nock(AZURE_VM_METADATA_HOST) + .get(AZURE_VM_METADATA_PATH) + .reply(200, linuxTestResponse); + + const resource: IResource = azureVmDetector.detect(); + if (resource.waitForAsyncAttributes) { + await resource.waitForAsyncAttributes(); + } + const attributes = resource.attributes; + for (let i = 0; i < Object.keys(attributes).length; i++) { + const key = Object.keys(attributes)[i]; + assert.strictEqual(attributes[key], linuxAttributes[key]); + } + scope.done(); + }); + + it('should get windows virtual machine attributes', async () => { + const scope = nock(AZURE_VM_METADATA_HOST) + .get(AZURE_VM_METADATA_PATH) + .reply(200, windowsTestResponse); + + const resource: IResource = azureVmDetector.detect(); + if (resource.waitForAsyncAttributes) { + await resource.waitForAsyncAttributes(); + } + const attributes = resource.attributes; + for (let i = 0; i < Object.keys(attributes).length; i++) { + const key = Object.keys(attributes)[i]; + assert.strictEqual(attributes[key], windowsAttributes[key]); + } + scope.done(); + }); +}); diff --git a/detectors/node/opentelemetry-resource-detector-azure/tsconfig.json b/detectors/node/opentelemetry-resource-detector-azure/tsconfig.json new file mode 100644 index 0000000000..3f6ea3378e --- /dev/null +++ b/detectors/node/opentelemetry-resource-detector-azure/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} diff --git a/release-please-config.json b/release-please-config.json index be9ea170ab..e55af5702e 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -8,6 +8,7 @@ "packages": { "detectors/node/opentelemetry-resource-detector-alibaba-cloud": {}, "detectors/node/opentelemetry-resource-detector-aws": {}, + "detectors/node/opentelemetry-resource-detector-azure": {}, "detectors/node/opentelemetry-resource-detector-container": {}, "detectors/node/opentelemetry-resource-detector-gcp": {}, "detectors/node/opentelemetry-resource-detector-github": {},