Skip to content

Commit

Permalink
chore: update charm libraries
Browse files Browse the repository at this point in the history
  • Loading branch information
Github Actions committed Nov 15, 2023
1 parent 37ab2b7 commit 5efaebb
Show file tree
Hide file tree
Showing 5 changed files with 195 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def _on_certificate_removed(self, event: CertificateRemovedEvent):
import logging
from typing import List

from jsonschema import exceptions, validate # type: ignore[import]
from jsonschema import exceptions, validate # type: ignore[import-untyped]
from ops.charm import CharmBase, CharmEvents, RelationBrokenEvent, RelationChangedEvent
from ops.framework import EventBase, EventSource, Handle, Object

Expand All @@ -109,7 +109,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 = 4
LIBPATCH = 5

PYDEPS = ["jsonschema"]

Expand Down
64 changes: 41 additions & 23 deletions lib/charms/grafana_cloud_integrator/v0/cloud_config_requirer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

LIBID = "e6f580481c1b4388aa4d2cdf412a47fa"
LIBAPI = 0
LIBPATCH = 3
LIBPATCH = 4

DEFAULT_RELATION_NAME = "grafana-cloud-config"

Expand Down Expand Up @@ -45,7 +45,7 @@ def __init__(self, charm, relation_name = DEFAULT_RELATION_NAME):
super().__init__(charm, relation_name)
self._charm = charm
self._relation_name = relation_name

for event in self._change_events:
self.framework.observe(event, self._on_relation_changed)

Expand All @@ -56,14 +56,6 @@ def _on_relation_changed(self, event):
if not self._charm.unit.is_leader():
return

if not all(
self._is_not_empty(x)
for x in [
event.relation.data[event.app].get("username", ""),
event.relation.data[event.app].get("password", ""),
]):
return

self.on.cloud_config_available.emit() # pyright: ignore

def _on_relation_broken(self, event):
Expand Down Expand Up @@ -96,29 +88,55 @@ def _events(self):

@property
def credentials(self):
return Credentials(
self._data.get("username", ""),
self._data.get("password", "")
)
"""Return the credentials, if any; otherwise, return None."""
if not all(
self._is_not_empty(x)
for x in [
self._data.get("username", ""),
self._data.get("password", ""),
]):
return Credentials(
self._data.get("username", ""),
self._data.get("password", "")
)
return None

@property
def loki_ready(self):
return (
self._is_not_empty(self.credentials.username)
and self._is_not_empty(self.credentials.password)
and self._is_not_empty(self.loki_url))
return self._is_not_empty(self.loki_url)

@property
def loki_endpoint(self) -> dict:
"""Return the loki endpoint dict."""
if not self.loki_ready:
return {}

endpoint = {}
endpoint["url"] = self.loki_url
if self.credentials:
endpoint["basic_auth"] = {"username": self.credentials.username, "password": self.credentials.password}
return endpoint

@property
def prometheus_ready(self):
return (
self._is_not_empty(self.credentials.username)
and self._is_not_empty(self.credentials.password)
and self._is_not_empty(self.prometheus_url))
return self._is_not_empty(self.prometheus_url)

@property
def prometheus_endpoint(self) -> dict:
"""Return the prometheus endpoint dict."""
if not self.prometheus_ready:
return {}

endpoint = {}
endpoint["url"] = self.prometheus_url
if self.credentials:
endpoint["basic_auth"] = {"username": self.credentials.username, "password": self.credentials.password}
return endpoint

@property
def loki_url(self):
return self._data.get("loki_url", "")

@property
def prometheus_url(self):
return self._data.get("prometheus_url", "")
Expand Down
14 changes: 12 additions & 2 deletions lib/charms/loki_k8s/v0/loki_push_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,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 = 21
LIBPATCH = 22

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -1773,6 +1773,8 @@ def __init__(
recursive: bool = False,
container_name: str = "",
promtail_resource_name: Optional[str] = None,
*, # TODO: In v1, move the star up so everything after 'charm' is a kwarg
insecure_skip_verify: bool = False,
):
super().__init__(charm, relation_name, alert_rules_path, recursive)
self._charm = charm
Expand All @@ -1792,6 +1794,7 @@ def __init__(
self._is_syslog = enable_syslog
self.topology = JujuTopology.from_charm(charm)
self._promtail_resource_name = promtail_resource_name or "promtail-bin"
self.insecure_skip_verify = insecure_skip_verify

# architecture used for promtail binary
arch = platform.processor()
Expand Down Expand Up @@ -2153,8 +2156,15 @@ def _current_config(self) -> dict:

@property
def _promtail_config(self) -> dict:
"""Generates the config file for Promtail."""
"""Generates the config file for Promtail.
Reference: https://grafana.com/docs/loki/latest/send-data/promtail/configuration
"""
config = {"clients": self._clients_list()}
if self.insecure_skip_verify:
for client in config["clients"]:
client["tls_config"] = {"insecure_skip_verify": True}

config.update(self._server_config())
config.update(self._positions())
config.update(self._scrape_configs())
Expand Down
38 changes: 25 additions & 13 deletions lib/charms/observability_libs/v0/cert_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@

LIBID = "b5cd5cd580f3428fa5f59a8876dcbe6a"
LIBAPI = 0
LIBPATCH = 8
LIBPATCH = 9


def is_ip_address(value: str) -> bool:
Expand Down Expand Up @@ -181,33 +181,40 @@ def _peer_relation(self) -> Optional[Relation]:
return self.charm.model.get_relation(self.peer_relation_name, None)

def _on_peer_relation_created(self, _):
"""Generate the private key and store it in a peer relation."""
# We're in "relation-created", so the relation should be there
"""Generate the CSR if the certificates relation is ready."""
self._generate_privkey()

# Just in case we already have a private key, do not overwrite it.
# Not sure how this could happen.
# TODO figure out how to go about key rotation.
if not self._private_key:
private_key = generate_private_key()
self._private_key = private_key.decode()

# Generate CSR here, in case peer events fired after tls-certificate relation events
# check cert relation is ready
if not (self.charm.model.get_relation(self.certificates_relation_name)):
# peer relation event happened to fire before tls-certificates events.
# Abort, and let the "certificates joined" observer create the CSR.
logger.info("certhandler waiting on certificates relation")
return

logger.debug("certhandler has peer and certs relation: proceeding to generate csr")
self._generate_csr()

def _on_certificates_relation_joined(self, _) -> None:
"""Generate the CSR and request the certificate creation."""
"""Generate the CSR if the peer relation is ready."""
self._generate_privkey()

# check peer relation is there
if not self._peer_relation:
# tls-certificates relation event happened to fire before peer events.
# Abort, and let the "peer joined" relation create the CSR.
logger.info("certhandler waiting on peer relation")
return

logger.debug("certhandler has peer and certs relation: proceeding to generate csr")
self._generate_csr()

def _generate_privkey(self):
# Generate priv key unless done already
# TODO figure out how to go about key rotation.
if not self._private_key:
private_key = generate_private_key()
self._private_key = private_key.decode()

def _on_config_changed(self, _):
# FIXME on config changed, the web_external_url may or may not change. But because every
# call to `generate_csr` appends a uuid, CSRs cannot be easily compared to one another.
Expand Down Expand Up @@ -237,7 +244,12 @@ def _generate_csr(
# In case we already have a csr, do not overwrite it by default.
if overwrite or renew or not self._csr:
private_key = self._private_key
assert private_key is not None # for type checker
if private_key is None:
# FIXME: raise this in a less nested scope by
# generating privkey and csr in the same method.
raise RuntimeError(
"private key unset. call _generate_privkey() before you call this method."
)
csr = generate_csr(
private_key=private_key.encode(),
subject=self.cert_subject,
Expand Down
Loading

0 comments on commit 5efaebb

Please sign in to comment.