Skip to content

Commit

Permalink
chore: update charm libraries (#290)
Browse files Browse the repository at this point in the history
Co-authored-by: Github Actions <github-actions@github.com>
  • Loading branch information
observability-noctua-bot and Github Actions authored Mar 19, 2024
1 parent 9a4ff05 commit 8dbe578
Show file tree
Hide file tree
Showing 6 changed files with 256 additions and 170 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
from ops.charm import CharmBase, RelationJoinedEvent
from ops.main import main
from lib.charms.certificate_transfer_interface.v0.certificate_transfer import CertificateTransferProvides # noqa: E501 W505
from lib.charms.certificate_transfer_interface.v0.certificate_transfer import(
CertificateTransferProvides,
)
class DummyCertificateTransferProviderCharm(CharmBase):
Expand All @@ -36,7 +38,9 @@ def _on_certificates_relation_joined(self, event: RelationJoinedEvent):
certificate = "my certificate"
ca = "my CA certificate"
chain = ["certificate 1", "certificate 2"]
self.certificate_transfer.set_certificate(certificate=certificate, ca=ca, chain=chain, relation_id=event.relation.id)
self.certificate_transfer.set_certificate(
certificate=certificate, ca=ca, chain=chain, relation_id=event.relation.id
)
if __name__ == "__main__":
Expand Down Expand Up @@ -95,7 +99,7 @@ def _on_certificate_removed(self, event: CertificateRemovedEvent):

import json
import logging
from typing import List
from typing import List, Mapping

from jsonschema import exceptions, validate # type: ignore[import-untyped]
from ops.charm import CharmBase, CharmEvents, RelationBrokenEvent, RelationChangedEvent
Expand All @@ -109,7 +113,7 @@ def _on_certificate_removed(self, event: CertificateRemovedEvent):

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

PYDEPS = ["jsonschema"]

Expand Down Expand Up @@ -210,7 +214,7 @@ def restore(self, snapshot: dict):
self.relation_id = snapshot["relation_id"]


def _load_relation_data(raw_relation_data: dict) -> dict:
def _load_relation_data(raw_relation_data: Mapping[str, str]) -> dict:
"""Load relation data from the relation data bag.
Args:
Expand Down Expand Up @@ -313,7 +317,7 @@ def remove_certificate(self, relation_id: int) -> None:
class CertificateTransferRequires(Object):
"""TLS certificates requirer class to be instantiated by TLS certificates requirers."""

on = CertificateTransferRequirerCharmEvents()
on = CertificateTransferRequirerCharmEvents() # type: ignore

def __init__(
self,
Expand Down Expand Up @@ -379,7 +383,7 @@ def _on_relation_changed(self, event: RelationChangedEvent) -> None:
)

def _on_relation_broken(self, event: RelationBrokenEvent) -> None:
"""Handler triggered on relation broken event.
"""Handle relation broken event.
Args:
event: Juju event
Expand Down
5 changes: 1 addition & 4 deletions lib/charms/hydra/v0/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def _set_client_config(self):

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

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -395,9 +395,6 @@ def _on_relation_broken_event(self, event: RelationBrokenEvent) -> None:
self.on.oauth_info_removed.emit()

def _on_relation_changed_event(self, event: RelationChangedEvent) -> None:
if not self.model.unit.is_leader():
return

data = event.relation.data[event.app]
if not data:
logger.info("No relation data available.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def setUp(self, *unused):

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


_Decimal = Union[Decimal, float, str, int] # types that are potentially convertible to Decimal
Expand Down Expand Up @@ -364,7 +364,7 @@ def is_patched(self, resource_reqs: ResourceRequirements) -> bool:
Returns:
bool: A boolean indicating if the service patch has been applied.
"""
return equals_canonically(self.get_templated(), resource_reqs)
return equals_canonically(self.get_templated(), resource_reqs) # pyright: ignore

def get_templated(self) -> Optional[ResourceRequirements]:
"""Returns the resource limits specified in the StatefulSet template."""
Expand Down Expand Up @@ -397,8 +397,8 @@ def is_ready(self, pod_name, resource_reqs: ResourceRequirements):
self.get_templated(),
self.get_actual(pod_name),
)
return self.is_patched(resource_reqs) and equals_canonically(
resource_reqs, self.get_actual(pod_name)
return self.is_patched(resource_reqs) and equals_canonically( # pyright: ignore
resource_reqs, self.get_actual(pod_name) # pyright: ignore
)

def apply(self, resource_reqs: ResourceRequirements) -> None:
Expand Down
16 changes: 5 additions & 11 deletions lib/charms/tempo_k8s/v1/charm_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def my_tracing_endpoint(self) -> Optional[str]:
# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version

LIBPATCH = 1
LIBPATCH = 2

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

Expand Down Expand Up @@ -200,15 +200,12 @@ def _get_tracer() -> Optional[Tracer]:
return tracer.get()
except LookupError:
try:
logger.debug("tracer was not found in context variable, looking up in default context")
ctx: Context = copy_context()
if context_tracer := _get_tracer_from_context(ctx):
return context_tracer.get()
else:
logger.debug("Couldn't find context var for tracer: span will be skipped")
return None
except LookupError as err:
logger.debug(f"Couldn't find tracer: span will be skipped, err: {err}")
return None


Expand All @@ -219,7 +216,6 @@ def _span(name: str) -> Generator[Optional[Span], Any, Any]:
with tracer.start_as_current_span(name) as span:
yield cast(Span, span)
else:
logger.debug("tracer not found")
yield None


Expand All @@ -243,9 +239,9 @@ def _get_tracing_endpoint(tracing_endpoint_getter, self, charm):
tracing_endpoint = tracing_endpoint_getter(self)

if tracing_endpoint is None:
logger.warning(
f"{charm}.{getattr(tracing_endpoint_getter, '__qualname__', str(tracing_endpoint_getter))} "
f"returned None; continuing with tracing DISABLED."
logger.debug(
"Charm tracing is disabled. Tracing endpoint is not defined - "
"tracing is not available or relation is not set."
)
return
elif not isinstance(tracing_endpoint, str):
Expand All @@ -266,15 +262,14 @@ def _get_server_cert(server_cert_getter, self, charm):

if server_cert is None:
logger.warning(
f"{charm}.{server_cert_getter} returned None; continuing with INSECURE connection."
f"{charm}.{server_cert_getter} returned None; sending traces over INSECURE connection."
)
return
elif not Path(server_cert).is_absolute():
raise ValueError(
f"{charm}.{server_cert_getter} should return a valid tls cert absolute path (string | Path)); "
f"got {server_cert} instead."
)
logger.debug("Certificate successfully retrieved.") # todo: some more validation?
return server_cert


Expand All @@ -300,7 +295,6 @@ def wrap_init(self: CharmBase, framework: Framework, *args, **kwargs):

original_event_context = framework._event_context

logging.debug("Initializing opentelemetry tracer...")
_service_name = service_name or self.app.name

resource = Resource.create(
Expand Down
16 changes: 10 additions & 6 deletions lib/charms/tempo_k8s/v1/tracing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2022 Pietro Pasotti
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""## Overview.
Expand Down Expand Up @@ -93,7 +93,7 @@ def __init__(self, *args):

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

PYDEPS = ["pydantic>=2"]

Expand Down Expand Up @@ -151,8 +151,12 @@ def load(cls, databag: MutableMapping):
try:
return cls.parse_raw(json.dumps(data)) # type: ignore
except pydantic.ValidationError as e:
msg = f"failed to validate databag: {databag}"
logger.error(msg, exc_info=True)
if not data:
# databag is empty; this is usually expected
raise DataValidationError("empty databag")

msg = f"failed to validate databag contents: {data!r} as {cls}"
logger.debug(msg, exc_info=True)
raise DataValidationError(msg) from e

def dump(self, databag: Optional[MutableMapping] = None, clear: bool = True):
Expand Down Expand Up @@ -194,8 +198,8 @@ class TracingProviderAppData(DatabagModel): # noqa: D101


class _AutoSnapshotEvent(RelationEvent):
__args__ = () # type: Tuple[str, ...]
__optional_kwargs__ = {} # type: Dict[str, Any]
__args__: Tuple[str, ...] = ()
__optional_kwargs__: Dict[str, Any] = {}

@classmethod
def __attrs__(cls):
Expand Down
Loading

0 comments on commit 8dbe578

Please sign in to comment.