__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. import logging
  15. import threading
  16. from collections import OrderedDict
  17. from collections.abc import MutableMapping
  18. from typing import Optional, Sequence, Tuple, Union
  19. from opentelemetry.util import types
  20. # bytes are accepted as a user supplied value for attributes but
  21. # decoded to strings internally.
  22. _VALID_ATTR_VALUE_TYPES = (bool, str, bytes, int, float)
  23. _logger = logging.getLogger(__name__)
  24. def _clean_attribute(
  25. key: str, value: types.AttributeValue, max_len: Optional[int]
  26. ) -> Optional[Union[types.AttributeValue, Tuple[Union[str, int, float], ...]]]:
  27. """Checks if attribute value is valid and cleans it if required.
  28. The function returns the cleaned value or None if the value is not valid.
  29. An attribute value is valid if it is either:
  30. - A primitive type: string, boolean, double precision floating
  31. point (IEEE 754-1985) or integer.
  32. - An array of primitive type values. The array MUST be homogeneous,
  33. i.e. it MUST NOT contain values of different types.
  34. An attribute needs cleansing if:
  35. - Its length is greater than the maximum allowed length.
  36. - It needs to be encoded/decoded e.g, bytes to strings.
  37. """
  38. if not (key and isinstance(key, str)):
  39. _logger.warning("invalid key `%s`. must be non-empty string.", key)
  40. return None
  41. if isinstance(value, _VALID_ATTR_VALUE_TYPES):
  42. return _clean_attribute_value(value, max_len)
  43. if isinstance(value, Sequence):
  44. sequence_first_valid_type = None
  45. cleaned_seq = []
  46. for element in value:
  47. element = _clean_attribute_value(element, max_len) # type: ignore
  48. if element is None:
  49. cleaned_seq.append(element)
  50. continue
  51. element_type = type(element)
  52. # Reject attribute value if sequence contains a value with an incompatible type.
  53. if element_type not in _VALID_ATTR_VALUE_TYPES:
  54. _logger.warning(
  55. "Invalid type %s in attribute '%s' value sequence. Expected one of "
  56. "%s or None",
  57. element_type.__name__,
  58. key,
  59. [
  60. valid_type.__name__
  61. for valid_type in _VALID_ATTR_VALUE_TYPES
  62. ],
  63. )
  64. return None
  65. # The type of the sequence must be homogeneous. The first non-None
  66. # element determines the type of the sequence
  67. if sequence_first_valid_type is None:
  68. sequence_first_valid_type = element_type
  69. # use equality instead of isinstance as isinstance(True, int) evaluates to True
  70. elif element_type != sequence_first_valid_type:
  71. _logger.warning(
  72. "Attribute %r mixes types %s and %s in attribute value sequence",
  73. key,
  74. sequence_first_valid_type.__name__,
  75. type(element).__name__,
  76. )
  77. return None
  78. cleaned_seq.append(element)
  79. # Freeze mutable sequences defensively
  80. return tuple(cleaned_seq)
  81. _logger.warning(
  82. "Invalid type %s for attribute '%s' value. Expected one of %s or a "
  83. "sequence of those types",
  84. type(value).__name__,
  85. key,
  86. [valid_type.__name__ for valid_type in _VALID_ATTR_VALUE_TYPES],
  87. )
  88. return None
  89. def _clean_attribute_value(
  90. value: types.AttributeValue, limit: Optional[int]
  91. ) -> Optional[types.AttributeValue]:
  92. if value is None:
  93. return None
  94. if isinstance(value, bytes):
  95. try:
  96. value = value.decode()
  97. except UnicodeDecodeError:
  98. _logger.warning("Byte attribute could not be decoded.")
  99. return None
  100. if limit is not None and isinstance(value, str):
  101. value = value[:limit]
  102. return value
  103. class BoundedAttributes(MutableMapping): # type: ignore
  104. """An ordered dict with a fixed max capacity.
  105. Oldest elements are dropped when the dict is full and a new element is
  106. added.
  107. """
  108. def __init__(
  109. self,
  110. maxlen: Optional[int] = None,
  111. attributes: types.Attributes = None,
  112. immutable: bool = True,
  113. max_value_len: Optional[int] = None,
  114. ):
  115. if maxlen is not None:
  116. if not isinstance(maxlen, int) or maxlen < 0:
  117. raise ValueError(
  118. "maxlen must be valid int greater or equal to 0"
  119. )
  120. self.maxlen = maxlen
  121. self.dropped = 0
  122. self.max_value_len = max_value_len
  123. # OrderedDict is not used until the maxlen is reached for efficiency.
  124. self._dict: Union[
  125. MutableMapping[str, types.AttributeValue],
  126. OrderedDict[str, types.AttributeValue],
  127. ] = {}
  128. self._lock = threading.RLock()
  129. if attributes:
  130. for key, value in attributes.items():
  131. self[key] = value
  132. self._immutable = immutable
  133. def __repr__(self) -> str:
  134. return f"{dict(self._dict)}"
  135. def __getitem__(self, key: str) -> types.AttributeValue:
  136. return self._dict[key]
  137. def __setitem__(self, key: str, value: types.AttributeValue) -> None:
  138. if getattr(self, "_immutable", False): # type: ignore
  139. raise TypeError
  140. with self._lock:
  141. if self.maxlen is not None and self.maxlen == 0:
  142. self.dropped += 1
  143. return
  144. value = _clean_attribute(key, value, self.max_value_len) # type: ignore
  145. if value is not None:
  146. if key in self._dict:
  147. del self._dict[key]
  148. elif (
  149. self.maxlen is not None and len(self._dict) == self.maxlen
  150. ):
  151. if not isinstance(self._dict, OrderedDict):
  152. self._dict = OrderedDict(self._dict)
  153. self._dict.popitem(last=False) # type: ignore
  154. self.dropped += 1
  155. self._dict[key] = value # type: ignore
  156. def __delitem__(self, key: str) -> None:
  157. if getattr(self, "_immutable", False): # type: ignore
  158. raise TypeError
  159. with self._lock:
  160. del self._dict[key]
  161. def __iter__(self): # type: ignore
  162. with self._lock:
  163. return iter(self._dict.copy()) # type: ignore
  164. def __len__(self) -> int:
  165. return len(self._dict)
  166. def copy(self): # type: ignore
  167. return self._dict.copy() # type: ignore