Skip to content

Commit

Permalink
feat(plugins): Latest additions
Browse files Browse the repository at this point in the history
  • Loading branch information
merkata committed Sep 24, 2024
1 parent 7c3ff02 commit 5710f83
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 11 deletions.
4 changes: 2 additions & 2 deletions lib/charms/synapse/v0/matrix_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def _on_config_changed(self, _) -> None:

logger = logging.getLogger(__name__)

DEFAULT_RELATION_NAME = "matrix-plugin-auth"
DEFAULT_RELATION_NAME = "matrix-auth"


#### Data models for Provider and Requirer ####
Expand Down Expand Up @@ -397,7 +397,7 @@ def _is_remote_relation_data_valid(self, relation: ops.Relation) -> bool:
_ = self._get_remote_relation_data(relation)
return True
except ValueError as ex:
logger.warning("Error validation the relation data %s", ex)
logger.warning("Error validating the relation data %s", ex)
return False

def _on_relation_changed(self, event: ops.RelationChangedEvent) -> None:
Expand Down
2 changes: 1 addition & 1 deletion metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ requires:
database:
interface: postgresql_client
limit: 1
require-irc-bridge:
matrix-auth:
interface: irc_bridge
limit: 1
3 changes: 2 additions & 1 deletion src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,9 @@ def reconcile(self) -> None:
if db is None:
self.unit.status = ops.BlockedStatus("Database relation not found")
return
except ValidationError:
except ValidationError as e:
self.unit.status = ops.BlockedStatus("Database configuration not correct")
logger.error(f"Database configuration not correct: {e}")
return
try:
logger.info("Matrix Reconciling charm")
Expand Down
17 changes: 16 additions & 1 deletion src/charm_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@

import re
import typing
import logging

import ops
from pydantic import BaseModel, Field, ValidationError, validator

logger = logging.getLogger(__name__)


class DatasourcePostgreSQL(BaseModel):
"""A named tuple representing a Datasource PostgreSQL.
Expand All @@ -32,7 +35,7 @@ class DatasourcePostgreSQL(BaseModel):
uri: str = Field(min_length=1, description="Database connection URI")

@classmethod
def from_relation(cls, relation: ops.Relation) -> "DatasourcePostgreSQL":
def from_relation(cls, model: ops.Model, relation: ops.Relation) -> "DatasourcePostgreSQL":
"""Create a DatasourcePostgreSQL from a relation.
Args:
Expand All @@ -42,11 +45,23 @@ def from_relation(cls, relation: ops.Relation) -> "DatasourcePostgreSQL":
A DatasourcePostgreSQL instance.
"""
relation_data = relation.data[relation.app]
logger.info(f"Relation data: {relation_data}")
user = relation_data.get("username", "")
password = relation_data.get("password", "")
secret_user = relation_data.get("secret-user", "")
if user == "" and secret_user != "":
logger.info(f"Getting user and password from secret: {secret_user}")
secret = model.get_secret(id=secret_user)
secret_fields = ops.Secret.get_content(secret)
logger.info(f"Secret fields: {secret_fields}")
user = secret_fields["username"]
password = secret_fields["password"]
logger.info(f"User: {user}")
logger.info(f"Password: {password}")
host, port = relation_data.get("endpoints", ":").split(":")
db = relation_data.get("database", "")
uri = f"postgres://{user}:{password}@{host}:{port}/{db}"
logger.info(f"DatasourcePostgreSQL: {uri}")

return DatasourcePostgreSQL(
user=user,
Expand Down
2 changes: 1 addition & 1 deletion src/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
IRC_BRIDGE_REGISTRATION_FILE_PATH = IRC_BRIDGE_CONFIG_DIR_PATH / "appservice-registration-irc.yaml"

# Charm
MATRIX_RELATION_NAME = "require-irc-bridge"
MATRIX_RELATION_NAME = "matrix-auth"

# Snap
IRC_BRIDGE_SNAP_NAME = "matrix-appservice-irc"
Expand Down
2 changes: 1 addition & 1 deletion src/database_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,4 @@ def get_db(self) -> typing.Optional[DatasourcePostgreSQL]:
return None

relation = self.model.get_relation(self.relation_name)
return DatasourcePostgreSQL.from_relation(relation)
return DatasourcePostgreSQL.from_relation(self.model, relation)
10 changes: 6 additions & 4 deletions src/irc.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def reconcile(
"""
self.prepare()
self.configure(db, matrix, config)
self.reload()
#self.reload()

def prepare(self) -> None:
"""Prepare the machine.
Expand Down Expand Up @@ -152,7 +152,8 @@ def _generate_pem_file_local(self) -> None:
f"-outform PEM -algorithm {IRC_BRIDGE_KEY_ALGO} -pkeyopt {IRC_BRIDGE_KEY_OPTS}",
]
logger.info("Creating PEM file for IRC bridge.")
subprocess.run(pem_create_command, shell=True, check=True, capture_output=True) # nosec
result = subprocess.run(pem_create_command, check=True, capture_output=True) # nosec
logger.info("PEM file creation result: %s", result)

def _generate_app_registration_local(
self, matrix: MatrixAuthProviderData, config: CharmConfig
Expand All @@ -172,9 +173,10 @@ def _generate_app_registration_local(
f"-c {IRC_BRIDGE_CONFIG_FILE_PATH} -l {config.bot_nickname}",
]
logger.info("Creating an app registration file for IRC bridge.")
subprocess.run(
app_reg_create_command, shell=True, check=True, capture_output=True
result = subprocess.run(
app_reg_create_command, check=True, capture_output=True
) # nosec
logger.info("App registration file creation result: %s", result)

def _eval_conf_local(
self, db: DatasourcePostgreSQL, matrix: MatrixAuthProviderData, config: CharmConfig
Expand Down
11 changes: 11 additions & 0 deletions src/matrix_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""Provide the DatabaseObserver class to handle database relation and state."""

import typing
import logging

from charms.synapse.v0.matrix_auth import (
MatrixAuthProviderData,
Expand All @@ -14,6 +15,8 @@
from ops.framework import Object
from pydantic import SecretStr

logger = logging.getLogger(__name__)


class MatrixObserver(Object):
"""The Matrix relation observer."""
Expand All @@ -32,6 +35,14 @@ def __init__(self, charm: CharmBase, relation_name: str):
self._charm,
relation_name=relation_name,
)
self.framework.observe(
self.matrix.on.matrix_auth_request_processed,
self._on_matrix_auth_request_processed,
)

def _on_matrix_auth_request_processed(self, event: Object) -> None:
logger.info("Matrix auth request processed")
self._charm.reconcile() # type: ignore

def get_matrix(self) -> typing.Optional[MatrixAuthProviderData]:
"""Return a Matrix authentication datasource model.
Expand Down

0 comments on commit 5710f83

Please sign in to comment.