From d4e7a0430356c3c5bc4b2c6e957cfc71773d312c Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Fri, 17 Jul 2026 11:31:04 -0400 Subject: [PATCH 1/8] add host id resource detector --- .changelog/0000.added | 1 + .github/workflows/core_contrib_test.yml | 30 +++ .github/workflows/lint.yml | 19 ++ .github/workflows/test.yml | 114 ++++++++++ docs/index.rst | 1 + docs/resource/host/host.rst | 7 + .../LICENSE | 201 ++++++++++++++++++ .../MANIFEST.rst | 9 + .../README.rst | 67 ++++++ .../pyproject.toml | 48 +++++ .../resource/detector/host/__init__.py | 149 +++++++++++++ .../resource/detector/host/version.py | 4 + .../test-requirements.txt | 12 ++ .../tests/__init__.py | 0 .../tests/test_host.py | 172 +++++++++++++++ tox.ini | 11 + 16 files changed, 845 insertions(+) create mode 100644 .changelog/0000.added create mode 100644 docs/resource/host/host.rst create mode 100644 resource/opentelemetry-resource-detector-host/LICENSE create mode 100644 resource/opentelemetry-resource-detector-host/MANIFEST.rst create mode 100644 resource/opentelemetry-resource-detector-host/README.rst create mode 100644 resource/opentelemetry-resource-detector-host/pyproject.toml create mode 100644 resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py create mode 100644 resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/version.py create mode 100644 resource/opentelemetry-resource-detector-host/test-requirements.txt create mode 100644 resource/opentelemetry-resource-detector-host/tests/__init__.py create mode 100644 resource/opentelemetry-resource-detector-host/tests/test_host.py diff --git a/.changelog/0000.added b/.changelog/0000.added new file mode 100644 index 0000000000..8d50cef540 --- /dev/null +++ b/.changelog/0000.added @@ -0,0 +1 @@ +Add `opentelemetry-resource-detector-host` package that sets `host.id` from the non-privileged machine id diff --git a/.github/workflows/core_contrib_test.yml b/.github/workflows/core_contrib_test.yml index be80dd5e94..d7a9a9059a 100644 --- a/.github/workflows/core_contrib_test.yml +++ b/.github/workflows/core_contrib_test.yml @@ -417,6 +417,36 @@ jobs: - name: Run tests run: tox -e py310-test-resource-detector-containerid -- -ra + py310-test-resource-detector-host: + name: resource-detector-host + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout contrib repo @ SHA - ${{ env.CONTRIB_REPO_SHA }} + uses: actions/checkout@v4 + with: + repository: open-telemetry/opentelemetry-python-contrib + ref: ${{ env.CONTRIB_REPO_SHA }} + + - name: Checkout core repo @ SHA - ${{ env.CORE_REPO_SHA }} + uses: actions/checkout@v4 + with: + repository: open-telemetry/opentelemetry-python + ref: ${{ env.CORE_REPO_SHA }} + path: opentelemetry-python + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10" + architecture: "x64" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py310-test-resource-detector-host -- -ra + py310-test-resource-detector-azure-0: name: resource-detector-azure-0 runs-on: ubuntu-latest diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index a6437462bc..2a38347993 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -157,6 +157,25 @@ jobs: - name: Run tests run: tox -e lint-resource-detector-containerid + lint-resource-detector-host: + name: resource-detector-host + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.14 + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e lint-resource-detector-host + lint-resource-detector-azure: name: resource-detector-azure runs-on: ubuntu-latest diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f27399a863..aae2568be7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1278,6 +1278,120 @@ jobs: - name: Run tests run: tox -e pypy3-test-resource-detector-containerid -- -ra + py310-test-resource-detector-host_ubuntu-latest: + name: resource-detector-host 3.10 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py310-test-resource-detector-host -- -ra + + py311-test-resource-detector-host_ubuntu-latest: + name: resource-detector-host 3.11 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py311-test-resource-detector-host -- -ra + + py312-test-resource-detector-host_ubuntu-latest: + name: resource-detector-host 3.12 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py312-test-resource-detector-host -- -ra + + py313-test-resource-detector-host_ubuntu-latest: + name: resource-detector-host 3.13 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py313-test-resource-detector-host -- -ra + + py314-test-resource-detector-host_ubuntu-latest: + name: resource-detector-host 3.14 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.14 + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py314-test-resource-detector-host -- -ra + + pypy3-test-resource-detector-host_ubuntu-latest: + name: resource-detector-host pypy-3.10 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python pypy-3.10 + uses: actions/setup-python@v5 + with: + python-version: "pypy-3.10" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e pypy3-test-resource-detector-host -- -ra + py310-test-resource-detector-azure-0_ubuntu-latest: name: resource-detector-azure-0 3.10 Ubuntu runs-on: ubuntu-latest diff --git a/docs/index.rst b/docs/index.rst index 1ac7f8179c..7cefc994cb 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -53,6 +53,7 @@ install pip install -e ./instrumentation-genai/opentelemetry-instrumentation-openai-v2 pip install -e ./sdk-extension/opentelemetry-sdk-extension-aws pip install -e ./resource/opentelemetry-resource-detector-containerid + pip install -e ./resource/opentelemetry-resource-detector-host .. toctree:: diff --git a/docs/resource/host/host.rst b/docs/resource/host/host.rst new file mode 100644 index 0000000000..029905417f --- /dev/null +++ b/docs/resource/host/host.rst @@ -0,0 +1,7 @@ +OpenTelemetry Python - Host ID Resource Detector +================================================ + +.. automodule:: opentelemetry.resource.detector.host + :members: + :undoc-members: + :show-inheritance: diff --git a/resource/opentelemetry-resource-detector-host/LICENSE b/resource/opentelemetry-resource-detector-host/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/resource/opentelemetry-resource-detector-host/MANIFEST.rst b/resource/opentelemetry-resource-detector-host/MANIFEST.rst new file mode 100644 index 0000000000..aed3e33273 --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/MANIFEST.rst @@ -0,0 +1,9 @@ +graft src +graft tests +global-exclude *.pyc +global-exclude *.pyo +global-exclude __pycache__/* +include CHANGELOG.md +include MANIFEST.in +include README.rst +include LICENSE diff --git a/resource/opentelemetry-resource-detector-host/README.rst b/resource/opentelemetry-resource-detector-host/README.rst new file mode 100644 index 0000000000..2e9f828aed --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/README.rst @@ -0,0 +1,67 @@ +OpenTelemetry Host ID Resource Detector +======================================= + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-resource-detector-host.svg + :target: https://pypi.org/project/opentelemetry-resource-detector-host/ + +This library provides a custom `Resource Detector `_ +that sets the ``host.id`` resource attribute for a physical or virtual host, following the +`Host Resource Semantic Conventions `_. + +The value is read from the non-privileged machine-id sources defined by the specification. It +complements the built-in host resource detector from the OpenTelemetry SDK, which only sets +``host.name`` and ``host.arch``. + +Installation +------------ + +:: + + pip install opentelemetry-resource-detector-host + +--------------------------- + +Usage example for ``opentelemetry-resource-detector-host`` + +.. code-block:: python + + from opentelemetry import trace + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.resource.detector.host import ( + HostIdResourceDetector, + ) + from opentelemetry.sdk.resources import get_aggregated_resources + + + trace.set_tracer_provider( + TracerProvider( + resource=get_aggregated_resources( + [ + HostIdResourceDetector(), + ] + ), + ) + ) + +Mappings +-------- + +The Host ID Resource Detector sets the ``host.id`` Resource Attribute from the following +non-privileged sources, depending on the operating system: + + * **Linux**: the contents of ``/etc/machine-id``, falling back to ``/var/lib/dbus/machine-id``. + * **macOS**: the ``IOPlatformUUID`` value from ``ioreg -rd1 -c IOPlatformExpertDevice``. + * **Windows**: the ``MachineGuid`` value under the ``HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography`` registry key. + * **BSD**: the contents of ``/etc/hostid``, falling back to the output of ``kenv -q smbios.system.uuid``. + +If no value can be read, the detector returns an empty resource and ``host.id`` is left unset. In +that case, the value can be provided explicitly through the ``OTEL_RESOURCE_ATTRIBUTES`` environment +variable. + +References +---------- + +* `OpenTelemetry Project `_ +* `Host Resource Semantic Conventions `_ diff --git a/resource/opentelemetry-resource-detector-host/pyproject.toml b/resource/opentelemetry-resource-detector-host/pyproject.toml new file mode 100644 index 0000000000..48c0d084b8 --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/pyproject.toml @@ -0,0 +1,48 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "opentelemetry-resource-detector-host" +dynamic = ["version"] +description = "Host ID Resource Detector for OpenTelemetry" +readme = "README.rst" +license = "Apache-2.0" +requires-python = ">=3.10" +authors = [ + { name = "OpenTelemetry Authors", email = "cncf-opentelemetry-contributors@lists.cncf.io" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +dependencies = [ + "opentelemetry-sdk ~= 1.12", +] + +[project.entry-points.opentelemetry_resource_detector] +host_id = "opentelemetry.resource.detector.host:HostIdResourceDetector" + +[project.urls] +Homepage = "https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/resource/opentelemetry-resource-detector-host" +Repository = "https://github.com/open-telemetry/opentelemetry-python-contrib" + +[tool.hatch.version] +path = "src/opentelemetry/resource/detector/host/version.py" + +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", +] + +[tool.hatch.build.targets.wheel] +packages = ["src/opentelemetry"] diff --git a/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py new file mode 100644 index 0000000000..76bc733116 --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py @@ -0,0 +1,149 @@ +# Copyright The OpenTelemetry Authors +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import platform +import subprocess +from logging import getLogger + +from opentelemetry.sdk.resources import Resource, ResourceDetector +from opentelemetry.semconv.resource import ResourceAttributes + +logger = getLogger(__name__) + +# Non-privileged machine-id sources per the semantic conventions: +# https://opentelemetry.io/docs/specs/semconv/resource/host/#non-privileged-machine-id-lookup +_LINUX_MACHINE_ID_PATHS = ("/etc/machine-id", "/var/lib/dbus/machine-id") +_BSD_HOSTID_PATH = "/etc/hostid" +_BSD_KENV_COMMAND = ("kenv", "-q", "smbios.system.uuid") +_MACOS_IOREG_COMMAND = ("ioreg", "-rd1", "-c", "IOPlatformExpertDevice") +_WINDOWS_REGISTRY_COMMAND = ( + "reg", + "query", + r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography", + "/v", + "MachineGuid", +) +_COMMAND_TIMEOUT_SECONDS = 5 + + +def _read_first_line(path: str) -> str | None: + try: + with open(path, encoding="utf8") as machine_id_file: + for raw_line in machine_id_file: + line = raw_line.strip() + if line: + return line + except OSError as exception: + logger.debug("Failed to read %s: %s", path, exception) + return None + + +def _run_command(command: tuple[str, ...]) -> str | None: + try: + completed = subprocess.run( + command, + capture_output=True, + text=True, + timeout=_COMMAND_TIMEOUT_SECONDS, + check=False, + ) + except (OSError, subprocess.SubprocessError) as exception: + logger.debug("Failed to run %s: %s", command[0], exception) + return None + if completed.returncode != 0: + logger.debug( + "Command %s exited with code %s", command[0], completed.returncode + ) + return None + return completed.stdout + + +def _get_linux_machine_id() -> str | None: + for path in _LINUX_MACHINE_ID_PATHS: + machine_id = _read_first_line(path) + if machine_id: + return machine_id + return None + + +def _get_bsd_machine_id() -> str | None: + machine_id = _read_first_line(_BSD_HOSTID_PATH) + if machine_id: + return machine_id + output = _run_command(_BSD_KENV_COMMAND) + if output: + machine_id = output.strip() + if machine_id: + return machine_id + return None + + +def _get_macos_machine_id() -> str | None: + output = _run_command(_MACOS_IOREG_COMMAND) + if not output: + return None + for line in output.splitlines(): + if "IOPlatformUUID" in line: + # Line looks like: ` "IOPlatformUUID" = "AAAAAAAA-BBBB-..."` + _, _, value = line.partition("=") + machine_id = value.strip().strip('"').strip() + if machine_id: + return machine_id + return None + + +def _get_windows_machine_id() -> str | None: + output = _run_command(_WINDOWS_REGISTRY_COMMAND) + if not output: + return None + for line in output.splitlines(): + if "MachineGuid" in line: + # Line looks like: ` MachineGuid REG_SZ ` + parts = line.split() + if len(parts) == 3: + return parts[2] + return None + + +def _get_host_id() -> str | None: + system = platform.system() + if system == "Linux": + return _get_linux_machine_id() + if system == "Darwin": + return _get_macos_machine_id() + if system == "Windows": + return _get_windows_machine_id() + if system == "DragonFly" or system.endswith("BSD"): + return _get_bsd_machine_id() + logger.debug("Unsupported OS type for host.id detection: %s", system) + return None + + +class HostIdResourceDetector(ResourceDetector): + """Detects the ``host.id`` resource attribute from the machine id of the + host, using only the non-privileged sources described in the OpenTelemetry + semantic conventions. + """ + + def detect(self) -> Resource: + try: + host_id = _get_host_id() + resource = Resource.get_empty() + if host_id: + resource = resource.merge( + Resource({ResourceAttributes.HOST_ID: host_id}) + ) + return resource + + # pylint: disable=broad-except + except Exception as exception: + logger.warning( + "%s Resource Detection failed silently: %s", + self.__class__.__name__, + exception, + ) + if self.raise_on_error: + raise exception + return Resource.get_empty() diff --git a/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/version.py b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/version.py new file mode 100644 index 0000000000..e49b1ceb43 --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/version.py @@ -0,0 +1,4 @@ +# Copyright The OpenTelemetry Authors +# SPDX-License-Identifier: Apache-2.0 + +__version__ = "0.66b0.dev" diff --git a/resource/opentelemetry-resource-detector-host/test-requirements.txt b/resource/opentelemetry-resource-detector-host/test-requirements.txt new file mode 100644 index 0000000000..5b0e7a6db1 --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/test-requirements.txt @@ -0,0 +1,12 @@ +asgiref==3.8.1 +Deprecated==1.2.14 +iniconfig==2.0.0 +packaging==24.0 +pluggy==1.6.0 +py-cpuinfo==9.0.0 +pytest==7.4.4 +tomli==2.0.1 +typing_extensions==4.12.2 +wrapt==1.16.0 +zipp==3.19.2 +-e resource/opentelemetry-resource-detector-host diff --git a/resource/opentelemetry-resource-detector-host/tests/__init__.py b/resource/opentelemetry-resource-detector-host/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/resource/opentelemetry-resource-detector-host/tests/test_host.py b/resource/opentelemetry-resource-detector-host/tests/test_host.py new file mode 100644 index 0000000000..32f4cfdabb --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/tests/test_host.py @@ -0,0 +1,172 @@ +# Copyright The OpenTelemetry Authors +# SPDX-License-Identifier: Apache-2.0 + +import subprocess +from types import SimpleNamespace +from unittest.mock import mock_open, patch + +from opentelemetry.resource.detector.host import HostIdResourceDetector +from opentelemetry.sdk.resources import get_aggregated_resources +from opentelemetry.semconv.resource import ResourceAttributes +from opentelemetry.test.test_base import TestBase +from opentelemetry.util._importlib_metadata import entry_points + +MODULE = "opentelemetry.resource.detector.host" +HOST_ID = ResourceAttributes.HOST_ID + +_IOREG_OUTPUT = """+-o IOPlatformExpertDevice + { + "IOPlatformUUID" = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE" + "IOPlatformSerialNumber" = "C02XXXXXXXXX" + } +""" + +_REG_OUTPUT = ( + "\r\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\r\n" + " MachineGuid REG_SZ 12345678-90ab-cdef-1234-567890abcdef\r\n" +) + + +def _completed(stdout: str = "", returncode: int = 0) -> SimpleNamespace: + return SimpleNamespace(stdout=stdout, stderr="", returncode=returncode) + + +class HostIdResourceDetectorTest(TestBase): + def _assert_only_host_id(self, resource, expected: str) -> None: + attributes = resource.attributes + self.assertEqual(dict(attributes), {HOST_ID: expected}) + # Verify the value type matches the semconv spec (string). + self.assertIsInstance(attributes[HOST_ID], str) + + # ---- Linux ---- + + @patch(f"{MODULE}.platform.system", return_value="Linux") + @patch( + f"{MODULE}.open", + new_callable=mock_open, + read_data="linux-machine-id\n", + ) + def test_linux_reads_etc_machine_id(self, mock_file, mock_system): + self._assert_only_host_id( + HostIdResourceDetector().detect(), "linux-machine-id" + ) + + @patch(f"{MODULE}.platform.system", return_value="Linux") + @patch( + f"{MODULE}._read_first_line", + side_effect=[None, "dbus-machine-id"], + ) + def test_linux_falls_back_to_dbus_machine_id(self, mock_read, mock_system): + resource = HostIdResourceDetector().detect() + self._assert_only_host_id(resource, "dbus-machine-id") + self.assertEqual( + [call.args[0] for call in mock_read.call_args_list], + ["/etc/machine-id", "/var/lib/dbus/machine-id"], + ) + + @patch(f"{MODULE}.platform.system", return_value="Linux") + @patch(f"{MODULE}._read_first_line", return_value=None) + def test_linux_no_machine_id(self, mock_read, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + + # ---- macOS ---- + + @patch(f"{MODULE}.platform.system", return_value="Darwin") + @patch(f"{MODULE}.subprocess.run", return_value=_completed(_IOREG_OUTPUT)) + def test_macos_parses_ioreg_platform_uuid(self, mock_run, mock_system): + self._assert_only_host_id( + HostIdResourceDetector().detect(), + "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE", + ) + + @patch(f"{MODULE}.platform.system", return_value="Darwin") + @patch(f"{MODULE}.subprocess.run", return_value=_completed("no uuid here")) + def test_macos_no_platform_uuid(self, mock_run, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + + # ---- Windows ---- + + @patch(f"{MODULE}.platform.system", return_value="Windows") + @patch(f"{MODULE}.subprocess.run", return_value=_completed(_REG_OUTPUT)) + def test_windows_parses_machine_guid(self, mock_run, mock_system): + self._assert_only_host_id( + HostIdResourceDetector().detect(), + "12345678-90ab-cdef-1234-567890abcdef", + ) + + @patch(f"{MODULE}.platform.system", return_value="Windows") + @patch( + f"{MODULE}.subprocess.run", + return_value=_completed("", returncode=1), + ) + def test_windows_registry_query_fails(self, mock_run, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + + # ---- BSD ---- + + @patch(f"{MODULE}.platform.system", return_value="FreeBSD") + @patch(f"{MODULE}._read_first_line", return_value="bsd-host-id") + def test_bsd_reads_etc_hostid(self, mock_read, mock_system): + resource = HostIdResourceDetector().detect() + self._assert_only_host_id(resource, "bsd-host-id") + self.assertEqual(mock_read.call_args.args[0], "/etc/hostid") + + @patch(f"{MODULE}.platform.system", return_value="NetBSD") + @patch(f"{MODULE}._read_first_line", return_value=None) + @patch( + f"{MODULE}.subprocess.run", + return_value=_completed("bsd-kenv-uuid\n"), + ) + def test_bsd_falls_back_to_kenv(self, mock_run, mock_read, mock_system): + self._assert_only_host_id( + HostIdResourceDetector().detect(), "bsd-kenv-uuid" + ) + + # ---- Unsupported / error paths ---- + + @patch(f"{MODULE}.platform.system", return_value="Java") + def test_unsupported_os_returns_empty(self, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + + @patch(f"{MODULE}.platform.system", return_value="Darwin") + @patch( + f"{MODULE}.subprocess.run", + side_effect=subprocess.TimeoutExpired(cmd="ioreg", timeout=5), + ) + def test_command_timeout_returns_empty(self, mock_run, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + + @patch(f"{MODULE}.platform.system", return_value="Darwin") + @patch(f"{MODULE}.subprocess.run", side_effect=FileNotFoundError) + def test_command_not_found_returns_empty(self, mock_run, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + + @patch(f"{MODULE}._get_host_id", side_effect=ValueError("boom")) + def test_error_swallowed_by_default(self, mock_get): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + + @patch(f"{MODULE}._get_host_id", side_effect=ValueError("boom")) + def test_raise_on_error(self, mock_get): + with self.assertRaises(ValueError): + HostIdResourceDetector(raise_on_error=True).detect() + + # ---- Integration ---- + + @patch(f"{MODULE}._get_host_id", return_value="agg-host-id") + def test_host_id_via_aggregated_resources(self, mock_get): + resource = get_aggregated_resources([HostIdResourceDetector()]) + self.assertEqual(resource.attributes[HOST_ID], "agg-host-id") + + def test_host_id_entrypoint(self): + (entrypoint,) = entry_points( + group="opentelemetry_resource_detector", name="host_id" + ) + detector = entrypoint.load()() + self.assertIsInstance(detector, HostIdResourceDetector) diff --git a/tox.ini b/tox.ini index 81ba52d1f5..2484711586 100644 --- a/tox.ini +++ b/tox.ini @@ -46,6 +46,11 @@ envlist = pypy3-test-resource-detector-containerid lint-resource-detector-containerid + ; opentelemetry-resource-detector-host + py3{10,11,12,13,14}-test-resource-detector-host + pypy3-test-resource-detector-host + lint-resource-detector-host + ; opentelemetry-resource-detector-azure py3{10,11,12,13,14}-test-resource-detector-azure-{0,1} pypy3-test-resource-detector-azure-{0,1} @@ -763,6 +768,9 @@ deps = resource-detector-containerid: {[testenv]test_deps} resource-detector-containerid: -r {toxinidir}/resource/opentelemetry-resource-detector-containerid/test-requirements.txt + resource-detector-host: {[testenv]test_deps} + resource-detector-host: -r {toxinidir}/resource/opentelemetry-resource-detector-host/test-requirements.txt + # packages that are released individually should provide a test-requirements.txt with the lowest version of OTel API # and SDK supported to test we are honoring it resource-detector-azure-0: -r {toxinidir}/resource/opentelemetry-resource-detector-azure/test-requirements-0.txt @@ -1037,6 +1045,9 @@ commands = test-resource-detector-containerid: pytest {toxinidir}/resource/opentelemetry-resource-detector-containerid/tests {posargs} lint-resource-detector-containerid: sh -c "cd resource && pylint --rcfile ../.pylintrc opentelemetry-resource-detector-containerid" + test-resource-detector-host: pytest {toxinidir}/resource/opentelemetry-resource-detector-host/tests {posargs} + lint-resource-detector-host: sh -c "cd resource && pylint --rcfile ../.pylintrc opentelemetry-resource-detector-host" + test-resource-detector-azure: pytest {toxinidir}/resource/opentelemetry-resource-detector-azure/tests {posargs} lint-resource-detector-azure: sh -c "cd resource && pylint --rcfile ../.pylintrc opentelemetry-resource-detector-azure" From 327dc1bf03a71aa8f3e05925bd88259757e8d8ad Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Mon, 20 Jul 2026 14:29:00 -0400 Subject: [PATCH 2/8] use non deprecated semconv ref --- .changelog/0000.added | 2 +- .../README.rst | 8 ------- .../resource/detector/host/__init__.py | 13 +++++----- .../tests/test_host.py | 24 +++++++++++++++++-- 4 files changed, 29 insertions(+), 18 deletions(-) diff --git a/.changelog/0000.added b/.changelog/0000.added index 8d50cef540..ce23768716 100644 --- a/.changelog/0000.added +++ b/.changelog/0000.added @@ -1 +1 @@ -Add `opentelemetry-resource-detector-host` package that sets `host.id` from the non-privileged machine id +`opentelemetry-resource-detector-host`: add detector setting `host.id` from the non-privileged machine id diff --git a/resource/opentelemetry-resource-detector-host/README.rst b/resource/opentelemetry-resource-detector-host/README.rst index 2e9f828aed..eca2ac5a0c 100644 --- a/resource/opentelemetry-resource-detector-host/README.rst +++ b/resource/opentelemetry-resource-detector-host/README.rst @@ -10,10 +10,6 @@ This library provides a custom `Resource Detector `_. -The value is read from the non-privileged machine-id sources defined by the specification. It -complements the built-in host resource detector from the OpenTelemetry SDK, which only sets -``host.name`` and ``host.arch``. - Installation ------------ @@ -56,10 +52,6 @@ non-privileged sources, depending on the operating system: * **Windows**: the ``MachineGuid`` value under the ``HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography`` registry key. * **BSD**: the contents of ``/etc/hostid``, falling back to the output of ``kenv -q smbios.system.uuid``. -If no value can be read, the detector returns an empty resource and ``host.id`` is left unset. In -that case, the value can be provided explicitly through the ``OTEL_RESOURCE_ATTRIBUTES`` environment -variable. - References ---------- diff --git a/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py index 76bc733116..700f10767a 100644 --- a/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py +++ b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py @@ -8,7 +8,9 @@ from logging import getLogger from opentelemetry.sdk.resources import Resource, ResourceDetector -from opentelemetry.semconv.resource import ResourceAttributes +from opentelemetry.semconv._incubating.attributes.host_attributes import ( + HOST_ID, +) logger = getLogger(__name__) @@ -122,9 +124,8 @@ def _get_host_id() -> str | None: class HostIdResourceDetector(ResourceDetector): - """Detects the ``host.id`` resource attribute from the machine id of the - host, using only the non-privileged sources described in the OpenTelemetry - semantic conventions. + """Detects the ``host.id`` resource attribute from the non-privileged + machine id of the host and returns it in a Resource """ def detect(self) -> Resource: @@ -132,9 +133,7 @@ def detect(self) -> Resource: host_id = _get_host_id() resource = Resource.get_empty() if host_id: - resource = resource.merge( - Resource({ResourceAttributes.HOST_ID: host_id}) - ) + resource = resource.merge(Resource({HOST_ID: host_id})) return resource # pylint: disable=broad-except diff --git a/resource/opentelemetry-resource-detector-host/tests/test_host.py b/resource/opentelemetry-resource-detector-host/tests/test_host.py index 32f4cfdabb..531c553ded 100644 --- a/resource/opentelemetry-resource-detector-host/tests/test_host.py +++ b/resource/opentelemetry-resource-detector-host/tests/test_host.py @@ -7,12 +7,13 @@ from opentelemetry.resource.detector.host import HostIdResourceDetector from opentelemetry.sdk.resources import get_aggregated_resources -from opentelemetry.semconv.resource import ResourceAttributes +from opentelemetry.semconv._incubating.attributes.host_attributes import ( + HOST_ID, +) from opentelemetry.test.test_base import TestBase from opentelemetry.util._importlib_metadata import entry_points MODULE = "opentelemetry.resource.detector.host" -HOST_ID = ResourceAttributes.HOST_ID _IOREG_OUTPUT = """+-o IOPlatformExpertDevice { @@ -105,6 +106,15 @@ def test_windows_registry_query_fails(self, mock_run, mock_system): resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) + @patch(f"{MODULE}.platform.system", return_value="Windows") + @patch( + f"{MODULE}.subprocess.run", + return_value=_completed("no machine guid here"), + ) + def test_windows_no_machine_guid(self, mock_run, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + # ---- BSD ---- @patch(f"{MODULE}.platform.system", return_value="FreeBSD") @@ -125,6 +135,16 @@ def test_bsd_falls_back_to_kenv(self, mock_run, mock_read, mock_system): HostIdResourceDetector().detect(), "bsd-kenv-uuid" ) + @patch(f"{MODULE}.platform.system", return_value="FreeBSD") + @patch(f"{MODULE}._read_first_line", return_value=None) + @patch( + f"{MODULE}.subprocess.run", + return_value=_completed("", returncode=1), + ) + def test_bsd_no_host_id(self, mock_run, mock_read, mock_system): + resource = HostIdResourceDetector().detect() + self.assertNotIn(HOST_ID, resource.attributes) + # ---- Unsupported / error paths ---- @patch(f"{MODULE}.platform.system", return_value="Java") From 4ab63e0bdd6eff24b037f5da22cfb88fc75b5c82 Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Mon, 20 Jul 2026 14:41:31 -0400 Subject: [PATCH 3/8] cleanups --- .../tests/test_host.py | 26 +++---------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/resource/opentelemetry-resource-detector-host/tests/test_host.py b/resource/opentelemetry-resource-detector-host/tests/test_host.py index 531c553ded..8e0c0da1b1 100644 --- a/resource/opentelemetry-resource-detector-host/tests/test_host.py +++ b/resource/opentelemetry-resource-detector-host/tests/test_host.py @@ -28,19 +28,16 @@ ) -def _completed(stdout: str = "", returncode: int = 0) -> SimpleNamespace: - return SimpleNamespace(stdout=stdout, stderr="", returncode=returncode) +def _completed(stdout: str = "", return_code: int = 0) -> SimpleNamespace: + return SimpleNamespace(stdout=stdout, stderr="", returncode=return_code) class HostIdResourceDetectorTest(TestBase): def _assert_only_host_id(self, resource, expected: str) -> None: attributes = resource.attributes self.assertEqual(dict(attributes), {HOST_ID: expected}) - # Verify the value type matches the semconv spec (string). self.assertIsInstance(attributes[HOST_ID], str) - # ---- Linux ---- - @patch(f"{MODULE}.platform.system", return_value="Linux") @patch( f"{MODULE}.open", @@ -71,8 +68,6 @@ def test_linux_no_machine_id(self, mock_read, mock_system): resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) - # ---- macOS ---- - @patch(f"{MODULE}.platform.system", return_value="Darwin") @patch(f"{MODULE}.subprocess.run", return_value=_completed(_IOREG_OUTPUT)) def test_macos_parses_ioreg_platform_uuid(self, mock_run, mock_system): @@ -87,8 +82,6 @@ def test_macos_no_platform_uuid(self, mock_run, mock_system): resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) - # ---- Windows ---- - @patch(f"{MODULE}.platform.system", return_value="Windows") @patch(f"{MODULE}.subprocess.run", return_value=_completed(_REG_OUTPUT)) def test_windows_parses_machine_guid(self, mock_run, mock_system): @@ -100,7 +93,7 @@ def test_windows_parses_machine_guid(self, mock_run, mock_system): @patch(f"{MODULE}.platform.system", return_value="Windows") @patch( f"{MODULE}.subprocess.run", - return_value=_completed("", returncode=1), + return_value=_completed("", return_code=1), ) def test_windows_registry_query_fails(self, mock_run, mock_system): resource = HostIdResourceDetector().detect() @@ -115,8 +108,6 @@ def test_windows_no_machine_guid(self, mock_run, mock_system): resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) - # ---- BSD ---- - @patch(f"{MODULE}.platform.system", return_value="FreeBSD") @patch(f"{MODULE}._read_first_line", return_value="bsd-host-id") def test_bsd_reads_etc_hostid(self, mock_read, mock_system): @@ -139,14 +130,12 @@ def test_bsd_falls_back_to_kenv(self, mock_run, mock_read, mock_system): @patch(f"{MODULE}._read_first_line", return_value=None) @patch( f"{MODULE}.subprocess.run", - return_value=_completed("", returncode=1), + return_value=_completed("", return_code=1), ) def test_bsd_no_host_id(self, mock_run, mock_read, mock_system): resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) - # ---- Unsupported / error paths ---- - @patch(f"{MODULE}.platform.system", return_value="Java") def test_unsupported_os_returns_empty(self, mock_system): resource = HostIdResourceDetector().detect() @@ -177,13 +166,6 @@ def test_raise_on_error(self, mock_get): with self.assertRaises(ValueError): HostIdResourceDetector(raise_on_error=True).detect() - # ---- Integration ---- - - @patch(f"{MODULE}._get_host_id", return_value="agg-host-id") - def test_host_id_via_aggregated_resources(self, mock_get): - resource = get_aggregated_resources([HostIdResourceDetector()]) - self.assertEqual(resource.attributes[HOST_ID], "agg-host-id") - def test_host_id_entrypoint(self): (entrypoint,) = entry_points( group="opentelemetry_resource_detector", name="host_id" From c3069806227052ccea2bfc88a32f02313d31230b Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Mon, 20 Jul 2026 14:56:38 -0400 Subject: [PATCH 4/8] update changelog with PR number --- .changelog/{0000.added => 4843.added} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .changelog/{0000.added => 4843.added} (100%) diff --git a/.changelog/0000.added b/.changelog/4843.added similarity index 100% rename from .changelog/0000.added rename to .changelog/4843.added From 5878cec6ab572ed30c14a1449fae851f716c8917 Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Mon, 20 Jul 2026 15:06:16 -0400 Subject: [PATCH 5/8] fix import --- resource/opentelemetry-resource-detector-host/tests/test_host.py | 1 - 1 file changed, 1 deletion(-) diff --git a/resource/opentelemetry-resource-detector-host/tests/test_host.py b/resource/opentelemetry-resource-detector-host/tests/test_host.py index 8e0c0da1b1..c1ceaa2f97 100644 --- a/resource/opentelemetry-resource-detector-host/tests/test_host.py +++ b/resource/opentelemetry-resource-detector-host/tests/test_host.py @@ -6,7 +6,6 @@ from unittest.mock import mock_open, patch from opentelemetry.resource.detector.host import HostIdResourceDetector -from opentelemetry.sdk.resources import get_aggregated_resources from opentelemetry.semconv._incubating.attributes.host_attributes import ( HOST_ID, ) From 89ca8be399cadf04d2fe2271f21d15a5a16ff6ea Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Wed, 22 Jul 2026 08:41:05 -0400 Subject: [PATCH 6/8] opt in to type checking, add end to end tests, use full path checking, switch statement --- pyproject.toml | 1 + .../resource/detector/host/__init__.py | 65 ++++--- .../resource/detector/host/py.typed | 0 .../tests/test_host.py | 165 +++++++++++++----- tox.ini | 1 + 5 files changed, 170 insertions(+), 62 deletions(-) create mode 100644 resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/py.typed diff --git a/pyproject.toml b/pyproject.toml index 4c90657e1c..81fef81227 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -217,6 +217,7 @@ include = [ "opamp/opentelemetry-opamp-client", "sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace", "opentelemetry-instrumentation/src/opentelemetry/instrumentation/_labeler", + "resource/opentelemetry-resource-detector-host", ] # We should also add type hints to the test suite - It helps on finding bugs. # We are excluding for now because it's easier, and more important to add to the instrumentation packages. diff --git a/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py index 700f10767a..f5633881b4 100644 --- a/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py +++ b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/__init__.py @@ -3,6 +3,7 @@ from __future__ import annotations +import os import platform import subprocess from logging import getLogger @@ -18,10 +19,19 @@ # https://opentelemetry.io/docs/specs/semconv/resource/host/#non-privileged-machine-id-lookup _LINUX_MACHINE_ID_PATHS = ("/etc/machine-id", "/var/lib/dbus/machine-id") _BSD_HOSTID_PATH = "/etc/hostid" -_BSD_KENV_COMMAND = ("kenv", "-q", "smbios.system.uuid") -_MACOS_IOREG_COMMAND = ("ioreg", "-rd1", "-c", "IOPlatformExpertDevice") -_WINDOWS_REGISTRY_COMMAND = ( - "reg", +_BSD_KENV_COMMAND = ("/bin/kenv", "-q", "smbios.system.uuid") +_MACOS_IOREG_COMMAND = ( + "/usr/sbin/ioreg", + "-rd1", + "-c", + "IOPlatformExpertDevice", +) +# Prefer the SystemRoot/WINDIR environment variables to locate the Windows +# directory, falling back to the conventional install path only if neither is +# set. SystemRoot and WINDIR normally point to the same directory. +_WINDOWS_ROOT_ENV_VARS = ("SystemRoot", "WINDIR") +_WINDOWS_ROOT_FALLBACK = r"C:\Windows" +_WINDOWS_REGISTRY_QUERY_ARGS = ( "query", r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography", "/v", @@ -30,6 +40,16 @@ _COMMAND_TIMEOUT_SECONDS = 5 +def _windows_reg_path() -> str: + for env_var in _WINDOWS_ROOT_ENV_VARS: + root = os.environ.get(env_var) + if root: + break + else: + root = _WINDOWS_ROOT_FALLBACK + return os.path.join(root, "System32", "reg.exe") + + def _read_first_line(path: str) -> str | None: try: with open(path, encoding="utf8") as machine_id_file: @@ -97,7 +117,8 @@ def _get_macos_machine_id() -> str | None: def _get_windows_machine_id() -> str | None: - output = _run_command(_WINDOWS_REGISTRY_COMMAND) + command = (_windows_reg_path(), *_WINDOWS_REGISTRY_QUERY_ARGS) + output = _run_command(command) if not output: return None for line in output.splitlines(): @@ -111,16 +132,20 @@ def _get_windows_machine_id() -> str | None: def _get_host_id() -> str | None: system = platform.system() - if system == "Linux": - return _get_linux_machine_id() - if system == "Darwin": - return _get_macos_machine_id() - if system == "Windows": - return _get_windows_machine_id() - if system == "DragonFly" or system.endswith("BSD"): - return _get_bsd_machine_id() - logger.debug("Unsupported OS type for host.id detection: %s", system) - return None + match system: + case "Linux": + return _get_linux_machine_id() + case "Darwin": + return _get_macos_machine_id() + case "Windows": + return _get_windows_machine_id() + case _ if system == "DragonFly" or system.endswith("BSD"): + return _get_bsd_machine_id() + case _: + logger.debug( + "Unsupported OS type for host.id detection: %s", system + ) + return None class HostIdResourceDetector(ResourceDetector): @@ -130,11 +155,9 @@ class HostIdResourceDetector(ResourceDetector): def detect(self) -> Resource: try: - host_id = _get_host_id() - resource = Resource.get_empty() - if host_id: - resource = resource.merge(Resource({HOST_ID: host_id})) - return resource + if host_id := _get_host_id(): + return Resource({HOST_ID: host_id}) + return Resource.get_empty() # pylint: disable=broad-except except Exception as exception: @@ -145,4 +168,4 @@ def detect(self) -> Resource: ) if self.raise_on_error: raise exception - return Resource.get_empty() + return Resource.get_empty() diff --git a/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/py.typed b/resource/opentelemetry-resource-detector-host/src/opentelemetry/resource/detector/host/py.typed new file mode 100644 index 0000000000..e69de29bb2 diff --git a/resource/opentelemetry-resource-detector-host/tests/test_host.py b/resource/opentelemetry-resource-detector-host/tests/test_host.py index c1ceaa2f97..0f75f29ed6 100644 --- a/resource/opentelemetry-resource-detector-host/tests/test_host.py +++ b/resource/opentelemetry-resource-detector-host/tests/test_host.py @@ -1,16 +1,29 @@ # Copyright The OpenTelemetry Authors # SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import os +import platform import subprocess +import sys +from importlib.metadata import entry_points from types import SimpleNamespace -from unittest.mock import mock_open, patch +from unittest import skipUnless +from unittest.mock import MagicMock, patch -from opentelemetry.resource.detector.host import HostIdResourceDetector +from opentelemetry.resource.detector.host import ( + HostIdResourceDetector, + _windows_reg_path, +) +from opentelemetry.sdk.resources import Resource from opentelemetry.semconv._incubating.attributes.host_attributes import ( HOST_ID, ) from opentelemetry.test.test_base import TestBase -from opentelemetry.util._importlib_metadata import entry_points + +if sys.platform == "win32": + import winreg MODULE = "opentelemetry.resource.detector.host" @@ -21,39 +34,62 @@ } """ -_REG_OUTPUT = ( - "\r\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\r\n" - " MachineGuid REG_SZ 12345678-90ab-cdef-1234-567890abcdef\r\n" -) - def _completed(stdout: str = "", return_code: int = 0) -> SimpleNamespace: return SimpleNamespace(stdout=stdout, stderr="", returncode=return_code) class HostIdResourceDetectorTest(TestBase): - def _assert_only_host_id(self, resource, expected: str) -> None: + def _assert_only_host_id(self, resource: Resource, expected: str) -> None: attributes = resource.attributes self.assertEqual(dict(attributes), {HOST_ID: expected}) self.assertIsInstance(attributes[HOST_ID], str) - @patch(f"{MODULE}.platform.system", return_value="Linux") - @patch( - f"{MODULE}.open", - new_callable=mock_open, - read_data="linux-machine-id\n", + def _assert_real_host_id(self) -> None: + resource = HostIdResourceDetector().detect() + self.assertIn(HOST_ID, resource.attributes) + host_id = resource.attributes[HOST_ID] + self.assertIsInstance(host_id, str) + self.assertTrue(host_id) + + @skipUnless( + platform.system() == "Linux", + "Linux specific host.id end-to-end detection", ) - def test_linux_reads_etc_machine_id(self, mock_file, mock_system): - self._assert_only_host_id( - HostIdResourceDetector().detect(), "linux-machine-id" - ) + def test_linux_end_to_end(self) -> None: + self._assert_real_host_id() + + @skipUnless( + platform.system() == "Windows", + "Windows specific host.id end-to-end detection", + ) + def test_windows_end_to_end(self) -> None: + # Guard on sys.platform (in addition to the skip decorator) so the + # type checker only analyzes the Windows-only winreg usage on Windows. + if sys.platform != "win32": + return + + # winreg reads the registry through the Win32 API, an independent + # mechanism from the detector's reg.exe subprocess, so it is a valid + # oracle for the exact value the detector should return. + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SOFTWARE\Microsoft\Cryptography", + ) as key: + machine_guid, _ = winreg.QueryValueEx(key, "MachineGuid") + + resource = HostIdResourceDetector().detect() + self.assertIn(HOST_ID, resource.attributes) + self.assertEqual(resource.attributes[HOST_ID], machine_guid) @patch(f"{MODULE}.platform.system", return_value="Linux") @patch( f"{MODULE}._read_first_line", side_effect=[None, "dbus-machine-id"], ) - def test_linux_falls_back_to_dbus_machine_id(self, mock_read, mock_system): + def test_linux_falls_back_to_dbus_machine_id( + self, mock_read: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self._assert_only_host_id(resource, "dbus-machine-id") self.assertEqual( @@ -63,13 +99,17 @@ def test_linux_falls_back_to_dbus_machine_id(self, mock_read, mock_system): @patch(f"{MODULE}.platform.system", return_value="Linux") @patch(f"{MODULE}._read_first_line", return_value=None) - def test_linux_no_machine_id(self, mock_read, mock_system): + def test_linux_no_machine_id( + self, mock_read: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) @patch(f"{MODULE}.platform.system", return_value="Darwin") @patch(f"{MODULE}.subprocess.run", return_value=_completed(_IOREG_OUTPUT)) - def test_macos_parses_ioreg_platform_uuid(self, mock_run, mock_system): + def test_macos_parses_ioreg_platform_uuid( + self, mock_run: MagicMock, mock_system: MagicMock + ) -> None: self._assert_only_host_id( HostIdResourceDetector().detect(), "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE", @@ -77,24 +117,20 @@ def test_macos_parses_ioreg_platform_uuid(self, mock_run, mock_system): @patch(f"{MODULE}.platform.system", return_value="Darwin") @patch(f"{MODULE}.subprocess.run", return_value=_completed("no uuid here")) - def test_macos_no_platform_uuid(self, mock_run, mock_system): + def test_macos_no_platform_uuid( + self, mock_run: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) - @patch(f"{MODULE}.platform.system", return_value="Windows") - @patch(f"{MODULE}.subprocess.run", return_value=_completed(_REG_OUTPUT)) - def test_windows_parses_machine_guid(self, mock_run, mock_system): - self._assert_only_host_id( - HostIdResourceDetector().detect(), - "12345678-90ab-cdef-1234-567890abcdef", - ) - @patch(f"{MODULE}.platform.system", return_value="Windows") @patch( f"{MODULE}.subprocess.run", return_value=_completed("", return_code=1), ) - def test_windows_registry_query_fails(self, mock_run, mock_system): + def test_windows_registry_query_fails( + self, mock_run: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) @@ -103,13 +139,42 @@ def test_windows_registry_query_fails(self, mock_run, mock_system): f"{MODULE}.subprocess.run", return_value=_completed("no machine guid here"), ) - def test_windows_no_machine_guid(self, mock_run, mock_system): + def test_windows_no_machine_guid( + self, mock_run: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) + def test_windows_reg_path_prefers_system_root(self) -> None: + with patch.dict( + "os.environ", + {"SystemRoot": r"D:\WinDir", "WINDIR": r"E:\Other"}, + clear=True, + ): + self.assertEqual( + _windows_reg_path(), + os.path.join(r"D:\WinDir", "System32", "reg.exe"), + ) + + def test_windows_reg_path_falls_back_to_windir(self) -> None: + with patch.dict("os.environ", {"WINDIR": r"E:\Other"}, clear=True): + self.assertEqual( + _windows_reg_path(), + os.path.join(r"E:\Other", "System32", "reg.exe"), + ) + + def test_windows_reg_path_falls_back_to_default(self) -> None: + with patch.dict("os.environ", {}, clear=True): + self.assertEqual( + _windows_reg_path(), + os.path.join(r"C:\Windows", "System32", "reg.exe"), + ) + @patch(f"{MODULE}.platform.system", return_value="FreeBSD") @patch(f"{MODULE}._read_first_line", return_value="bsd-host-id") - def test_bsd_reads_etc_hostid(self, mock_read, mock_system): + def test_bsd_reads_etc_hostid( + self, mock_read: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self._assert_only_host_id(resource, "bsd-host-id") self.assertEqual(mock_read.call_args.args[0], "/etc/hostid") @@ -120,7 +185,12 @@ def test_bsd_reads_etc_hostid(self, mock_read, mock_system): f"{MODULE}.subprocess.run", return_value=_completed("bsd-kenv-uuid\n"), ) - def test_bsd_falls_back_to_kenv(self, mock_run, mock_read, mock_system): + def test_bsd_falls_back_to_kenv( + self, + mock_run: MagicMock, + mock_read: MagicMock, + mock_system: MagicMock, + ) -> None: self._assert_only_host_id( HostIdResourceDetector().detect(), "bsd-kenv-uuid" ) @@ -131,41 +201,54 @@ def test_bsd_falls_back_to_kenv(self, mock_run, mock_read, mock_system): f"{MODULE}.subprocess.run", return_value=_completed("", return_code=1), ) - def test_bsd_no_host_id(self, mock_run, mock_read, mock_system): + def test_bsd_no_host_id( + self, + mock_run: MagicMock, + mock_read: MagicMock, + mock_system: MagicMock, + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) @patch(f"{MODULE}.platform.system", return_value="Java") - def test_unsupported_os_returns_empty(self, mock_system): + def test_unsupported_os_returns_empty( + self, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) + # Failure modes of the subprocess-backed lookups must not raise. + @patch(f"{MODULE}.platform.system", return_value="Darwin") @patch( f"{MODULE}.subprocess.run", side_effect=subprocess.TimeoutExpired(cmd="ioreg", timeout=5), ) - def test_command_timeout_returns_empty(self, mock_run, mock_system): + def test_command_timeout_returns_empty( + self, mock_run: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) @patch(f"{MODULE}.platform.system", return_value="Darwin") @patch(f"{MODULE}.subprocess.run", side_effect=FileNotFoundError) - def test_command_not_found_returns_empty(self, mock_run, mock_system): + def test_command_not_found_returns_empty( + self, mock_run: MagicMock, mock_system: MagicMock + ) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) @patch(f"{MODULE}._get_host_id", side_effect=ValueError("boom")) - def test_error_swallowed_by_default(self, mock_get): + def test_error_swallowed_by_default(self, mock_get: MagicMock) -> None: resource = HostIdResourceDetector().detect() self.assertNotIn(HOST_ID, resource.attributes) @patch(f"{MODULE}._get_host_id", side_effect=ValueError("boom")) - def test_raise_on_error(self, mock_get): + def test_raise_on_error(self, mock_get: MagicMock) -> None: with self.assertRaises(ValueError): HostIdResourceDetector(raise_on_error=True).detect() - def test_host_id_entrypoint(self): + def test_host_id_entrypoint(self) -> None: (entrypoint,) = entry_points( group="opentelemetry_resource_detector", name="host_id" ) diff --git a/tox.ini b/tox.ini index 044e913de0..3adebc7e94 100644 --- a/tox.ini +++ b/tox.ini @@ -1209,6 +1209,7 @@ deps = {toxinidir}/exporter/opentelemetry-exporter-credential-provider-gcp {toxinidir}/instrumentation/opentelemetry-instrumentation-aiohttp-client[instruments] {toxinidir}/opamp/opentelemetry-opamp-client + {toxinidir}/resource/opentelemetry-resource-detector-host commands = pyright From 43d1c03523f1f79b1ba54cce85e0379826273371 Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Wed, 22 Jul 2026 11:20:06 -0400 Subject: [PATCH 7/8] fix minimum version for semconv compliance, ensure CI runs on a windows machine --- .github/workflows/core_contrib_test.yml | 36 +++- .github/workflows/generate_workflows.py | 9 +- .../src/generate_workflows_lib/__init__.py | 22 ++- .github/workflows/test.yml | 172 ++++++++++++++++-- .../pyproject.toml | 2 +- ...ments.txt => test-requirements.latest.txt} | 0 .../test-requirements.oldest.txt | 14 ++ .../tests/test_host.py | 10 +- tox.ini | 11 +- 9 files changed, 241 insertions(+), 35 deletions(-) rename resource/opentelemetry-resource-detector-host/{test-requirements.txt => test-requirements.latest.txt} (100%) create mode 100644 resource/opentelemetry-resource-detector-host/test-requirements.oldest.txt diff --git a/.github/workflows/core_contrib_test.yml b/.github/workflows/core_contrib_test.yml index 440ffe96e6..8db82ffda6 100644 --- a/.github/workflows/core_contrib_test.yml +++ b/.github/workflows/core_contrib_test.yml @@ -417,8 +417,8 @@ jobs: - name: Run tests run: tox -e py310-test-resource-detector-containerid -- -ra - py310-test-resource-detector-host: - name: resource-detector-host + py310-test-resource-detector-host-oldest: + name: resource-detector-host-oldest runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -445,7 +445,37 @@ jobs: run: pip install tox-uv - name: Run tests - run: tox -e py310-test-resource-detector-host -- -ra + run: tox -e py310-test-resource-detector-host-oldest -- -ra + + py310-test-resource-detector-host-latest: + name: resource-detector-host-latest + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout contrib repo @ SHA - ${{ env.CONTRIB_REPO_SHA }} + uses: actions/checkout@v4 + with: + repository: open-telemetry/opentelemetry-python-contrib + ref: ${{ env.CONTRIB_REPO_SHA }} + + - name: Checkout core repo @ SHA - ${{ env.CORE_REPO_SHA }} + uses: actions/checkout@v4 + with: + repository: open-telemetry/opentelemetry-python + ref: ${{ env.CORE_REPO_SHA }} + path: opentelemetry-python + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10" + architecture: "x64" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py310-test-resource-detector-host-latest -- -ra py310-test-resource-detector-azure-0: name: resource-detector-azure-0 diff --git a/.github/workflows/generate_workflows.py b/.github/workflows/generate_workflows.py index 7aacf708f0..64ca84ea17 100644 --- a/.github/workflows/generate_workflows.py +++ b/.github/workflows/generate_workflows.py @@ -11,7 +11,14 @@ tox_ini_path = Path(__file__).parent.parent.parent.joinpath("tox.ini") workflows_directory_path = Path(__file__).parent -generate_test_workflow(tox_ini_path, workflows_directory_path, "ubuntu-latest") +generate_test_workflow( + tox_ini_path, + workflows_directory_path, + "ubuntu-latest", + additional_jobs={ + "py312-test-resource-detector-host-latest": ("windows-latest",), + }, +) generate_lint_workflow(tox_ini_path, workflows_directory_path) generate_misc_workflow(tox_ini_path, workflows_directory_path) generate_contrib_workflow(workflows_directory_path) diff --git a/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py b/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py index 10f4ad921f..642818fd41 100644 --- a/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py +++ b/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py @@ -185,10 +185,28 @@ def _generate_workflow( def generate_test_workflow( - tox_ini_path: Path, workflow_directory_path: Path, *operating_systems + tox_ini_path: Path, + workflow_directory_path: Path, + *operating_systems: str, + additional_jobs: dict[str, tuple[str, ...]] | None = None, ) -> None: + tox_envs = get_tox_envs(tox_ini_path) + job_datas = get_test_job_datas(tox_envs, list(operating_systems)) + + for tox_env, additional_operating_systems in ( + additional_jobs or {} + ).items(): + if tox_env not in tox_envs: + raise ValueError(f"Unknown tox environment: {tox_env}") + job_datas.extend( + get_test_job_datas( + [tox_env], + list(additional_operating_systems), + ) + ) + _generate_workflow( - get_test_job_datas(get_tox_envs(tox_ini_path), operating_systems), + job_datas, "test", workflow_directory_path, ) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 97321aac89..5d7874450d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1278,8 +1278,8 @@ jobs: - name: Run tests run: tox -e pypy3-test-resource-detector-containerid -- -ra - py310-test-resource-detector-host_ubuntu-latest: - name: resource-detector-host 3.10 Ubuntu + py310-test-resource-detector-host-oldest_ubuntu-latest: + name: resource-detector-host-oldest 3.10 Ubuntu runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -1295,10 +1295,48 @@ jobs: run: pip install tox-uv - name: Run tests - run: tox -e py310-test-resource-detector-host -- -ra + run: tox -e py310-test-resource-detector-host-oldest -- -ra - py311-test-resource-detector-host_ubuntu-latest: - name: resource-detector-host 3.11 Ubuntu + py310-test-resource-detector-host-latest_ubuntu-latest: + name: resource-detector-host-latest 3.10 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py310-test-resource-detector-host-latest -- -ra + + py311-test-resource-detector-host-oldest_ubuntu-latest: + name: resource-detector-host-oldest 3.11 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py311-test-resource-detector-host-oldest -- -ra + + py311-test-resource-detector-host-latest_ubuntu-latest: + name: resource-detector-host-latest 3.11 Ubuntu runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -1314,10 +1352,29 @@ jobs: run: pip install tox-uv - name: Run tests - run: tox -e py311-test-resource-detector-host -- -ra + run: tox -e py311-test-resource-detector-host-latest -- -ra + + py312-test-resource-detector-host-oldest_ubuntu-latest: + name: resource-detector-host-oldest 3.12 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py312-test-resource-detector-host-oldest -- -ra - py312-test-resource-detector-host_ubuntu-latest: - name: resource-detector-host 3.12 Ubuntu + py312-test-resource-detector-host-latest_ubuntu-latest: + name: resource-detector-host-latest 3.12 Ubuntu runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -1333,10 +1390,29 @@ jobs: run: pip install tox-uv - name: Run tests - run: tox -e py312-test-resource-detector-host -- -ra + run: tox -e py312-test-resource-detector-host-latest -- -ra + + py313-test-resource-detector-host-oldest_ubuntu-latest: + name: resource-detector-host-oldest 3.13 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py313-test-resource-detector-host-oldest -- -ra - py313-test-resource-detector-host_ubuntu-latest: - name: resource-detector-host 3.13 Ubuntu + py313-test-resource-detector-host-latest_ubuntu-latest: + name: resource-detector-host-latest 3.13 Ubuntu runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -1352,10 +1428,29 @@ jobs: run: pip install tox-uv - name: Run tests - run: tox -e py313-test-resource-detector-host -- -ra + run: tox -e py313-test-resource-detector-host-latest -- -ra + + py314-test-resource-detector-host-oldest_ubuntu-latest: + name: resource-detector-host-oldest 3.14 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.14 + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py314-test-resource-detector-host-oldest -- -ra - py314-test-resource-detector-host_ubuntu-latest: - name: resource-detector-host 3.14 Ubuntu + py314-test-resource-detector-host-latest_ubuntu-latest: + name: resource-detector-host-latest 3.14 Ubuntu runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -1371,10 +1466,29 @@ jobs: run: pip install tox-uv - name: Run tests - run: tox -e py314-test-resource-detector-host -- -ra + run: tox -e py314-test-resource-detector-host-latest -- -ra + + pypy3-test-resource-detector-host-oldest_ubuntu-latest: + name: resource-detector-host-oldest pypy-3.10 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python pypy-3.10 + uses: actions/setup-python@v5 + with: + python-version: "pypy-3.10" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e pypy3-test-resource-detector-host-oldest -- -ra - pypy3-test-resource-detector-host_ubuntu-latest: - name: resource-detector-host pypy-3.10 Ubuntu + pypy3-test-resource-detector-host-latest_ubuntu-latest: + name: resource-detector-host-latest pypy-3.10 Ubuntu runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -1390,7 +1504,7 @@ jobs: run: pip install tox-uv - name: Run tests - run: tox -e pypy3-test-resource-detector-host -- -ra + run: tox -e pypy3-test-resource-detector-host-latest -- -ra py310-test-resource-detector-azure-0_ubuntu-latest: name: resource-detector-azure-0 3.10 Ubuntu @@ -13855,3 +13969,25 @@ jobs: - name: Run tests run: tox -e py314-test-opamp-client-lowest -- -ra + + py312-test-resource-detector-host-latest_windows-latest: + name: resource-detector-host-latest 3.12 Windows + runs-on: windows-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install tox + run: pip install tox-uv + + - name: Configure git to support long filenames + run: git config --system core.longpaths true + + - name: Run tests + run: tox -e py312-test-resource-detector-host-latest -- -ra diff --git a/resource/opentelemetry-resource-detector-host/pyproject.toml b/resource/opentelemetry-resource-detector-host/pyproject.toml index 48c0d084b8..6269dc1729 100644 --- a/resource/opentelemetry-resource-detector-host/pyproject.toml +++ b/resource/opentelemetry-resource-detector-host/pyproject.toml @@ -25,7 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.14", ] dependencies = [ - "opentelemetry-sdk ~= 1.12", + "opentelemetry-sdk ~= 1.25", ] [project.entry-points.opentelemetry_resource_detector] diff --git a/resource/opentelemetry-resource-detector-host/test-requirements.txt b/resource/opentelemetry-resource-detector-host/test-requirements.latest.txt similarity index 100% rename from resource/opentelemetry-resource-detector-host/test-requirements.txt rename to resource/opentelemetry-resource-detector-host/test-requirements.latest.txt diff --git a/resource/opentelemetry-resource-detector-host/test-requirements.oldest.txt b/resource/opentelemetry-resource-detector-host/test-requirements.oldest.txt new file mode 100644 index 0000000000..58773a7915 --- /dev/null +++ b/resource/opentelemetry-resource-detector-host/test-requirements.oldest.txt @@ -0,0 +1,14 @@ +asgiref==3.8.1 +Deprecated==1.2.14 +iniconfig==2.0.0 +opentelemetry-api==1.25.0 # when updating, also update in pyproject.toml +opentelemetry-sdk==1.25.0 # when updating, also update in pyproject.toml +packaging==24.0 +pluggy==1.6.0 +py-cpuinfo==9.0.0 +pytest==7.4.4 +tomli==2.0.1 +typing_extensions==4.12.2 +wrapt==1.16.0 +zipp==3.19.2 +-e resource/opentelemetry-resource-detector-host diff --git a/resource/opentelemetry-resource-detector-host/tests/test_host.py b/resource/opentelemetry-resource-detector-host/tests/test_host.py index 0f75f29ed6..6f970caf69 100644 --- a/resource/opentelemetry-resource-detector-host/tests/test_host.py +++ b/resource/opentelemetry-resource-detector-host/tests/test_host.py @@ -9,7 +9,7 @@ import sys from importlib.metadata import entry_points from types import SimpleNamespace -from unittest import skipUnless +from unittest import TestCase, skipUnless from unittest.mock import MagicMock, patch from opentelemetry.resource.detector.host import ( @@ -20,10 +20,6 @@ from opentelemetry.semconv._incubating.attributes.host_attributes import ( HOST_ID, ) -from opentelemetry.test.test_base import TestBase - -if sys.platform == "win32": - import winreg MODULE = "opentelemetry.resource.detector.host" @@ -39,7 +35,7 @@ def _completed(stdout: str = "", return_code: int = 0) -> SimpleNamespace: return SimpleNamespace(stdout=stdout, stderr="", returncode=return_code) -class HostIdResourceDetectorTest(TestBase): +class HostIdResourceDetectorTest(TestCase): def _assert_only_host_id(self, resource: Resource, expected: str) -> None: attributes = resource.attributes self.assertEqual(dict(attributes), {HOST_ID: expected}) @@ -69,6 +65,8 @@ def test_windows_end_to_end(self) -> None: if sys.platform != "win32": return + import winreg # pylint: disable=import-outside-toplevel # noqa: PLC0415 + # winreg reads the registry through the Win32 API, an independent # mechanism from the detector's reg.exe subprocess, so it is a valid # oracle for the exact value the detector should return. diff --git a/tox.ini b/tox.ini index 3adebc7e94..450a0cde80 100644 --- a/tox.ini +++ b/tox.ini @@ -47,8 +47,8 @@ envlist = lint-resource-detector-containerid ; opentelemetry-resource-detector-host - py3{10,11,12,13,14}-test-resource-detector-host - pypy3-test-resource-detector-host + py3{10,11,12,13,14}-test-resource-detector-host-{oldest,latest} + pypy3-test-resource-detector-host-{oldest,latest} lint-resource-detector-host ; opentelemetry-resource-detector-azure @@ -772,8 +772,11 @@ deps = resource-detector-containerid: {[testenv]test_deps} resource-detector-containerid: -r {toxinidir}/resource/opentelemetry-resource-detector-containerid/test-requirements.txt - resource-detector-host: {[testenv]test_deps} - resource-detector-host: -r {toxinidir}/resource/opentelemetry-resource-detector-host/test-requirements.txt + resource-detector-host-oldest: -r {toxinidir}/resource/opentelemetry-resource-detector-host/test-requirements.oldest.txt + resource-detector-host-latest: {[testenv]test_deps} + resource-detector-host-latest: -r {toxinidir}/resource/opentelemetry-resource-detector-host/test-requirements.latest.txt + lint-resource-detector-host: {[testenv]test_deps} + lint-resource-detector-host: -r {toxinidir}/resource/opentelemetry-resource-detector-host/test-requirements.latest.txt # packages that are released individually should provide a test-requirements.txt with the lowest version of OTel API # and SDK supported to test we are honoring it From 5a1338e47c049d66c57ba44c372447a22fe52d44 Mon Sep 17 00:00:00 2001 From: Jay DeLuca Date: Wed, 22 Jul 2026 15:06:51 -0400 Subject: [PATCH 8/8] undo windows test runner changes --- .github/workflows/generate_workflows.py | 9 +------- .../src/generate_workflows_lib/__init__.py | 22 ++----------------- .github/workflows/test.yml | 22 ------------------- 3 files changed, 3 insertions(+), 50 deletions(-) diff --git a/.github/workflows/generate_workflows.py b/.github/workflows/generate_workflows.py index 64ca84ea17..7aacf708f0 100644 --- a/.github/workflows/generate_workflows.py +++ b/.github/workflows/generate_workflows.py @@ -11,14 +11,7 @@ tox_ini_path = Path(__file__).parent.parent.parent.joinpath("tox.ini") workflows_directory_path = Path(__file__).parent -generate_test_workflow( - tox_ini_path, - workflows_directory_path, - "ubuntu-latest", - additional_jobs={ - "py312-test-resource-detector-host-latest": ("windows-latest",), - }, -) +generate_test_workflow(tox_ini_path, workflows_directory_path, "ubuntu-latest") generate_lint_workflow(tox_ini_path, workflows_directory_path) generate_misc_workflow(tox_ini_path, workflows_directory_path) generate_contrib_workflow(workflows_directory_path) diff --git a/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py b/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py index 642818fd41..10f4ad921f 100644 --- a/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py +++ b/.github/workflows/generate_workflows_lib/src/generate_workflows_lib/__init__.py @@ -185,28 +185,10 @@ def _generate_workflow( def generate_test_workflow( - tox_ini_path: Path, - workflow_directory_path: Path, - *operating_systems: str, - additional_jobs: dict[str, tuple[str, ...]] | None = None, + tox_ini_path: Path, workflow_directory_path: Path, *operating_systems ) -> None: - tox_envs = get_tox_envs(tox_ini_path) - job_datas = get_test_job_datas(tox_envs, list(operating_systems)) - - for tox_env, additional_operating_systems in ( - additional_jobs or {} - ).items(): - if tox_env not in tox_envs: - raise ValueError(f"Unknown tox environment: {tox_env}") - job_datas.extend( - get_test_job_datas( - [tox_env], - list(additional_operating_systems), - ) - ) - _generate_workflow( - job_datas, + get_test_job_datas(get_tox_envs(tox_ini_path), operating_systems), "test", workflow_directory_path, ) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5d7874450d..77d835e2b5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13969,25 +13969,3 @@ jobs: - name: Run tests run: tox -e py314-test-opamp-client-lowest -- -ra - - py312-test-resource-detector-host-latest_windows-latest: - name: resource-detector-host-latest 3.12 Windows - runs-on: windows-latest - timeout-minutes: 30 - steps: - - name: Checkout repo @ SHA - ${{ github.sha }} - uses: actions/checkout@v4 - - - name: Set up Python 3.12 - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - - name: Install tox - run: pip install tox-uv - - - name: Configure git to support long filenames - run: git config --system core.longpaths true - - - name: Run tests - run: tox -e py312-test-resource-detector-host-latest -- -ra