Skip to content

Commit

Permalink
charm: open port NATS is listening on
Browse files Browse the repository at this point in the history
The operator framework currently doesn't not support opening or closing
ports the charm exposes. Due to this we have to manually invoke the
open-port and close-port hook tools. The implementation also keeps track
of changing ports.
  • Loading branch information
morphis committed Oct 26, 2020
1 parent 0fcdf60 commit f531fec
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ def __init__(self, framework, key):
self.cluster = NatsCluster(self, 'cluster', listen_on_all_addresses)
self.client = NatsClient(self, 'client', listen_on_all_addresses, self.model.config['client-port'])
self.state.set_default(is_started=False, auth_token=self.get_auth_token(self.AUTH_TOKEN_LENGTH),
use_tls=None, use_tls_ca=None, nats_config_hash=None)
use_tls=None, use_tls_ca=None, nats_config_hash=None,
client_port=None)

self.ca_client = CAClient(self, 'ca-client')
self.framework.observe(self.ca_client.on.tls_config_ready, self)
Expand Down Expand Up @@ -234,9 +235,20 @@ def reconfigure_nats(self):
self.NATS_SERVER_CONFIG_PATH.write_text(rendered_content)
if self.state.is_started:
subprocess.check_call(['systemctl', 'restart', self.NATS_SERVICE])
self.unit.status = ActiveStatus()
self.client.expose_nats(auth_token=self.state.auth_token)

client_port = self.model.config['client-port']
if (client_port is None or client_port == 0) and (self.state.client_port is not None or len(self.state.client_port) > 0):
self._close_port(self.state.client_port)
else:
port = '{}/tcp'.format(client_port)
if self.state.client_port is not None and port != self.state.client_port:
self._close_port(self.state.client_port)
self._open_port(port)
self.state.client_port = port

self.unit.status = ActiveStatus()

def get_auth_token(self, length=None):
'''Generate a random auth token.'''
if not isinstance(length, int):
Expand All @@ -263,6 +275,12 @@ def on_config_changed(self, event):
def on_upgrade_charm(self, event):
self.reconfigure_nats()

def _open_port(self, port):
subprocess.check_call(['open-port', port])

def _close_port(self, port):
subprocess.check_call(['close-port', port])


if __name__ == '__main__':
main(NatsCharm)

0 comments on commit f531fec

Please sign in to comment.