diff --git a/src/charm.py b/src/charm.py index 7c96368..6aa229b 100755 --- a/src/charm.py +++ b/src/charm.py @@ -11,7 +11,8 @@ from ops.framework import StoredState from ops.charm import RelationJoinedEvent, RelationDepartedEvent from ops.main import main -from ops.model import ActiveStatus, BlockedStatus, Relation +from ops.model import ActiveStatus, BlockedStatus, ErrorStatus, Relation +from typing import List logger = logging.getLogger(__name__) @@ -79,6 +80,11 @@ def _on_metrics_endpoint_relation_created(self, event: RelationJoinedEvent): self.control_socket.add_metrics_user(username, password) # Set up Prometheus scrape config + try: + api_port = self.api_port() + except AgentConfException as e: + self.unit.status = ErrorStatus(f"can't read controller API port from agent.conf: {e}") + metrics_endpoint = MetricsEndpointProvider( self, jobs=[{ @@ -86,7 +92,7 @@ def _on_metrics_endpoint_relation_created(self, event: RelationJoinedEvent): "scheme": "https", "static_configs": [{ "targets": [ - f'*:{self.api_port()}' + f'*:{api_port}' ] }], "basic_auth": { @@ -116,7 +122,20 @@ def _agent_conf(self, key: str): def api_port(self) -> str: """Return the port on which the controller API server is listening.""" - return self._agent_conf('apiport') + api_port = self._agent_conf('apiport') + if api_port: + return api_port + + # If there is no 'apiport' key, try to parse 'apiaddresses'. + api_addresses = self._agent_conf('apiaddresses') + if not api_addresses: + raise AgentConfException("neither 'apiport' or 'apiaddresses' defined in agent.conf") + if isinstance(api_addresses, List) == 0: + raise AgentConfException("agent.conf key 'apiaddresses' is not a list") + if len(api_addresses) == 0: + raise AgentConfException("agent.conf key 'apiaddresses' is empty list") + + return api_addresses[0].split(':')[1] def ca_cert(self) -> str: """Return the controller's CA certificate.""" @@ -136,5 +155,9 @@ def generate_password() -> str: return secrets.token_urlsafe(16) +class AgentConfException(Exception): + """Raised when there are errors reading info from agent.conf.""" + + if __name__ == "__main__": main(JujuControllerCharm) diff --git a/tests/test_charm.py b/tests/test_charm.py index 0585206..72b32bd 100644 --- a/tests/test_charm.py +++ b/tests/test_charm.py @@ -8,7 +8,8 @@ from unittest.mock import mock_open, patch agent_conf = ''' -apiport: 17070 +apiaddresses: +- localhost:17070 cacert: fake '''