-
Notifications
You must be signed in to change notification settings - Fork 7
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
python configuration prototype #44
Closed
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f6054e5
python config prototype
54f5255
a few ergonomics changes
d7e9916
more work to get prototype working
c3006c9
change object to array
a0f95ed
use entry points where possible
e123d14
update prototype to test out otlp, added insecure field
bacb1d4
add meter provider configuration
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.venv |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
# JSON Schema validation with Python | ||
|
||
The code in this directory shows an example of using `jsonschema` for validation in combination with `pyyaml` YAML parser in Python. | ||
Usage: | ||
|
||
```bash | ||
python3 -m venv .venv | ||
source .venv/bin/activate | ||
pip install -r requirements.txt | ||
python prototype.py ../../config.yaml ../../json_schema/schema/schema.json | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
|
||
import logging | ||
from typing import List, Sequence, Tuple | ||
from pkg_resources import iter_entry_points | ||
|
||
|
||
import yaml | ||
from pathlib import Path | ||
from jsonschema import validate, validators | ||
from jsonschema.exceptions import ValidationError | ||
|
||
from opentelemetry.metrics import set_meter_provider | ||
from opentelemetry.trace import set_tracer_provider | ||
from opentelemetry.sdk.trace.export import SpanExporter | ||
from opentelemetry.sdk.metrics.export import MetricExporter | ||
|
||
|
||
# borromed from opentelemetry/sdk/_configuration | ||
def _import_config_component( | ||
selected_component: str, entry_point_name: str | ||
) -> object: | ||
component_entry_points = { | ||
ep.name: ep for ep in iter_entry_points(entry_point_name) | ||
} | ||
entry_point = component_entry_points.get(selected_component, None) | ||
if not entry_point: | ||
raise RuntimeError( | ||
f"Requested component '{selected_component}' not found in entry points for '{entry_point_name}'" | ||
) | ||
|
||
return entry_point.load() | ||
|
||
class Config: | ||
def __init__(self, config=None) -> None: | ||
self._config = config | ||
|
||
def _resource(self): | ||
# resource detection | ||
# attributes | ||
from opentelemetry.sdk.resources import Resource | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why import here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. not necessary to have the import in the method, that was just me being lazy |
||
return Resource.create(self._config.get("sdk").get("resource").get("attributes")) | ||
|
||
# _get_exporter returns an exporter class for the signal | ||
def _get_exporter(self, signal: str, name: str): | ||
if name not in self._config.get("sdk").get(signal).get("exporters"): | ||
raise Exception(f"exporter {name} not specified for {signal} signal") | ||
|
||
exporter = _import_config_component(name, f"opentelemetry_{signal}_exporter") | ||
if signal == "metrics": | ||
cls_type = MetricExporter | ||
elif signal == "traces": | ||
cls_type = SpanExporter | ||
elif signal == "logs": | ||
cls_type = SpanExporter | ||
if issubclass(exporter, cls_type): | ||
if self._config.get("sdk").get(signal).get("exporters").get(name) is not None: | ||
return exporter(**self._config.get("sdk").get(signal).get("exporters").get(name)) | ||
return exporter() | ||
raise RuntimeError(f"{name} is not a {signal} exporter") | ||
|
||
def configure_tracing(self, cfg): | ||
if cfg is None: | ||
return | ||
from opentelemetry.sdk.trace import TracerProvider | ||
provider = TracerProvider(resource=self._resource()) | ||
from opentelemetry.sdk.trace.export import BatchSpanProcessor | ||
|
||
for processor in cfg.get("span_processors"): | ||
logging.debug("adding span processor %s", processor) | ||
try: | ||
processor = BatchSpanProcessor(self._get_exporter("traces", processor.get("args").get("exporter"))) | ||
provider.add_span_processor(processor) | ||
except ModuleNotFoundError as exc: | ||
logging.error("module not found", exc) | ||
set_tracer_provider(provider) | ||
|
||
def configure_metrics(self, cfg): | ||
if cfg is None: | ||
return | ||
from opentelemetry.sdk.metrics import MeterProvider | ||
readers = [] | ||
for reader in cfg.get("metric_readers"): | ||
if reader.get("type") == "periodic": | ||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader | ||
readers.append(PeriodicExportingMetricReader(self._get_exporter("metrics", reader.get("args").get("exporter")))) | ||
provider = MeterProvider(resource=self._resource(), metric_readers=readers) | ||
set_meter_provider(provider) | ||
|
||
def apply(self): | ||
logging.debug("applying configuration %s", self._config) | ||
if self._config is None or self._config.get("sdk").get("disabled"): | ||
logging.debug("sdk disabled, nothing to apply") | ||
return | ||
self.configure_tracing(self._config.get("sdk").get("traces")) | ||
self.configure_metrics(self._config.get("sdk").get("metrics")) | ||
|
||
|
||
NoOpConfig = Config() | ||
|
||
def configure(configuration: Config) -> None: | ||
configuration.apply() | ||
|
||
def parse_and_validate_from_config_file(filename: str, schema: str="../schema/schema.json") -> Config: | ||
logging.debug(f"Loading config file: {filename}") | ||
path = Path(__file__).parent.resolve() | ||
resolver = validators.RefResolver( | ||
base_uri=f"{path.as_uri()}/", | ||
referrer=True, | ||
) | ||
|
||
with open(filename, "r") as stream: | ||
try: | ||
parse_config = yaml.safe_load(stream) | ||
logging.debug("YAML parsed successfully") | ||
logging.debug(f"Validating using schema file: {schema}") | ||
validate( | ||
instance=parse_config, | ||
schema={"$ref": schema}, | ||
resolver=resolver, | ||
) | ||
logging.debug("No validation errors") | ||
return Config(parse_config) | ||
except yaml.YAMLError as exc: | ||
logging.error(exc) | ||
except ValidationError as exc: | ||
logging.error(exc) | ||
return NoOpConfig |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
#!/usr/bin/env python3 | ||
|
||
import logging | ||
import sys | ||
|
||
from opentelemetry.trace import get_tracer | ||
from opentelemetry.metrics import get_meter | ||
|
||
import otel | ||
|
||
|
||
def main(): | ||
logging.basicConfig(level=logging.DEBUG) | ||
otel.configure(otel.parse_and_validate_from_config_file(sys.argv[1], sys.argv[2])) | ||
|
||
tracer = get_tracer("config-prototype") | ||
meter = get_meter("config-prototype") | ||
|
||
counter = meter.create_counter("work", unit="1") | ||
|
||
with tracer.start_as_current_span("operation-a"): | ||
with tracer.start_as_current_span("operation-b"): | ||
with tracer.start_as_current_span("operation-c"): | ||
logging.debug("you should see telemetry after this line") | ||
counter.add(1) | ||
|
||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
jsonschema | ||
pyyaml | ||
opentelemetry-api | ||
opentelemetry-sdk | ||
opentelemetry-exporter-otlp | ||
opentelemetry-exporter-jaeger | ||
opentelemetry-exporter-zipkin |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pkg_resources
has been deprecated (see this, and also this).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah good to know. It's probably ok for the prototype but wouldn't want to ship this code :D