Skip to content
This repository was archived by the owner on Jul 25, 2024. It is now read-only.

Commit 3f2a8db

Browse files
pirgeoarminru
andauthored
Rename OneAgent metadata to Dynatrace Metadata (#19)
Co-authored-by: Armin Ruech <armin.ruech@dynatrace.com>
1 parent cd7d1f4 commit 3f2a8db

12 files changed

Lines changed: 206 additions & 165 deletions

File tree

.github/workflows/publish.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: Upload Python Package to PyPI
22

33
on:
44
release:
5-
types: [published]
5+
types: [ published ]
66

77
jobs:
88
publish:

.github/workflows/python-package.yml

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,33 +11,33 @@ jobs:
1111
runs-on: ubuntu-latest
1212

1313
steps:
14-
- uses: actions/checkout@v2
15-
- name: Set up Python
16-
uses: actions/setup-python@v2
17-
with:
18-
python-version: 3.8
19-
- name: Install Dependencies
20-
run: |
21-
pip install -U pip
22-
pip install -U wheel setuptools tox
23-
- run: tox -e lint
14+
- uses: actions/checkout@v2
15+
- name: Set up Python
16+
uses: actions/setup-python@v2
17+
with:
18+
python-version: 3.8
19+
- name: Install Dependencies
20+
run: |
21+
pip install -U pip
22+
pip install -U wheel setuptools tox
23+
- run: tox -e lint
2424

2525
build-and-test:
2626
runs-on: ubuntu-latest
2727
strategy:
2828
fail-fast: false
2929
matrix:
30-
python-version: [ '3.6', '3.7', '3.8', '3.9', 'pypy3']
30+
python-version: [ '3.6', '3.7', '3.8', '3.9', 'pypy3' ]
3131

3232
steps:
33-
- uses: actions/checkout@v2
34-
- name: Set up Python ${{ matrix.python-version }}
35-
uses: actions/setup-python@v2
36-
with:
37-
python-version: ${{ matrix.python-version }}
38-
- name: Install Dependencies
39-
run: |
40-
pip install -U pip
41-
pip install -U wheel setuptools tox
42-
- name: Test
43-
run: tox -e py
33+
- uses: actions/checkout@v2
34+
- name: Set up Python ${{ matrix.python-version }}
35+
uses: actions/setup-python@v2
36+
with:
37+
python-version: ${{ matrix.python-version }}
38+
- name: Install Dependencies
39+
run: |
40+
pip install -U pip
41+
pip install -U wheel setuptools tox
42+
- name: Test
43+
run: tox -e py

README.md

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@
66
77
## Getting started
88

9+
### Installation
10+
11+
To install the [latest version from PyPI](https://pypi.org/project/opentelemetry-exporter-dynatrace-metrics/) run:
12+
13+
```shell
14+
pip install opentelemetry-exporter-dynatrace-metrics
15+
```
16+
917
### Usage
1018

1119
The general setup of OpenTelemetry Python is explained in the official [Getting Started Guide](https://opentelemetry-python.readthedocs.io/en/stable/getting-started.html).
@@ -35,8 +43,8 @@ counter.add(25, {"dimension-1", "value-1"})
3543
To run the [example](example/basic_example.py), clone this repository and change to the `opentelemetry-metric-python` folder, then run:
3644

3745
```shell
38-
pip install . # install the Dynatrace exporter
39-
export LOGLEVEL=DEBUG # (optional) Set the log level to debug to see more output (default is INFO)
46+
pip install . # install the Dynatrace exporter
47+
export LOGLEVEL=DEBUG # (optional) Set the log level to debug to see more output (default is INFO)
4048
python example/basic_example.py
4149
```
4250

@@ -80,29 +88,29 @@ The `prefix` parameter specifies an optional prefix, which is prepended to each
8088
The `default_dimensions` parameter can be used to optionally specify a list of key/value pairs, which will be added as additional dimensions to all data points.
8189
Dimension keys are unique, and labels on instruments will overwrite the default dimensions if key collisions appear.
8290

83-
#### Export OneAgent Metadata
91+
#### Export Dynatrace Metadata
8492

85-
If running on a host with a running OneAgent, setting the `export_oneagent_metadata` option to `True` will export metadata collected by the OneAgent to the Dynatrace endpoint.
93+
If running on a host with a running OneAgent, setting the `export_dynatrace_metadata` option to `True` will export metadata collected by the OneAgent to the Dynatrace endpoint.
8694
If no Dynatrace API endpoint is set, the default exporter endpoint will be the OneAgent endpoint, and this option will be set automatically.
87-
Therefore, if no endpoint is specified, we assume a OneAgent is running and export to it, including metadata.
88-
More information on the underlying OneAgent feature that is used by the exporter can be found in the
95+
Therefore, if no endpoint is specified, a OneAgent is assumed to be running and used as the export endpoint for all metric lines, including metadata.
96+
More information on the underlying Dynatrace metadata feature that is used by the exporter can be found in the
8997
[Dynatrace documentation](https://www.dynatrace.com/support/help/how-to-use-dynatrace/metrics/metric-ingestion/ingestion-methods/enrich-metrics/).
9098

9199
##### Dimensions precedence
92100

93-
When specifying default dimensions, labels and OneAgent metadata enrichment, the precedence of dimensions with the same key is as follows:
94-
Default dimensions are overwritten by labels passed to instruments, which in turn are overwritten by the OneAgent dimensions (even though the likeliness of a collision here is very low, since the OneAgent metadata only contains [Dynatrace reserved dimensions](https://www.dynatrace.com/support/help/how-to-use-dynatrace/metrics/metric-ingestion/metric-ingestion-protocol/#syntax) starting with `dt.*`).
101+
When specifying default dimensions, labels and Dynatrace metadata enrichment, the precedence of dimensions with the same key is as follows:
102+
Default dimensions are overwritten by labels passed to instruments, which in turn are overwritten by the Dynatrace metadata dimensions (even though the likeliness of a collision here is very low, since the Dynatrace metadata only contains [Dynatrace reserved dimensions](https://www.dynatrace.com/support/help/how-to-use-dynatrace/metrics/metric-ingestion/metric-ingestion-protocol/#syntax) starting with `dt.*`).
95103

96104
## Development
97105

98106
### Requirements
99107

100-
Just [`tox`](https://pypi.org/project/tox/)
108+
Just [`tox`](https://pypi.org/project/tox/).
101109

102110
### Running tests and lint
103111

104-
*Test all supported python versions:* `tox`
105-
*Test all supported python versions in parallel:* `tox -p`
106-
*A particular python version:* `tox -e 38`
107-
*Current python version*: `tox -e py`
108-
*Lint*: `tox -e lint`
112+
* Test all supported python versions: `tox`
113+
* Test all supported python versions in parallel: `tox -p`
114+
* A particular python version: `tox -e 38`
115+
* Current python version: `tox -e py`
116+
* Lint: `tox -e lint`

example/basic_example.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,18 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
import random
15-
import time
1614

1715
from dynatrace.opentelemetry.metrics.export import DynatraceMetricsExporter
1816
from opentelemetry import metrics
1917
from opentelemetry.sdk.metrics import MeterProvider
18+
2019
from os.path import splitext, basename
2120
import argparse
2221
import logging
2322
import os
2423
import psutil
24+
import random
25+
import time
2526

2627

2728
# Callback to gather cpu usage
@@ -59,10 +60,11 @@ def parse_arguments():
5960

6061
parser.add_argument("-nm", "--no-metadata", dest="metadata_enrichment",
6162
action="store_false",
62-
help="Turn off OneAgent Metadata enrichment. If no "
63-
"OneAgent is running on the machine, this is "
64-
"ignored. Otherwise, OneAgent metadata will be "
65-
"added to each of the exported metric lines.")
63+
help="Turn off Dynatrace Metadata enrichment. If no "
64+
"OneAgent is running on "
65+
"the host, this is ignored. Otherwise, Dynatrace "
66+
"metadata will be added to each of the exported "
67+
"metric lines.")
6668

6769
parser.add_argument("-i", "--interval", default=10., type=float,
6870
dest="interval",
@@ -101,8 +103,8 @@ def parse_arguments():
101103
logger.info("setting up Dynatrace metrics exporting interface.")
102104
exporter = DynatraceMetricsExporter(args.endpoint, args.token,
103105
prefix="otel.python",
104-
export_oneagent_metadata=args
105-
.metadata_enrichment)
106+
export_dynatrace_metadata=
107+
args.metadata_enrichment)
106108

107109
logger.info("registering Dynatrace exporter with the global OpenTelemetry"
108110
" instance...")
@@ -163,6 +165,5 @@ def parse_arguments():
163165
requests_size.record(random.randint(0, 100), testing_labels)
164166
time.sleep(5)
165167

166-
167168
except KeyboardInterrupt:
168169
logger.info("shutting down...")

example/install_and_run.sh

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ else
1010
fi
1111

1212
# change into the opentelemetry-metric-python folder if you haven't already
13-
python3 -m venv .venv `# create a new virtual environment in the current folder`
13+
python3 -m venv .venv `# create a new virtual environment in the current folder`
1414

1515
source .venv/bin/activate
16-
pip3 install --upgrade setuptools `# make sure setuptools and wheel are on the latest version`
17-
pip3 install psutil `# for observing cpu and ram`
18-
pip3 install . `# install the library itself`
16+
pip3 install --upgrade setuptools `# make sure setuptools and wheel are on the latest version`
17+
pip3 install psutil `# for observing cpu and ram`
18+
pip3 install . `# install the library itself`
1919
# Valid log levels are: DEBUG, INFO, WARN/WARNING, ERROR, CRITICAL/FATAL
20-
export LOGLEVEL=DEBUG `# set the log level`
21-
python3 example/basic_example.py `# run the example in a venv`
20+
export LOGLEVEL=DEBUG `# set the log level`
21+
python3 example/basic_example.py `# run the example in a venv`

src/dynatrace/opentelemetry/metrics/export/__init__.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@
2323
)
2424

2525
from .serializer import DynatraceMetricsSerializer
26-
from .oneagentmetadataenricher import OneAgentMetadataEnricher
26+
from .dynatracemetadataenricher import DynatraceMetadataEnricher
2727

28-
VERSION = "0.1.0b0"
28+
VERSION = "0.1.0b1"
2929

3030

3131
class DynatraceMetricsExporter(MetricsExporter):
@@ -43,7 +43,7 @@ def __init__(
4343
api_token: Optional[str] = None,
4444
prefix: Optional[str] = None,
4545
default_dimensions: Optional[Mapping[str, str]] = None,
46-
export_oneagent_metadata: Optional[bool] = False,
46+
export_dynatrace_metadata: Optional[bool] = False,
4747
):
4848
self.__logger = logging.getLogger(__name__)
4949

@@ -54,15 +54,16 @@ def __init__(
5454
"to default local OneAgent ingest endpoint.")
5555
self._endpoint_url = "http://localhost:14499/metrics/ingest"
5656

57-
oneagent_dims = {}
57+
dynatrace_metadata_dims = {}
5858

59-
if export_oneagent_metadata:
60-
enricher = OneAgentMetadataEnricher()
61-
enricher.add_oneagent_metadata_to_dimensions(oneagent_dims)
59+
if export_dynatrace_metadata:
60+
enricher = DynatraceMetadataEnricher()
61+
enricher.add_dynatrace_metadata_to_dimensions(
62+
dynatrace_metadata_dims)
6263

6364
self._serializer = DynatraceMetricsSerializer(prefix,
6465
default_dimensions,
65-
oneagent_dims)
66+
dynatrace_metadata_dims)
6667
self._session = requests.Session()
6768
self._headers = {
6869
"Accept": "*/*; q=0",
@@ -111,7 +112,8 @@ def export(
111112
headers=self._headers,
112113
) as resp:
113114
resp.raise_for_status()
114-
self.__logger.debug("got response: " + resp.content)
115+
self.__logger.debug("got response: " +
116+
resp.content.decode("utf-8"))
115117
except Exception as ex:
116118
self.__logger.warning("Failed to export metrics: %s", ex)
117119
return MetricsExportResult.FAILURE

src/dynatrace/opentelemetry/metrics/export/oneagentmetadataenricher.py renamed to src/dynatrace/opentelemetry/metrics/export/dynatracemetadataenricher.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@
1616
from typing import List, Mapping
1717

1818

19-
class OneAgentMetadataEnricher:
19+
class DynatraceMetadataEnricher:
2020
def __init__(self) -> None:
2121
self.__logger = logging.getLogger(__name__)
2222

23-
def add_oneagent_metadata_to_dimensions(self, tags: Mapping[str, str]):
23+
def add_dynatrace_metadata_to_dimensions(self, tags: Mapping[str, str]):
2424
metadata_file_content = self._get_metadata_file_content()
25-
parsed_metadata = self._parse_oneagent_metadata(metadata_file_content)
25+
parsed_metadata = self._parse_dynatrace_metadata(metadata_file_content)
2626
for key, value in parsed_metadata.items():
2727
tags[key] = value
2828

@@ -36,11 +36,11 @@ def _get_metadata_file_name(self, indirection_fname: str) -> str:
3636
file_name = metadata_indirection_file.read()
3737

3838
if not file_name:
39-
self.__logger.warning("OneAgent metadata file not specified "
39+
self.__logger.warning("Dynatrace metadata file not specified "
4040
"in indirection file.")
4141

4242
except OSError:
43-
self.__logger.warning("Could not read local OneAgent metadata "
43+
self.__logger.warning("Could not read local Dynatrace metadata "
4444
"enrichment file. This is normal if no "
4545
"OneAgent is installed.")
4646

@@ -59,11 +59,11 @@ def _get_metadata_file_content(self) -> List[str]:
5959
return attributes_file.readlines()
6060
except OSError:
6161
self.__logger.info(
62-
"Could not read OneAgent metadata file ({}).".format(
62+
"Could not read Dynatrace metadata file ({}).".format(
6363
metadata_file_name))
6464
return []
6565

66-
def _parse_oneagent_metadata(self, lines) -> Mapping[str, str]:
66+
def _parse_dynatrace_metadata(self, lines) -> Mapping[str, str]:
6767
key_value_pairs = {}
6868
for line in lines:
6969
self.__logger.debug("Parsing line {}".format(line.rstrip("\n")))

src/dynatrace/opentelemetry/metrics/export/serializer.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def __init__(
7070
self,
7171
prefix: Optional[str] = "",
7272
default_dimensions: Optional[Mapping] = None,
73-
oneagent_dimensions: Optional[Mapping] = None,
73+
dynatrace_metadata_dimensions: Optional[Mapping] = None,
7474
):
7575
self._prefix = prefix
7676
self._is_delta_export = None
@@ -81,7 +81,7 @@ def __init__(
8181
default_dimensions)
8282

8383
self._static_dimensions = self._normalize_dimensions(
84-
oneagent_dimensions)
84+
dynatrace_metadata_dimensions)
8585
self._static_dimensions["dt.metrics.source"] = "opentelemetry"
8686

8787
@classmethod
@@ -123,6 +123,7 @@ def _write_record(
123123
metric_key = self._get_metric_key(record)
124124
if metric_key == "":
125125
return
126+
126127
string_buffer.append(metric_key)
127128

128129
# merge dimensions to make them unique
@@ -133,8 +134,8 @@ def _write_record(
133134

134135
# add the merged dimension to the string builder.
135136
self._write_dimensions(string_buffer, unique_dimensions)
136-
137137
serialize_func(string_buffer, aggregator)
138+
138139
self._write_timestamp(string_buffer, aggregator)
139140
string_buffer.append("\n")
140141

@@ -305,10 +306,11 @@ def _make_unique_dimensions(cls,
305306
default_dimensions: typing.Dict[str, str],
306307
labels: Iterable[Tuple[str, str]],
307308
one_agent_dimensions: typing.Dict[str, str]):
308-
"""Merge default dimensions, user specified dimensions and OneAgent
309-
dimensions. default dimensions will be overwritten by user-specified
310-
dimensions, which will be overwritten by OneAgent dimensions.
311-
Default and OneAgent dimensions are assumed to be normalized when
309+
"""Merge default dimensions, user specified dimensions and Dynatrace
310+
metadata dimensions. Default dimensions will be overwritten by
311+
user-specified dimensions, which will be overwritten by Dynatrace
312+
metadata dimensions.
313+
Default and metadata dimensions are expected to be normalized when
312314
they are passed to this function."""
313315
dims_map = {}
314316

@@ -323,7 +325,7 @@ def _make_unique_dimensions(cls,
323325
dims_map[key] = cls._normalize_dimension_value(v)
324326

325327
# overwrite dimensions that the user set with the default dimensions
326-
# and OneAgent metadata. Tags are normalized in __init__ so they
328+
# and Dynatrace metadata. Tags are normalized in __init__ so they
327329
# don't have to be re-normalized here.
328330
if one_agent_dimensions:
329331
for k, v in one_agent_dimensions.items():

0 commit comments

Comments
 (0)