Skip to content

Commit

Permalink
Update charm libraries (#549)
Browse files Browse the repository at this point in the history
* chore: update charm libraries

* triggering CI

* fix static analysis and fmt

---------

Co-authored-by: Github Actions <[email protected]>
Co-authored-by: Luca Bello <[email protected]>
  • Loading branch information
3 people authored Jan 2, 2024
1 parent d29f323 commit 3accbee
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def setUp(self, *unused):
from math import ceil, floor
from typing import Callable, Dict, List, Optional, Union

from lightkube import ApiError, Client
from lightkube import ApiError, Client # pyright: ignore
from lightkube.core import exceptions
from lightkube.models.apps_v1 import StatefulSetSpec
from lightkube.models.core_v1 import (
Expand All @@ -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 = 4
LIBPATCH = 5


_Decimal = Union[Decimal, float, str, int] # types that are potentially convertible to Decimal
Expand Down Expand Up @@ -322,7 +322,7 @@ def __init__(self, namespace: str, statefulset_name: str, container_name: str):
self.namespace = namespace
self.statefulset_name = statefulset_name
self.container_name = container_name
self.client = Client()
self.client = Client() # pyright: ignore

def _patched_delta(self, resource_reqs: ResourceRequirements) -> StatefulSet:
statefulset = self.client.get(
Expand Down Expand Up @@ -421,7 +421,7 @@ def apply(self, resource_reqs: ResourceRequirements) -> None:
class KubernetesComputeResourcesPatch(Object):
"""A utility for patching the Kubernetes compute resources set up by Juju."""

on = K8sResourcePatchEvents()
on = K8sResourcePatchEvents() # pyright: ignore

def __init__(
self,
Expand Down
4 changes: 2 additions & 2 deletions lib/charms/tempo_k8s/v0/tracing.py
Original file line number Diff line number Diff line change
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 = 7
LIBPATCH = 8

PYDEPS = ["pydantic<2.0"]

Expand Down Expand Up @@ -494,7 +494,7 @@ def is_ready(self, relation: Optional[Relation] = None):
return False
try:
TracingProviderAppData.load(relation.data[relation.app])
except (json.JSONDecodeError, pydantic.ValidationError):
except (json.JSONDecodeError, pydantic.ValidationError, DataValidationError):
logger.info(f"failed validating relation data for {relation}")
return False
return True
Expand Down
50 changes: 35 additions & 15 deletions lib/charms/tls_certificates_interface/v2/tls_certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def _on_all_certificates_invalidated(self, event: AllCertificatesInvalidatedEven
)
from ops.framework import EventBase, EventSource, Handle, Object
from ops.jujuversion import JujuVersion
from ops.model import Relation, SecretNotFoundError
from ops.model import ModelError, Relation, RelationDataContent, SecretNotFoundError

# The unique Charmhub library identifier, never change it
LIBID = "afd8c2bccf834997afce12c2706d2ede"
Expand All @@ -308,7 +308,7 @@ def _on_all_certificates_invalidated(self, event: AllCertificatesInvalidatedEven

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

PYDEPS = ["cryptography", "jsonschema"]

Expand Down Expand Up @@ -600,23 +600,26 @@ def restore(self, snapshot: dict):
self.chain = snapshot["chain"]


def _load_relation_data(raw_relation_data: dict) -> dict:
def _load_relation_data(relation_data_content: RelationDataContent) -> dict:
"""Loads relation data from the relation data bag.
Json loads all data.
Args:
raw_relation_data: Relation data from the databag
relation_data_content: Relation data from the databag
Returns:
dict: Relation data in dict format.
"""
certificate_data = dict()
for key in raw_relation_data:
try:
certificate_data[key] = json.loads(raw_relation_data[key])
except (json.decoder.JSONDecodeError, TypeError):
certificate_data[key] = raw_relation_data[key]
try:
for key in relation_data_content:
try:
certificate_data[key] = json.loads(relation_data_content[key])
except (json.decoder.JSONDecodeError, TypeError):
certificate_data[key] = relation_data_content[key]
except ModelError:
pass
return certificate_data


Expand Down Expand Up @@ -1257,12 +1260,24 @@ def _revoke_certificates_for_which_no_csr_exists(self, relation_id: int) -> None
)
self.remove_certificate(certificate=certificate["certificate"])

def get_requirer_csrs_with_no_certs(
def get_outstanding_certificate_requests(
self, relation_id: Optional[int] = None
) -> List[Dict[str, Union[int, str, List[Dict[str, str]]]]]:
"""Filters the requirer's units csrs.
"""Returns CSR's for which no certificate has been issued.
Keeps the ones for which no certificate was provided.
Example return: [
{
"relation_id": 0,
"application_name": "tls-certificates-requirer",
"unit_name": "tls-certificates-requirer/0",
"unit_csrs": [
{
"certificate_signing_request": "-----BEGIN CERTIFICATE REQUEST-----...",
"is_ca": false
}
]
}
]
Args:
relation_id (int): Relation id
Expand All @@ -1279,6 +1294,7 @@ def get_requirer_csrs_with_no_certs(
if not self.certificate_issued_for_csr(
app_name=unit_csr_mapping["application_name"], # type: ignore[arg-type]
csr=csr["certificate_signing_request"], # type: ignore[index]
relation_id=relation_id,
):
csrs_without_certs.append(csr)
if csrs_without_certs:
Expand Down Expand Up @@ -1325,17 +1341,21 @@ def get_requirer_csrs(
)
return unit_csr_mappings

def certificate_issued_for_csr(self, app_name: str, csr: str) -> bool:
def certificate_issued_for_csr(
self, app_name: str, csr: str, relation_id: Optional[int]
) -> bool:
"""Checks whether a certificate has been issued for a given CSR.
Args:
app_name (str): Application name that the CSR belongs to.
csr (str): Certificate Signing Request.
relation_id (Optional[int]): Relation ID
Returns:
bool: True/False depending on whether a certificate has been issued for the given CSR.
"""
issued_certificates_per_csr = self.get_issued_certificates()[app_name]
issued_certificates_per_csr = self.get_issued_certificates(relation_id=relation_id)[
app_name
]
for issued_pair in issued_certificates_per_csr:
if "csr" in issued_pair and issued_pair["csr"] == csr:
return csr_matches_certificate(csr, issued_pair["certificate"])
Expand Down
3 changes: 2 additions & 1 deletion lib/charms/traefik_k8s/v1/ingress_per_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _on_ingress_revoked(self, event: IngressPerUnitRevokedForUnitEvent):

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

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -254,6 +254,7 @@ def __init__(self, charm: CharmBase, relation_name: str = DEFAULT_RELATION_NAME)
observe(rel_events.relation_created, self._handle_relation)
observe(rel_events.relation_joined, self._handle_relation)
observe(rel_events.relation_changed, self._handle_relation)
observe(rel_events.relation_departed, self._handle_relation)
observe(rel_events.relation_broken, self._handle_relation_broken)
observe(charm.on.leader_elected, self._handle_upgrade_or_leader) # type: ignore
observe(charm.on.upgrade_charm, self._handle_upgrade_or_leader) # type: ignore
Expand Down
6 changes: 4 additions & 2 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,7 @@ def _get_pvc_capacity(self) -> str:
pvc_name = ""
for volume in cast(
Pod, client.get(Pod, name=pod_name, namespace=self.model.name)
).spec.volumes:
).spec.volumes: # pyright: ignore
if not volume.persistentVolumeClaim:
# The volumes 'charm-data' and 'kube-api-access-xxxxx' do not have PVCs - filter
# those out.
Expand All @@ -776,7 +776,9 @@ def _get_pvc_capacity(self) -> str:
capacity = cast(
PersistentVolumeClaim,
client.get(PersistentVolumeClaim, name=pvc_name, namespace=namespace),
).status.capacity["storage"]
).status.capacity[ # pyright: ignore
"storage"
]

# The other kind of storage to query for is
# client.get(...).spec.resources.requests["storage"]
Expand Down

0 comments on commit 3accbee

Please sign in to comment.