Skip to content
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

feat: add grafana_base_url to Grafana source #494

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 30 additions & 9 deletions lib/charms/grafana_k8s/v0/grafana_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,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 = 24
LIBPATCH = 26

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -429,6 +429,27 @@ def update_source(self, source_url: Optional[str] = ""):
continue
self._set_sources(rel)

def get_grafana_base_urls(self) -> Dict[str, str]:
# TODO update docstring
"""Get the grafana external URL assigned by the remote end(s) to this datasource.

Returns a mapping from remote application UIDs to unit names to datasource uids.
"""
urls = {}
for rel in self._charm.model.relations.get(self._relation_name, []):
if not rel:
continue
app_databag = rel.data[rel.app]
grafana_uid = app_databag.get("grafana_uid")
if not grafana_uid:
logger.warning(
"remote end is using an old grafana_datasource interface: "
"`grafana_uid` field not found."
)
continue
urls[grafana_uid] = app_databag.get("grafana_base_url")
return urls

def get_source_uids(self) -> Dict[str, Dict[str, str]]:
"""Get the datasource UID(s) assigned by the remote end(s) to this datasource.

Expand Down Expand Up @@ -504,13 +525,17 @@ class GrafanaSourceConsumer(Object):
def __init__(
self,
charm: CharmBase,
grafana_uid: str,
grafana_base_url: str,
relation_name: str = DEFAULT_RELATION_NAME,
) -> None:
"""A Grafana based Monitoring service consumer, i.e., the charm that uses a datasource.

Args:
charm: a :class:`CharmBase` instance that manages this
instance of the Grafana source service.
grafana_uid: an unique identifier for this grafana-k8s application.
grafana_base_url: the base URL (potentially ingressed) for this grafana-k8s application.
relation_name: string name of the relation that is provides the
Grafana source service. It is strongly advised not to change
the default, so that people deploying your charm will have a
Expand All @@ -524,6 +549,8 @@ def __init__(
super().__init__(charm, relation_name)
self._relation_name = relation_name
self._charm = charm
self._grafana_uid = grafana_uid
self._grafana_base_url = grafana_base_url
events = self._charm.on[relation_name]

# We're stuck with this forever now so upgrades work, or until such point as we can
Expand Down Expand Up @@ -577,15 +604,9 @@ def _publish_source_uids(self, rel: Relation, uids: Dict[str, str]):

Assumes only leader unit will call this method
"""
unique_grafana_name = "juju_{}_{}_{}_{}".format(
self._charm.model.name,
self._charm.model.uuid,
self._charm.model.app.name,
self._charm.model.unit.name.split("/")[1], # type: ignore
)

rel.data[self._charm.app]["grafana_uid"] = unique_grafana_name
rel.data[self._charm.app]["grafana_uid"] = self._grafana_uid
rel.data[self._charm.app]["datasource_uids"] = json.dumps(uids)
rel.data[self._charm.app]["grafana_base_url"] = self._grafana_base_url

def _get_source_config(self, rel: Relation):
"""Generate configuration from data stored in relation data by providers."""
Expand Down
11 changes: 9 additions & 2 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

https://discourse.charmhub.io/t/4208
"""

import datetime
import logging
import os
Expand Down Expand Up @@ -554,7 +555,13 @@ def _configure(self): # noqa: C901
# operations fail, better to let the charm go into error state than setting blocked.
if self.server_cert.available and not self._certs_on_disk:
self._update_cert()

# Obtain the Grafana base URL
urls = self.grafana_source_provider.get_grafana_base_urls()
if urls:
grafana_uid = next(iter(urls)) # TODO How to handle multiple grafanas?
grafana_external_url = urls[grafana_uid]
else:
grafana_external_url = ""
config = ConfigBuilder(
instance_addr=self.hostname,
alertmanager_url=self._alerting_config(),
Expand All @@ -565,6 +572,7 @@ def _configure(self): # noqa: C901
http_tls=self._tls_ready,
tsdb_versions_migration_dates=self._tsdb_versions_migration_dates,
reporting_enabled=bool(self.config["reporting-enabled"]),
grafana_external_url=grafana_external_url,
).build()

# Add a layer so we can check if the service is running
Expand Down Expand Up @@ -857,7 +865,6 @@ def _charm_logging_ca_cert(self) -> Optional[str]:

@property
def _tsdb_versions_migration_dates(self) -> List[Dict[str, str]]:

# If v13_migration_date isn't set (due to missing or failed retrieval),
# we determine the migration date for v13 schema. This occurs once
# during initial setup, as subsequent hooks will get the value from the persisted backup config.
Expand Down
5 changes: 4 additions & 1 deletion src/config_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ def __init__(
http_tls: bool = False,
tsdb_versions_migration_dates: Optional[List[Dict[str, str]]] = None,
reporting_enabled: bool,
grafana_external_url: str,
):
"""Init method."""
self.instance_addr = instance_addr
Expand All @@ -67,6 +68,7 @@ def __init__(
self.retention_period = retention_period
self.tsdb_versions_migration_dates = tsdb_versions_migration_dates or []
self.reporting_enabled = reporting_enabled
self.grafana_external_url = grafana_external_url

def build(self) -> dict:
"""Build Loki config dictionary."""
Expand Down Expand Up @@ -122,7 +124,8 @@ def _ruler(self) -> dict:
# Reference: https://grafana.com/docs/loki/latest/configure/#ruler
return {
"alertmanager_url": self.alertmanager_url,
"external_url": self.external_url,
"external_url": self.grafana_external_url,
# "datasource_uid": "juju_am-test_3688ddf4-84ec-4f55-81da-5afc4166105d_loki_0",
"enable_alertmanager_v2": True,
}

Expand Down
Loading