Add automatically reading interface properties

This commit is contained in:
Liam Young 2021-10-07 13:29:02 +01:00
parent c8d012b0fa
commit 5fe20d43f5
2 changed files with 22 additions and 14 deletions

View File

@ -67,6 +67,16 @@ class RelationHandler(ops.charm.Object):
""" """
return self.interface, self.relation_name return self.interface, self.relation_name
def interface_properties(self):
property_names = [
p for p in dir(self.interface) if isinstance(
getattr(type(self.interface), p, None), property)]
properties = {
p: getattr(self.interface, p)
for p in property_names
if not p.startswith('_') and p not in ['model']}
return properties
@property @property
def ready(self) -> bool: def ready(self) -> bool:
"""Determine with the relation is ready for use.""" """Determine with the relation is ready for use."""
@ -74,7 +84,7 @@ class RelationHandler(ops.charm.Object):
def context(self) -> dict: def context(self) -> dict:
"""Pull together context for rendering templates.""" """Pull together context for rendering templates."""
return {} return self.interface_properties()
class IngressHandler(RelationHandler): class IngressHandler(RelationHandler):
@ -233,22 +243,18 @@ class AMQPHandler(RelationHandler):
return {} return {}
if not hosts: if not hosts:
return {} return {}
hosts = ','.join(hosts) ctxt = self.interface_properties()
port = self.interface.ssl_port or self.DEFAULT_PORT ctxt['hosts'] = ','.join(ctxt['hostnames'])
username = self.interface.username ctxt['port'] = ctxt.get('ssl_port') or self.DEFAULT_PORT
password = self.interface.password
transport_url_hosts = ','.join([ transport_url_hosts = ','.join([
"{}:{}@{}:{}".format(username, "{}:{}@{}:{}".format(self.username,
password, ctxt['password'],
host_, # TODO deal with IPv6 host_, # TODO deal with IPv6
port) ctxt['port'])
for host_ in self.interface.hostnames for host_ in ctxt['hostnames']
]) ])
transport_url = "rabbit://{}/{}".format( transport_url = "rabbit://{}/{}".format(
transport_url_hosts, transport_url_hosts,
self.vhost) self.vhost)
ctxt = { ctxt['transport_url'] = transport_url
'port': port,
'hosts': hosts,
'transport_url': transport_url}
return ctxt return ctxt

View File

@ -225,6 +225,7 @@ TEMPLATE_CONTENTS = """
{{ my_service_db.database_password }} {{ my_service_db.database_password }}
{{ options.debug }} {{ options.debug }}
{{ amqp.transport_url }} {{ amqp.transport_url }}
{{ amqp.hostname }}
""" """
@ -395,7 +396,8 @@ class TestOSBaseOperatorAPICharm(CharmTestCase):
'/bin/wsgi_admin', '/bin/wsgi_admin',
'hardpassword', 'hardpassword',
'true', 'true',
'rabbit://my-service:rabbit.pass@10.0.0.13:5672/my-service'] 'rabbit://my-service:rabbit.pass@10.0.0.13:5672/my-service',
'rabbithost1.local']
expect_string = '\n' + '\n'.join(expect_entries) expect_string = '\n' + '\n'.join(expect_entries)
self.assertEqual( self.assertEqual(
self.container_calls['push']['/etc/my-service/my-service.conf'], self.container_calls['push']['/etc/my-service/my-service.conf'],