|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import fnmatch |
| 18 | +import logging |
| 19 | +from typing import Callable, Optional |
| 20 | +from urllib import parse |
| 21 | + |
| 22 | +from opentelemetry.sdk._configuration.models import ( |
| 23 | + AttributeNameValue, |
| 24 | + AttributeType, |
| 25 | + ExperimentalResourceDetector, |
| 26 | + IncludeExclude, |
| 27 | +) |
| 28 | +from opentelemetry.sdk._configuration.models import Resource as ResourceConfig |
| 29 | +from opentelemetry.sdk.resources import ( |
| 30 | + _DEFAULT_RESOURCE, |
| 31 | + SERVICE_NAME, |
| 32 | + Resource, |
| 33 | +) |
| 34 | + |
| 35 | +_logger = logging.getLogger(__name__) |
| 36 | + |
| 37 | + |
| 38 | +def _coerce_bool(value: object) -> bool: |
| 39 | + if isinstance(value, str): |
| 40 | + return value.lower() not in ("false", "0", "") |
| 41 | + return bool(value) |
| 42 | + |
| 43 | + |
| 44 | +def _array(coerce: Callable) -> Callable: |
| 45 | + return lambda value: [coerce(item) for item in value] |
| 46 | + |
| 47 | + |
| 48 | +# Dispatch table mapping AttributeType to its coercion callable |
| 49 | +_COERCIONS = { |
| 50 | + AttributeType.string: str, |
| 51 | + AttributeType.int: int, |
| 52 | + AttributeType.double: float, |
| 53 | + AttributeType.bool: _coerce_bool, |
| 54 | + AttributeType.string_array: _array(str), |
| 55 | + AttributeType.int_array: _array(int), |
| 56 | + AttributeType.double_array: _array(float), |
| 57 | + AttributeType.bool_array: _array(_coerce_bool), |
| 58 | +} |
| 59 | + |
| 60 | + |
| 61 | +def _coerce_attribute_value(attr: AttributeNameValue) -> object: |
| 62 | + """Coerce an attribute value to the correct Python type based on AttributeType.""" |
| 63 | + coerce = _COERCIONS.get(attr.type) # type: ignore[arg-type] |
| 64 | + return coerce(attr.value) if coerce is not None else attr.value # type: ignore[operator] |
| 65 | + |
| 66 | + |
| 67 | +def _parse_attributes_list(attributes_list: str) -> dict[str, str]: |
| 68 | + """Parse a comma-separated key=value string into a dict. |
| 69 | +
|
| 70 | + Format is the same as OTEL_RESOURCE_ATTRIBUTES: key=value,key=value |
| 71 | + Values are always strings (no type coercion). |
| 72 | + """ |
| 73 | + result: dict[str, str] = {} |
| 74 | + for item in attributes_list.split(","): |
| 75 | + item = item.strip() |
| 76 | + if not item: |
| 77 | + continue |
| 78 | + if "=" not in item: |
| 79 | + _logger.warning( |
| 80 | + "Invalid resource attribute pair in attributes_list: %s", |
| 81 | + item, |
| 82 | + ) |
| 83 | + continue |
| 84 | + key, value = item.split("=", maxsplit=1) |
| 85 | + result[key.strip()] = parse.unquote(value.strip()) |
| 86 | + return result |
| 87 | + |
| 88 | + |
| 89 | +def create_resource(config: Optional[ResourceConfig]) -> Resource: |
| 90 | + """Create an SDK Resource from declarative config. |
| 91 | +
|
| 92 | + Does NOT read OTEL_RESOURCE_ATTRIBUTES. Resource detectors are only run |
| 93 | + when explicitly listed under detection_development.detectors in the config. |
| 94 | + Starts from SDK telemetry defaults (telemetry.sdk.*), merges any detected |
| 95 | + attributes, then merges explicit config attributes on top (highest priority). |
| 96 | +
|
| 97 | + Args: |
| 98 | + config: Resource config from the parsed config file, or None. |
| 99 | +
|
| 100 | + Returns: |
| 101 | + A Resource with SDK defaults, optional detector attributes, and any |
| 102 | + config-specified attributes merged in priority order. |
| 103 | + """ |
| 104 | + # Spec requires service.name to always be present; detectors and explicit |
| 105 | + # config attributes can override this default. |
| 106 | + base = _DEFAULT_RESOURCE.merge(Resource({SERVICE_NAME: "unknown_service"})) |
| 107 | + |
| 108 | + if config is None: |
| 109 | + return base |
| 110 | + |
| 111 | + # attributes_list is lower priority; explicit attributes overwrite conflicts. |
| 112 | + config_attrs: dict[str, object] = {} |
| 113 | + if config.attributes_list: |
| 114 | + config_attrs.update(_parse_attributes_list(config.attributes_list)) |
| 115 | + |
| 116 | + if config.attributes: |
| 117 | + for attr in config.attributes: |
| 118 | + config_attrs[attr.name] = _coerce_attribute_value(attr) |
| 119 | + |
| 120 | + schema_url = config.schema_url |
| 121 | + |
| 122 | + # Run detectors only if detection_development is configured. Collect all |
| 123 | + # detected attributes, apply the include/exclude filter, then merge before |
| 124 | + # config attributes so explicit values always win. |
| 125 | + result = base |
| 126 | + if config.detection_development: |
| 127 | + detected_attrs: dict[str, object] = {} |
| 128 | + if config.detection_development.detectors: |
| 129 | + for detector_config in config.detection_development.detectors: |
| 130 | + _run_detectors(detector_config, detected_attrs) |
| 131 | + |
| 132 | + filtered = _filter_attributes( |
| 133 | + detected_attrs, config.detection_development.attributes |
| 134 | + ) |
| 135 | + if filtered: |
| 136 | + result = result.merge(Resource(filtered)) # type: ignore[arg-type] |
| 137 | + |
| 138 | + config_resource = Resource(config_attrs, schema_url) # type: ignore[arg-type] |
| 139 | + return result.merge(config_resource) |
| 140 | + |
| 141 | + |
| 142 | +def _run_detectors( |
| 143 | + detector_config: ExperimentalResourceDetector, |
| 144 | + detected_attrs: dict[str, object], |
| 145 | +) -> None: |
| 146 | + """Run any detectors present in a single detector config entry. |
| 147 | +
|
| 148 | + Each detector PR adds its own branch here. The detected_attrs dict |
| 149 | + is updated in-place; later detectors overwrite earlier ones for the |
| 150 | + same key. |
| 151 | + """ |
| 152 | + |
| 153 | + |
| 154 | +def _filter_attributes( |
| 155 | + attrs: dict[str, object], filter_config: Optional[IncludeExclude] |
| 156 | +) -> dict[str, object]: |
| 157 | + """Filter detected attribute keys using include/exclude glob patterns. |
| 158 | +
|
| 159 | + Mirrors other SDK IncludeExcludePredicate.createPatternMatching behaviour: |
| 160 | + - No filter config (attributes absent) → include all detected attributes. |
| 161 | + - included patterns are checked first; excluded patterns are applied after. |
| 162 | + - An empty included list is treated as "include everything". |
| 163 | + """ |
| 164 | + if filter_config is None: |
| 165 | + return attrs |
| 166 | + |
| 167 | + included = filter_config.included |
| 168 | + excluded = filter_config.excluded |
| 169 | + |
| 170 | + if not included and not excluded: |
| 171 | + return attrs |
| 172 | + |
| 173 | + effective_included = included if included else None # [] → include all |
| 174 | + |
| 175 | + result: dict[str, object] = {} |
| 176 | + for key, value in attrs.items(): |
| 177 | + if effective_included is not None and not any( |
| 178 | + fnmatch.fnmatch(key, pat) for pat in effective_included |
| 179 | + ): |
| 180 | + continue |
| 181 | + if excluded and any(fnmatch.fnmatch(key, pat) for pat in excluded): |
| 182 | + continue |
| 183 | + result[key] = value |
| 184 | + return result |
0 commit comments