Skip to content

Commit

Permalink
[DPE-5312] Update tracing charm libs to retrieve them from tempo coor…
Browse files Browse the repository at this point in the history
…dinator repo (#324)

## Issue
There are a bunch of tempo tracing related updates:
1. tempo-k8s has been deprecated in favor of tempo ha
2. tracing charm libs need to be fetch-ed from tempo_coordinator_k8s
3. tracing traffic is now relayed through grafana-agent-k8s (like the
remaining COS traffic)

## Solution
2. update tracing charm libs from new repo
Test integration with tempo ha + test relay of traffic through
grafana-agent-k8s

## To be done simultaneously
Update mysql-router-k8s tracing related documentation (in progress)
  • Loading branch information
shayancanonical authored Oct 15, 2024
1 parent 1e2ded4 commit 8fe759b
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 42 deletions.
21 changes: 20 additions & 1 deletion lib/charms/data_platform_libs/v0/data_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def _on_topic_requested(self, event: TopicRequestedEvent):

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 39
LIBPATCH = 40

PYDEPS = ["ops>=2.0.0"]

Expand Down Expand Up @@ -391,6 +391,10 @@ class IllegalOperationError(DataInterfacesError):
"""To be used when an operation is not allowed to be performed."""


class PrematureDataAccessError(DataInterfacesError):
"""To be raised when the Relation Data may be accessed (written) before protocol init complete."""


##############################################################################
# Global helpers / utilities
##############################################################################
Expand Down Expand Up @@ -1453,6 +1457,8 @@ def _on_relation_changed_event(self, event: RelationChangedEvent) -> None:
class ProviderData(Data):
"""Base provides-side of the data products relation."""

RESOURCE_FIELD = "database"

def __init__(
self,
model: Model,
Expand Down Expand Up @@ -1618,6 +1624,15 @@ def _fetch_my_specific_relation_data(
def _update_relation_data(self, relation: Relation, data: Dict[str, str]) -> None:
"""Set values for fields not caring whether it's a secret or not."""
req_secret_fields = []

keys = set(data.keys())
if self.fetch_relation_field(relation.id, self.RESOURCE_FIELD) is None and (
keys - {"endpoints", "read-only-endpoints", "replset"}
):
raise PrematureDataAccessError(
"Premature access to relation data, update is forbidden before the connection is initialized."
)

if relation.app:
req_secret_fields = get_encoded_list(relation, relation.app, REQ_SECRET_FIELDS)

Expand Down Expand Up @@ -3290,6 +3305,8 @@ class KafkaRequiresEvents(CharmEvents):
class KafkaProviderData(ProviderData):
"""Provider-side of the Kafka relation."""

RESOURCE_FIELD = "topic"

def __init__(self, model: Model, relation_name: str) -> None:
super().__init__(model, relation_name)

Expand Down Expand Up @@ -3539,6 +3556,8 @@ class OpenSearchRequiresEvents(CharmEvents):
class OpenSearchProvidesData(ProviderData):
"""Provider-side of the OpenSearch relation."""

RESOURCE_FIELD = "index"

def __init__(self, model: Model, relation_name: str) -> None:
super().__init__(model, relation_name)

Expand Down
81 changes: 76 additions & 5 deletions lib/charms/loki_k8s/v1/loki_push_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,25 @@ def _alert_rules_error(self, event):
Units of consumer charm send their alert rules over app relation data using the `alert_rules`
key.
## Charm logging
The `charms.loki_k8s.v0.charm_logging` library can be used in conjunction with this one to configure python's
logging module to forward all logs to Loki via the loki-push-api interface.
```python
from lib.charms.loki_k8s.v0.charm_logging import log_charm
from lib.charms.loki_k8s.v1.loki_push_api import charm_logging_config, LokiPushApiConsumer
@log_charm(logging_endpoint="my_endpoints", server_cert="cert_path")
class MyCharm(...):
_cert_path = "/path/to/cert/on/charm/container.crt"
def __init__(self, ...):
self.logging = LokiPushApiConsumer(...)
self.my_endpoints, self.cert_path = charm_logging_config(
self.logging, self._cert_path)
```
Do this, and all charm logs will be forwarded to Loki as soon as a relation is formed.
"""

import json
Expand Down Expand Up @@ -527,7 +546,7 @@ def _alert_rules_error(self, event):

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 12
LIBPATCH = 13

PYDEPS = ["cosl"]

Expand Down Expand Up @@ -577,7 +596,11 @@ def _alert_rules_error(self, event):
GRPC_LISTEN_PORT_START = 9095 # odd start port


class RelationNotFoundError(ValueError):
class LokiPushApiError(Exception):
"""Base class for errors raised by this module."""


class RelationNotFoundError(LokiPushApiError):
"""Raised if there is no relation with the given name."""

def __init__(self, relation_name: str):
Expand All @@ -587,7 +610,7 @@ def __init__(self, relation_name: str):
super().__init__(self.message)


class RelationInterfaceMismatchError(Exception):
class RelationInterfaceMismatchError(LokiPushApiError):
"""Raised if the relation with the given name has a different interface."""

def __init__(
Expand All @@ -607,7 +630,7 @@ def __init__(
super().__init__(self.message)


class RelationRoleMismatchError(Exception):
class RelationRoleMismatchError(LokiPushApiError):
"""Raised if the relation with the given name has a different direction."""

def __init__(
Expand Down Expand Up @@ -2555,7 +2578,7 @@ def _on_pebble_ready(self, event: PebbleReadyEvent):

self._update_endpoints(event.workload, loki_endpoints)

def _update_logging(self, _):
def _update_logging(self, event: RelationEvent):
"""Update the log forwarding to match the active Loki endpoints."""
if not (loki_endpoints := self._retrieve_endpoints_from_relation()):
logger.warning("No Loki endpoints available")
Expand All @@ -2566,6 +2589,8 @@ def _update_logging(self, _):
self._update_endpoints(container, loki_endpoints)
# else: `_update_endpoints` will be called on pebble-ready anyway.

self._handle_alert_rules(event.relation)

def _retrieve_endpoints_from_relation(self) -> dict:
loki_endpoints = {}

Expand Down Expand Up @@ -2750,3 +2775,49 @@ def _exec(self, cmd) -> str:
result = subprocess.run(cmd, check=True, stdout=subprocess.PIPE)
output = result.stdout.decode("utf-8").strip()
return output


def charm_logging_config(
endpoint_requirer: LokiPushApiConsumer, cert_path: Optional[Union[Path, str]]
) -> Tuple[Optional[List[str]], Optional[str]]:
"""Utility function to determine the charm_logging config you will likely want.
If no endpoint is provided:
disable charm logging.
If https endpoint is provided but cert_path is not found on disk:
disable charm logging.
If https endpoint is provided and cert_path is None:
ERROR
Else:
proceed with charm logging (with or without tls, as appropriate)
Args:
endpoint_requirer: an instance of LokiPushApiConsumer.
cert_path: a path where a cert is stored.
Returns:
A tuple with (optionally) the values of the endpoints and the certificate path.
Raises:
LokiPushApiError: if some endpoint are http and others https.
"""
endpoints = [ep["url"] for ep in endpoint_requirer.loki_endpoints]
if not endpoints:
return None, None

https = tuple(endpoint.startswith("https://") for endpoint in endpoints)

if all(https): # all endpoints are https
if cert_path is None:
raise LokiPushApiError("Cannot send logs to https endpoints without a certificate.")
if not Path(cert_path).exists():
# if endpoints is https BUT we don't have a server_cert yet:
# disable charm logging until we do to prevent tls errors
return None, None
return endpoints, str(cert_path)

if all(not x for x in https): # all endpoints are http
return endpoints, None

# if there's a disagreement, that's very weird:
raise LokiPushApiError("Some endpoints are http, some others are https. That's not good.")
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
# Quickstart
Fetch the following charm libs (and ensure the minimum version/revision numbers are satisfied):
charmcraft fetch-lib charms.tempo_k8s.v2.tracing # >= 1.10
charmcraft fetch-lib charms.tempo_k8s.v1.charm_tracing # >= 2.7
charmcraft fetch-lib charms.tempo_coordinator_k8s.v0.tracing # >= 1.10
charmcraft fetch-lib charms.tempo_coordinator_k8s.v0.charm_tracing # >= 2.7
Then edit your charm code to include:
```python
# import the necessary charm libs
from charms.tempo_k8s.v2.tracing import TracingEndpointRequirer, charm_tracing_config
from charms.tempo_k8s.v1.charm_tracing import charm_tracing
from charms.tempo_coordinator_k8s.v0.tracing import TracingEndpointRequirer, charm_tracing_config
from charms.tempo_coordinator_k8s.v0.charm_tracing import charm_tracing
# decorate your charm class with charm_tracing:
@charm_tracing(
Expand Down Expand Up @@ -51,7 +51,7 @@ def __init__(self, ...):
2) add to your charm a "my_tracing_endpoint" (you can name this attribute whatever you like)
**property**, **method** or **instance attribute** that returns an otlp http/https endpoint url.
If you are using the ``charms.tempo_k8s.v2.tracing.TracingEndpointRequirer`` as
If you are using the ``charms.tempo_coordinator_k8s.v0.tracing.TracingEndpointRequirer`` as
``self.tracing = TracingEndpointRequirer(self)``, the implementation could be:
```
Expand Down Expand Up @@ -80,7 +80,7 @@ def my_tracing_endpoint(self) -> Optional[str]:
For example:
```
from charms.tempo_k8s.v1.charm_tracing import trace_charm
from charms.tempo_coordinator_k8s.v0.charm_tracing import trace_charm
@trace_charm(
tracing_endpoint="my_tracing_endpoint",
server_cert="_server_cert"
Expand Down Expand Up @@ -129,7 +129,7 @@ def get_tracer(self) -> opentelemetry.trace.Tracer:
For example:
```
from charms.tempo_k8s.v0.charm_tracing import trace_charm
from charms.tempo_coordinator_k8s.v0.charm_tracing import trace_charm
@trace_charm(
tracing_endpoint="my_tracing_endpoint",
Expand All @@ -150,7 +150,7 @@ def my_tracing_endpoint(self) -> Optional[str]:
needs to be replaced with:
```
from charms.tempo_k8s.v1.charm_tracing import trace_charm
from charms.tempo_coordinator_k8s.v0.charm_tracing import trace_charm
@trace_charm(
tracing_endpoint="my_tracing_endpoint",
Expand Down Expand Up @@ -249,28 +249,27 @@ def _remove_stale_otel_sdk_packages():
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import Span, TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace import INVALID_SPAN, Tracer
from opentelemetry.trace import get_current_span as otlp_get_current_span
from opentelemetry.trace import (
INVALID_SPAN,
Tracer,
get_tracer,
get_tracer_provider,
set_span_in_context,
set_tracer_provider,
)
from opentelemetry.trace import get_current_span as otlp_get_current_span
from ops.charm import CharmBase
from ops.framework import Framework

# The unique Charmhub library identifier, never change it
LIBID = "cb1705dcd1a14ca09b2e60187d1215c7"
LIBID = "01780f1e588c42c3976d26780fdf9b89"

# Increment this major API version when introducing breaking changes
LIBAPI = 1
LIBAPI = 0

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version

LIBPATCH = 15
LIBPATCH = 1

PYDEPS = ["opentelemetry-exporter-otlp-proto-http==1.21.0"]

Expand Down Expand Up @@ -332,7 +331,7 @@ def _get_tracer() -> Optional[Tracer]:
return tracer.get()
except LookupError:
# fallback: this course-corrects for a user error where charm_tracing symbols are imported
# from different paths (typically charms.tempo_k8s... and lib.charms.tempo_k8s...)
# from different paths (typically charms.tempo_coordinator_k8s... and lib.charms.tempo_coordinator_k8s...)
try:
ctx: Context = copy_context()
if context_tracer := _get_tracer_from_context(ctx):
Expand Down Expand Up @@ -562,8 +561,8 @@ def trace_charm(
method calls on instances of this class.
Usage:
>>> from charms.tempo_k8s.v1.charm_tracing import trace_charm
>>> from charms.tempo_k8s.v1.tracing import TracingEndpointRequirer
>>> from charms.tempo_coordinator_k8s.v0.charm_tracing import trace_charm
>>> from charms.tempo_coordinator_k8s.v0.tracing import TracingEndpointRequirer
>>> from ops import CharmBase
>>>
>>> @trace_charm(
Expand Down Expand Up @@ -626,7 +625,7 @@ def _autoinstrument(
Usage:
>>> from charms.tempo_k8s.v1.charm_tracing import _autoinstrument
>>> from charms.tempo_coordinator_k8s.v0.charm_tracing import _autoinstrument
>>> from ops.main import main
>>> _autoinstrument(
>>> MyCharm,
Expand Down
Loading

0 comments on commit 8fe759b

Please sign in to comment.