Source code for multistorageclient.telemetry.attributes.msc_config
1# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import copy
17import hashlib
18from collections.abc import Mapping
19from typing import Any, TypedDict
20
21import jmespath
22import jmespath.functions as jmespath_functions
23import opentelemetry.util.types as api_types
24
25from .base import AttributesProvider
26
27
28class _MSCConfigJMESPathFunctions(jmespath_functions.Functions):
29 """
30 Additional JMESPath functions.
31 """
32
33 @jmespath_functions.signature({"types": ["string"]}, {"types": ["string"]})
34 def _func_hash(self, algorithm: str, value: str) -> str:
35 """
36 Return the hexadecimal hash digest of a string.
37
38 :param algorithm: Hash algorithm.
39 :param value: Hash value.
40 :return: Hexadecimal hash digest.
41 """
42 value_hash = hashlib.new(algorithm)
43 value_hash.update(value.encode())
44 return value_hash.hexdigest()
45
46
[docs]
47class MSCConfigAttributesProvider(AttributesProvider):
48 """
49 Provides :py:type:`opentelemetry.util.types.Attributes` from a multi-storage client configuration.
50 """
51
[docs]
52 class AttributeValueOptions(TypedDict):
53 """
54 MSC configuration attribute value options.
55 """
56
57 #: JMESPath expression.
58 #:
59 #: Additional JMESPath functions:
60 #:
61 #: - ``hash(algorithm: str, value: str)``
62 #: - Calculate the hash digest of a value using a specific hash algorithm (e.g. ``sha3-256``).
63 #: - See :py:meth:`hashlib.new` for algorithms.
64 expression: str
65
66 #: Static attributes.
67 _attributes: api_types.Attributes
68
69 def __init__(self, attributes: Mapping[str, AttributeValueOptions], config_dict: Mapping[str, Any]):
70 """
71 :param attributes: Map of attribute key to map of attribute value options.
72 """
73
74 self._attributes = {
75 attribute_key: jmespath.search(
76 attribute_value_options["expression"],
77 config_dict,
78 options=jmespath.Options(custom_functions=_MSCConfigJMESPathFunctions()),
79 )
80 for attribute_key, attribute_value_options in attributes.items()
81 }
82
[docs]
83 def attributes(self) -> api_types.Attributes:
84 return copy.deepcopy(self._attributes)