From a18facbad868aa2104181abfd6073fab06c68297 Mon Sep 17 00:00:00 2001 From: "(Eliseo) Nathaniel Ruiz Nowell" Date: Mon, 1 Nov 2021 13:02:11 -0400 Subject: [PATCH] Filter invalid resource attribute pairs --- CHANGELOG.md | 2 ++ .../opentelemetry/sdk/resources/__init__.py | 19 +++++++++++++------ .../tests/resources/test_resources.py | 9 +++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f4c305ae74..d2e3d6816ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#2153](https://github.com/open-telemetry/opentelemetry-python/pull/2153)) - Add metrics API ([#1887](https://github.com/open-telemetry/opentelemetry-python/pull/1887)) +- `opentelemetry-sdk` Sanitize env var resource attribute pairs + ([#2256](https://github.com/open-telemetry/opentelemetry-python/pull/2256)) ## [1.6.2-0.25b2](https://github.com/open-telemetry/opentelemetry-python/releases/tag/v1.6.2-0.25b2) - 2021-10-19 diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py index 5878f375d79..81c8694ef7e 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py @@ -266,13 +266,20 @@ class OTELResourceDetector(ResourceDetector): def detect(self) -> "Resource": env_resources_items = os.environ.get(OTEL_RESOURCE_ATTRIBUTES) env_resource_map = {} + if env_resources_items: - env_resource_map = { - key.strip(): value.strip() - for key, value in ( - item.split("=") for item in env_resources_items.split(",") - ) - } + for item in env_resources_items.split(","): + try: + key, value = item.split("=") + except ValueError as exc: + logger.warning( + "Invalid key value resource attribute pair %s: %s", + item, + exc, + ) + continue + env_resource_map[key.strip()] = value.strip() + service_name = os.environ.get(OTEL_SERVICE_NAME) if service_name: env_resource_map[SERVICE_NAME] = service_name diff --git a/opentelemetry-sdk/tests/resources/test_resources.py b/opentelemetry-sdk/tests/resources/test_resources.py index ea3de80ed1b..5d4ab326258 100644 --- a/opentelemetry-sdk/tests/resources/test_resources.py +++ b/opentelemetry-sdk/tests/resources/test_resources.py @@ -482,6 +482,15 @@ def test_multiple_with_whitespace(self): detector.detect(), resources.Resource({"k": "v", "k2": "v2"}) ) + def test_invalid_key_value_pairs(self): + detector = resources.OTELResourceDetector() + os.environ[ + resources.OTEL_RESOURCE_ATTRIBUTES + ] = "k=v,k2=v2,invalid,,foo=bar=baz," + self.assertEqual( + detector.detect(), resources.Resource({"k": "v", "k2": "v2"}) + ) + @mock.patch.dict( os.environ, {resources.OTEL_SERVICE_NAME: "test-srv-name"},