Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sanitize resource attribute pairs to avoid exception #2256

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#1887](https://github.com/open-telemetry/opentelemetry-python/pull/1887))
- Make batch processor fork aware and reinit when needed
([#2242](https://github.com/open-telemetry/opentelemetry-python/pull/2242))
- `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

Expand Down
19 changes: 13 additions & 6 deletions opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("=", maxsplit=1)
except ValueError as exc:
logger.warning(
aabmass marked this conversation as resolved.
Show resolved Hide resolved
"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
Expand Down
10 changes: 10 additions & 0 deletions opentelemetry-sdk/tests/resources/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,16 @@ 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", "foo": "bar=baz"}),
)

@mock.patch.dict(
os.environ,
{resources.OTEL_SERVICE_NAME: "test-srv-name"},
Expand Down