Skip to content

Commit 2e0bd19

Browse files
Apply Carl suggestions
1 parent 9a40854 commit 2e0bd19

File tree

3 files changed

+54
-24
lines changed

3 files changed

+54
-24
lines changed

common/common/mysql_shell/__init__.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -144,18 +144,13 @@ def _get_mysql_roles(self, name_pattern: str) -> typing.Set[str]:
144144
logger.debug(f"MySQL roles found for {name_pattern=}: {len(rows)}")
145145
return {row[0] for row in rows}
146146

147-
def create_application_database(self, *, database: str) -> str:
147+
def _create_application_database(self, *, database: str, rolename: str) -> str:
148148
"""Create database for related database_provides application."""
149-
role_name = f"charmed_dba_{database}"
150-
if len(role_name) >= _ROLE_MAX_LENGTH:
151-
logger.exception("Failed to create application database")
152-
raise ValueError("Role name longer than 32 characters")
153-
154149
statements = [
155150
f"CREATE DATABASE IF NOT EXISTS `{database}`",
156-
f"CREATE ROLE IF NOT EXISTS `{role_name}`",
157-
f"GRANT SELECT, INSERT, DELETE, UPDATE, EXECUTE ON `{database}`.* TO {role_name}",
158-
f"GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, DROP, INDEX, LOCK TABLES, REFERENCES, TRIGGER ON `{database}`.* TO {role_name}",
151+
f"CREATE ROLE IF NOT EXISTS `{rolename}`",
152+
f"GRANT SELECT, INSERT, DELETE, UPDATE, EXECUTE ON `{database}`.* TO {rolename}",
153+
f"GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, DROP, INDEX, LOCK TABLES, REFERENCES, TRIGGER ON `{database}`.* TO {rolename}",
159154
]
160155

161156
mysql_roles = self._get_mysql_roles("charmed_%")
@@ -173,7 +168,7 @@ def create_application_database(self, *, database: str) -> str:
173168
logger.debug(f"Created {database=}")
174169
return database
175170

176-
def create_application_user(self, *, database: str, username: str) -> str:
171+
def _create_application_user(self, *, database: str, username: str) -> str:
177172
"""Create database user for related database_provides application."""
178173
attributes = self._get_attributes()
179174
password = utils.generate_password()
@@ -185,6 +180,16 @@ def create_application_user(self, *, database: str, username: str) -> str:
185180
logger.debug(f"Created {username=} with {attributes=}")
186181
return password
187182

183+
def create_application_database(self, *, database: str, username: str) -> str:
184+
"""Create both the database and the relation user, returning its password."""
185+
rolename = f"charmed_dba_{database}"
186+
if len(rolename) >= _ROLE_MAX_LENGTH:
187+
raise ValueError("Database DBA role longer than 32 characters")
188+
189+
________ = self._create_application_database(database=database, rolename=rolename)
190+
password = self._create_application_user(database=database, username=username)
191+
return password
192+
188193
def add_attributes_to_mysql_router_user(
189194
self, *, username: str, router_id: str, unit_name: str
190195
) -> None:

common/common/relations/database_provides.py

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,25 @@ class _UnsupportedExtraUserRole(status_exception.StatusException):
3030

3131
def __init__(self, *, app_name: str, endpoint_name: str) -> None:
3232
message = (
33-
f"{app_name} app requested unsupported extra user role on {endpoint_name} endpoint"
33+
f"{app_name} app requested unsupported extra user role on "
34+
f"{endpoint_name} endpoint"
3435
)
3536
logger.warning(message)
3637
super().__init__(ops.BlockedStatus(message))
3738

3839

40+
class _InvalidDatabaseName(status_exception.StatusException):
41+
"""Application charm requested an invalid database name"""
42+
43+
def __init__(self, *, app_name: str, endpoint_name: str, exception_msg: str) -> None:
44+
message = (
45+
f"{app_name} app requested an invalid database name on "
46+
f"{endpoint_name} endpoint: {exception_msg}"
47+
)
48+
logger.warning(message)
49+
super().__init__(ops.BlockedStatus(exception_msg))
50+
51+
3952
class _Relation:
4053
"""Relation to one application charm"""
4154

@@ -79,9 +92,11 @@ def __init__(
7992
if isinstance(event, ops.RelationBrokenEvent) and event.relation.id == self._id:
8093
raise _RelationBreaking
8194
self._database: str = self._databag["database"]
95+
self._app_name: str = relation.app.name
96+
self._endpoint_name: str = relation.endpoint.name
8297
if self._databag.get("extra-user-roles"):
8398
raise _UnsupportedExtraUserRole(
84-
app_name=relation.app.name, endpoint_name=relation.name
99+
app_name=self._app_name, endpoint_name=self._endpoint_name
85100
)
86101

87102
def _set_databag(
@@ -121,15 +136,24 @@ def create_database_and_user(
121136
shell.delete_user(username, must_exist=False)
122137
logger.debug("Deleted user if exists before creating user")
123138

124-
________ = shell.create_application_database(database=self._database)
125-
password = shell.create_application_user(database=self._database, username=username)
126-
127-
self._set_databag(
128-
username=username,
129-
password=password,
130-
router_read_write_endpoints=router_read_write_endpoints,
131-
router_read_only_endpoints=router_read_only_endpoints,
132-
)
139+
try:
140+
password = shell.create_application_database(
141+
database=self._database,
142+
username=username,
143+
)
144+
except ValueError as exception:
145+
raise _InvalidDatabaseName(
146+
app_name=self._app_name,
147+
endpoint_name=self._endpoint_name,
148+
exception_msg=str(exception),
149+
)
150+
else:
151+
self._set_databag(
152+
username=username,
153+
password=password,
154+
router_read_write_endpoints=router_read_write_endpoints,
155+
router_read_only_endpoints=router_read_only_endpoints,
156+
)
133157

134158

135159
class _UserNotShared(Exception):

machines/src/relations/deprecated_shared_db_database_provides.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,10 @@ def create_database_and_user(
147147
shell.delete_user(self._username, must_exist=False)
148148
logger.debug("Deleted user if exists before creating user")
149149

150-
________ = shell.create_application_database(database=self._database)
151-
password = shell.create_application_user(database=self._database, username=self._username)
152-
150+
password = shell.create_application_database(
151+
database=self._database,
152+
username=self._username,
153+
)
153154
self._peer_app_databag[self.peer_databag_password_key] = password
154155
self.set_databag(password=password)
155156

0 commit comments

Comments
 (0)