From 3240a1d27ffdb4bf3cafa421498a45234a03633c Mon Sep 17 00:00:00 2001 From: arturo-seijas Date: Wed, 15 Nov 2023 16:15:59 +0100 Subject: [PATCH] Support aliases for the redis relation --- lib/charms/redis_k8s/v0/redis.py | 36 ++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/lib/charms/redis_k8s/v0/redis.py b/lib/charms/redis_k8s/v0/redis.py index ad02ac2..eb5180e 100644 --- a/lib/charms/redis_k8s/v0/redis.py +++ b/lib/charms/redis_k8s/v0/redis.py @@ -33,6 +33,7 @@ """ import logging import socket +from typing import Dict, Optional from ops.charm import CharmEvents from ops.framework import EventBase, EventSource, Object @@ -61,14 +62,16 @@ class RedisRelationCharmEvents(CharmEvents): class RedisRequires(Object): + def __init__(self, charm, _stored, relation_name: str = DEFAULT_REALTION_NAME): """A class implementing the redis requires relation.""" super().__init__(charm, relation_name) - self.framework.observe(charm.on.redis_relation_joined, self._on_relation_changed) - self.framework.observe(charm.on.redis_relation_changed, self._on_relation_changed) - self.framework.observe(charm.on.redis_relation_broken, self._on_relation_broken) + self.framework.observe(charm.on[relation_name].relation_joined, self._on_relation_changed) + self.framework.observe(charm.on[relation_name].relation_changed, self._on_relation_changed) + self.framework.observe(charm.on[relation_name].relation_broken, self._on_relation_broken) self._stored = _stored self.charm = charm + self.relation_name = relation_name def _on_relation_changed(self, event): """Handle the relation changed event.""" @@ -90,12 +93,37 @@ def _on_relation_broken(self, event): # Trigger an event that our charm can react to. self.charm.on.redis_relation_updated.emit() + def get_relation_data(self) -> Optional[Dict[str, str]]: + """Retrieve the relation data. + + Returns: + Dict: dict containing the relation data. + """ + relation = self.model.get_relation(self.relation_name) + if not relation: + return None + unit = next(iter(relation.units)) + return relation.data[unit] + + def get_url(self) -> Optional[str]: + """Retrieve the Redis URL. + + Returns: + str: the Redis URL. + """ + relation_data = self.get_relation_data() + if not relation_data: + return None + redis_host = relation_data.get("hostname") + redis_port = relation_data.get("port") + return f"redis://{redis_host}:{redis_port}" + class RedisProvides(Object): def __init__(self, charm, port, relation_name: str = DEFAULT_REALTION_NAME): """A class implementing the redis provides relation.""" super().__init__(charm, relation_name) - self.framework.observe(charm.on.redis_relation_changed, self._on_relation_changed) + self.framework.observe(charm.on[relation_name].relation_changed, self._on_relation_changed) self._port = port self._charm = charm