Automatically set hostname relation data

Instead of relying on the user of the interface to set the correct
hostname parameter when configuring database access request,
automatically determine the correct hostname using:

 1) In Juju >= 2.0, using the network space binding of the
    named relation.
 2) In Juju < 2.0, using the units private-address.

The hostname relation value can be overridden using the hostname
parameter of the configure method.

Change-Id: Id69a3786d2ac754aa8659b8cde977c4d86a37fc8
This commit is contained in:
James Page 2017-01-25 10:44:55 +00:00
parent 7587a4b6e8
commit 7b9fc4e9aa
2 changed files with 25 additions and 4 deletions

View File

@ -38,9 +38,8 @@ from charms.reactive import when, when_not
@when('database.connected')
def setup_database(database):
host = unit_get('private-address')
database.configure('mydatabase', 'myusername', host, prefix="first")
database.configure('mydatabase2', 'myusername2', host, prefix="second")
database.configure('mydatabase', 'myusername', prefix="first")
database.configure('mydatabase2', 'myusername2', prefix="second")
@when('database.available')
def use_database(database):
@ -80,3 +79,15 @@ def waiting_mysql(database):
def unit_ready(database):
status_set('active', 'Unit is ready')
```
In Juju 2.0 environments, the interface will automatically determine the network
space binding on the local unit to present to the remote mysql-shared service
based on the name of the relation. In older Juju versions, the private-address
of the unit will be used instead. This can be overridden using the hostname
parameter of the configure method.
```python
@when('database.connected')
def setup_database(database):
database.configure('mydatabase', 'myusername', hostname='hostname.override')
```

View File

@ -1,3 +1,4 @@
from charmhelpers.core import hookenv
from charms.reactive import RelationBase
from charms.reactive import hook
from charms.reactive import scopes
@ -31,10 +32,19 @@ class MySQLSharedRequires(RelationBase):
self.remove_state('{relation_name}.available.access_network')
self.remove_state('{relation_name}.available.ssl')
def configure(self, database, username, hostname, prefix=None):
def configure(self, database, username, hostname=None, prefix=None):
"""
Called by charm layer that uses this interface to configure a database.
"""
if not hostname:
conversation = self.conversation()
try:
hostname = hookenv.network_get_primary_address(
conversation.relation_name
)
except NotImplementedError:
hostname = hookenv.unit_private_ip()
if prefix:
relation_info = {
prefix + '_database': database,