Skip to content

Commit

Permalink
parse controller API port from apiaddresses in agent.conf
Browse files Browse the repository at this point in the history
  • Loading branch information
barrettj12 committed Nov 7, 2023
1 parent c69f232 commit 5a38a26
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
29 changes: 26 additions & 3 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -79,14 +80,19 @@ 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=[{
"metrics_path": "/introspection/metrics",
"scheme": "https",
"static_configs": [{
"targets": [
f'*:{self.api_port()}'
f'*:{api_port}'
]
}],
"basic_auth": {
Expand Down Expand Up @@ -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."""
Expand All @@ -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)
3 changes: 2 additions & 1 deletion tests/test_charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
from unittest.mock import mock_open, patch

agent_conf = '''
apiport: 17070
apiaddresses:
- localhost:17070
cacert: fake
'''

Expand Down

0 comments on commit 5a38a26

Please sign in to comment.