Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merging from upstream master #7

Merged
merged 5 commits into from
Dec 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ env:
# Otherwise, set variable to the commit of your branch on
# opentelemetry-python-contrib which is compatible with these Core repo
# changes.
CONTRIB_REPO_SHA: e1d4eeb951694afebb1767b4ea8f593753d894e3
CONTRIB_REPO_SHA: b37945bdeaf49822b240281d493d053995cc2b7b

jobs:
build:
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ var
sdist
develop-eggs
.installed.cfg
pyvenv.cfg
lib
share/
lib64
__pycache__
venv*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,13 @@ def test_get_collector_metric_type(self):
def test_get_collector_point(self):
aggregator = aggregate.SumAggregator()
int_counter = self._meter.create_counter(
"testName", "testDescription", "unit", int,
"testNameIntCounter", "testDescription", "unit", int,
)
float_counter = self._meter.create_counter(
"testName", "testDescription", "unit", float,
"testNameFloatCounter", "testDescription", "unit", float,
)
valuerecorder = self._meter.create_valuerecorder(
"testName", "testDescription", "unit", float,
"testNameValueRecorder", "testDescription", "unit", float,
)
result = metrics_exporter.get_collector_point(
ExportRecord(
Expand Down Expand Up @@ -168,7 +168,7 @@ def test_export(self):

def test_translate_to_collector(self):
test_metric = self._meter.create_counter(
"testname", "testdesc", "unit", int, self._labels.keys()
"testcollector", "testdesc", "unit", int, self._labels.keys()
)
aggregator = aggregate.SumAggregator()
aggregator.update(123)
Expand All @@ -185,7 +185,9 @@ def test_translate_to_collector(self):
)
self.assertEqual(len(output_metrics), 1)
self.assertIsInstance(output_metrics[0], metrics_pb2.Metric)
self.assertEqual(output_metrics[0].metric_descriptor.name, "testname")
self.assertEqual(
output_metrics[0].metric_descriptor.name, "testcollector"
)
self.assertEqual(
output_metrics[0].metric_descriptor.description, "testdesc"
)
Expand Down
4 changes: 4 additions & 0 deletions exporter/opentelemetry-exporter-otlp/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

## Version 0.16b1

Released 2020-11-26

- Add meter reference to observers
([#1425](https://github.com/open-telemetry/opentelemetry-python/pull/1425))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,12 @@ def __init__(
credentials is None
and Configuration().EXPORTER_OTLP_CERTIFICATE is None
):
raise ValueError("No credentials set in secure mode.")

credentials = credentials or _load_credential_from_file(
Configuration().EXPORTER_OTLP_CERTIFICATE
)
# use the default location chosen by gRPC runtime
credentials = ssl_channel_credentials()
else:
credentials = credentials or _load_credential_from_file(
Configuration().EXPORTER_OTLP_CERTIFICATE
)
self._client = self._stub(
secure_channel(
endpoint, credentials, compression=compression_algorithm
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,17 @@ def test_env_variables(self, mock_exporter_mixin):
self.assertIsNotNone(kwargs["credentials"])
self.assertIsInstance(kwargs["credentials"], ChannelCredentials)

def test_no_credentials_error(self):
with self.assertRaises(ValueError):
OTLPMetricsExporter()
@patch("opentelemetry.exporter.otlp.exporter.ssl_channel_credentials")
@patch("opentelemetry.exporter.otlp.exporter.secure_channel")
@patch(
"opentelemetry.exporter.otlp.metrics_exporter.OTLPMetricsExporter._stub"
)
# pylint: disable=unused-argument
def test_no_credentials_error(
self, mock_ssl_channel, mock_secure, mock_stub
):
OTLPMetricsExporter(insecure=False)
self.assertTrue(mock_ssl_channel.called)

@patch("opentelemetry.sdk.metrics.export.aggregate.time_ns")
def test_translate_counter_export_record(self, mock_time_ns):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,15 @@ def test_env_variables(self, mock_exporter_mixin):
self.assertIsNotNone(kwargs["credentials"])
self.assertIsInstance(kwargs["credentials"], ChannelCredentials)

def test_no_credentials_error(self):
with self.assertRaises(ValueError):
OTLPSpanExporter()
@patch("opentelemetry.exporter.otlp.exporter.ssl_channel_credentials")
@patch("opentelemetry.exporter.otlp.exporter.secure_channel")
@patch("opentelemetry.exporter.otlp.trace_exporter.OTLPSpanExporter._stub")
# pylint: disable=unused-argument
def test_no_credentials_error(
self, mock_ssl_channel, mock_secure, mock_stub
):
OTLPSpanExporter(insecure=False)
self.assertTrue(mock_ssl_channel.called)

@patch("opentelemetry.exporter.otlp.exporter.expo")
@patch("opentelemetry.exporter.otlp.exporter.sleep")
Expand Down
35 changes: 32 additions & 3 deletions opentelemetry-api/src/opentelemetry/configuration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,26 @@
to override this value instead of changing it.
"""

import re
from os import environ
from re import fullmatch
from typing import ClassVar, Dict, Optional, TypeVar, Union
from typing import ClassVar, Dict, List, Optional, Sequence, TypeVar, Union

ConfigValue = Union[str, bool, int, float]
_T = TypeVar("_T", ConfigValue, Optional[ConfigValue])


class ExcludeList:
"""Class to exclude certain paths (given as a list of regexes) from tracing requests"""

def __init__(self, excluded_urls: Sequence[str]):
self._non_empty = len(excluded_urls) > 0
if self._non_empty:
self._regex = re.compile("|".join(excluded_urls))

def url_disabled(self, url: str) -> bool:
return bool(self._non_empty and re.search(self._regex, url))


class Configuration:
_instance = None # type: ClassVar[Optional[Configuration]]
_config_map = {} # type: ClassVar[Dict[str, ConfigValue]]
Expand All @@ -113,7 +125,7 @@ def __new__(cls) -> "Configuration":
instance = super().__new__(cls)
for key, value_str in environ.items():

match = fullmatch(r"OTEL_(PYTHON_)?([A-Za-z_][\w_]*)", key)
match = re.fullmatch(r"OTEL_(PYTHON_)?([A-Za-z_][\w_]*)", key)

if match is not None:

Expand Down Expand Up @@ -167,3 +179,20 @@ def _reset(cls) -> None:
if cls._instance:
cls._instance._config_map.clear() # pylint: disable=protected-access
cls._instance = None

def _traced_request_attrs(self, instrumentation: str) -> List[str]:
"""Returns list of traced request attributes for instrumentation."""
key = "{}_TRACED_REQUEST_ATTRS".format(instrumentation.upper())
value = self._config_map.get(key, "")

request_attrs = (
[attr.strip() for attr in str.split(value, ",")] if value else [] # type: ignore
)
return request_attrs

def _excluded_urls(self, instrumentation: str) -> ExcludeList:
key = "{}_EXCLUDED_URLS".format(instrumentation.upper())
value = self._config_map.get(key, "")

urls = str.split(value, ",") if value else [] # type: ignore
return ExcludeList(urls)
2 changes: 1 addition & 1 deletion opentelemetry-api/src/opentelemetry/trace/span.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def is_recording(self) -> bool:
@abc.abstractmethod
def set_status(self, status: Status) -> None:
"""Sets the Status of the Span. If used, this will override the default
Span status, which is OK.
Span status.
"""

@abc.abstractmethod
Expand Down
12 changes: 0 additions & 12 deletions opentelemetry-api/src/opentelemetry/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,3 @@ def _load_meter_provider(provider: str) -> "MeterProvider":

def _load_trace_provider(provider: str) -> "TracerProvider":
return cast("TracerProvider", _load_provider(provider))


class ExcludeList:
"""Class to exclude certain paths (given as a list of regexes) from tracing requests"""

def __init__(self, excluded_urls: Sequence[str]):
self._non_empty = len(excluded_urls) > 0
if self._non_empty:
self._regex = re.compile("|".join(excluded_urls))

def url_disabled(self, url: str) -> bool:
return bool(self._non_empty and re.search(self._regex, url))
29 changes: 29 additions & 0 deletions opentelemetry-api/tests/configuration/test_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,32 @@ def test_float(self) -> None:
self.assertEqual(
Configuration().NON_FLOAT, "-12z3.123"
) # pylint: disable=no-member

@patch.dict(
"os.environ", # type: ignore
{
"OTEL_PYTHON_WEBFRAMEWORK_TRACED_REQUEST_ATTRS": "content_type,keep_alive",
},
)
def test_traced_request_attrs(self) -> None:
cfg = Configuration()
request_attrs = cfg._traced_request_attrs("webframework")
self.assertEqual(len(request_attrs), 2)
self.assertIn("content_type", request_attrs)
self.assertIn("keep_alive", request_attrs)
self.assertNotIn("authorization", request_attrs)

@patch.dict(
"os.environ", # type: ignore
{
"OTEL_PYTHON_WEBFRAMEWORK_EXCLUDED_URLS": "/healthzz,path,/issues/.*/view",
},
)
def test_excluded_urls(self) -> None:
cfg = Configuration()
excluded_urls = cfg._excluded_urls("webframework")
self.assertTrue(excluded_urls.url_disabled("/healthzz"))
self.assertTrue(excluded_urls.url_disabled("/path"))
self.assertTrue(excluded_urls.url_disabled("/issues/123/view"))
self.assertFalse(excluded_urls.url_disabled("/issues"))
self.assertFalse(excluded_urls.url_disabled("/hello"))
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
# limitations under the License.

import unittest
from unittest import mock

from opentelemetry.util import ExcludeList
from opentelemetry.configuration import ExcludeList


class TestExcludeList(unittest.TestCase):
Expand Down
6 changes: 5 additions & 1 deletion opentelemetry-instrumentation/tests/test_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def test_ctor(self):
"measures the duration of the outbound HTTP request",
)

def test_ctor_types(self):
def test_ctor_type_client(self):
meter = metrics_api.get_meter(__name__)
recorder = HTTPMetricRecorder(meter, HTTPMetricType.CLIENT)
self.assertEqual(recorder._http_type, HTTPMetricType.CLIENT)
Expand All @@ -81,13 +81,17 @@ def test_ctor_types(self):
)
self.assertIsNone(recorder._server_duration)

def test_ctor_type_server(self):
meter = metrics_api.get_meter(__name__)
recorder = HTTPMetricRecorder(meter, HTTPMetricType.SERVER)
self.assertEqual(recorder._http_type, HTTPMetricType.SERVER)
self.assertTrue(
isinstance(recorder._server_duration, metrics.ValueRecorder)
)
self.assertIsNone(recorder._client_duration)

def test_ctor_type_both(self):
meter = metrics_api.get_meter(__name__)
recorder = HTTPMetricRecorder(meter, HTTPMetricType.BOTH)
self.assertEqual(recorder._http_type, HTTPMetricType.BOTH)
self.assertTrue(
Expand Down
2 changes: 2 additions & 0 deletions opentelemetry-sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- Add meter reference to observers
([#1425](https://github.com/open-telemetry/opentelemetry-python/pull/1425))
- Add local/remote samplers to parent based sampler
([#1440](https://github.com/open-telemetry/opentelemetry-python/pull/1440))
- Add `fields` to propagators
([#1374](https://github.com/open-telemetry/opentelemetry-python/pull/1374))

Expand Down
Loading