|
| 1 | +# Copyright 2010 New Relic, Inc. |
| 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 | +"""This module provides common utilities for interacting with OTLP protocol buffers.""" |
| 16 | + |
| 17 | +import logging |
| 18 | +_logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +try: |
| 21 | + from newrelic.packages.opentelemetry_proto.common_pb2 import AnyValue, KeyValue |
| 22 | +except ImportError: |
| 23 | + create_key_value, create_key_values_from_iterable = None, None |
| 24 | +else: |
| 25 | + def create_key_value(key, value): |
| 26 | + if isinstance(value, bool): |
| 27 | + return KeyValue(key=key, value=AnyValue(bool_value=value)) |
| 28 | + elif isinstance(value, int): |
| 29 | + return KeyValue(key=key, value=AnyValue(int_value=value)) |
| 30 | + elif isinstance(value, float): |
| 31 | + return KeyValue(key=key, value=AnyValue(double_value=value)) |
| 32 | + elif isinstance(value, str): |
| 33 | + return KeyValue(key=key, value=AnyValue(string_value=value)) |
| 34 | + # Technically AnyValue accepts array, kvlist, and bytes however, since |
| 35 | + # those are not valid custom attribute types according to our api spec, |
| 36 | + # we will not bother to support them here either. |
| 37 | + else: |
| 38 | + _logger.warn("Unsupported ML event attribute value type %s: %s." % (key, value)) |
| 39 | + |
| 40 | + |
| 41 | + def create_key_values_from_iterable(iterable): |
| 42 | + if isinstance(iterable, dict): |
| 43 | + iterable = iterable.items() |
| 44 | + |
| 45 | + return list( |
| 46 | + filter( |
| 47 | + lambda i: i is not None, |
| 48 | + (create_key_value(key, value) for key, value in iterable), |
| 49 | + ) |
| 50 | + ) |
0 commit comments