Skip to content

Commit ddd5182

Browse files
authored
[MISC] Setting profiles (#157)
* Setting profiles * Bump libs
1 parent e80d50a commit ddd5182

File tree

10 files changed

+63
-12
lines changed

10 files changed

+63
-12
lines changed

lib/charms/data_platform_libs/v0/data_interfaces.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ def _on_topic_requested(self, event: TopicRequestedEvent):
320320

321321
# Increment this PATCH version before using `charmcraft publish-lib` or reset
322322
# to 0 if you are raising the major API version
323-
LIBPATCH = 19
323+
LIBPATCH = 20
324324

325325
PYDEPS = ["ops>=2.0.0"]
326326

@@ -1674,6 +1674,10 @@ def _assign_relation_alias(self, relation_id: int) -> None:
16741674
if relation:
16751675
relation.data[self.local_unit].update({"alias": available_aliases[0]})
16761676

1677+
# We need to set relation alias also on the application level so,
1678+
# it will be accessible in show-unit juju command, executed for a consumer application unit
1679+
self.update_relation_data(relation_id, {"alias": available_aliases[0]})
1680+
16771681
def _emit_aliased_event(self, event: RelationChangedEvent, event_name: str) -> None:
16781682
"""Emit an aliased event to a particular relation if it has an alias.
16791683

lib/charms/data_platform_libs/v0/upgrade.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ def restart(self, event) -> None:
285285

286286
# Increment this PATCH version before using `charmcraft publish-lib` or reset
287287
# to 0 if you are raising the major API version
288-
LIBPATCH = 13
288+
LIBPATCH = 14
289289

290290
PYDEPS = ["pydantic>=1.10,<2", "poetry-core"]
291291

@@ -895,6 +895,10 @@ def _on_upgrade_charm(self, event: UpgradeCharmEvent) -> None:
895895
self.charm.unit.status = WaitingStatus("other units upgrading first...")
896896
self.peer_relation.data[self.charm.unit].update({"state": "ready"})
897897

898+
if self.charm.app.planned_units() == 1:
899+
# single unit upgrade, emit upgrade_granted event right away
900+
getattr(self.on, "upgrade_granted").emit()
901+
898902
else:
899903
# for k8s run version checks only on highest ordinal unit
900904
if (

lib/charms/postgresql_k8s/v0/postgresql.py

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
Any charm using this library should import the `psycopg2` or `psycopg2-binary` dependency.
2020
"""
2121
import logging
22-
from typing import List, Optional, Set, Tuple
22+
from typing import Dict, List, Optional, Set, Tuple
2323

2424
import psycopg2
2525
from psycopg2 import sql
@@ -32,7 +32,7 @@
3232

3333
# Increment this PATCH version before using `charmcraft publish-lib` or reset
3434
# to 0 if you are raising the major API version
35-
LIBPATCH = 14
35+
LIBPATCH = 17
3636

3737
INVALID_EXTRA_USER_ROLE_BLOCKING_MESSAGE = "invalid role(s) for extra user roles"
3838

@@ -117,12 +117,13 @@ def _connect_to_database(
117117
connection.autocommit = True
118118
return connection
119119

120-
def create_database(self, database: str, user: str) -> None:
120+
def create_database(self, database: str, user: str, plugins: List[str] = []) -> None:
121121
"""Creates a new database and grant privileges to a user on it.
122122
123123
Args:
124124
database: database to be created.
125125
user: user that will have access to the database.
126+
plugins: extensions to enable in the new database.
126127
"""
127128
try:
128129
connection = self._connect_to_database()
@@ -170,6 +171,10 @@ def create_database(self, database: str, user: str) -> None:
170171
logger.error(f"Failed to create database: {e}")
171172
raise PostgreSQLCreateDatabaseError()
172173

174+
# Enable preset extensions
175+
for plugin in plugins:
176+
self.enable_disable_extension(plugin, True, database)
177+
173178
def create_user(
174179
self, user: str, password: str = None, admin: bool = False, extra_user_roles: str = None
175180
) -> None:
@@ -406,6 +411,7 @@ def update_user_password(self, username: str, password: str) -> None:
406411
Raises:
407412
PostgreSQLUpdateUserPasswordError if the password couldn't be changed.
408413
"""
414+
connection = None
409415
try:
410416
with self._connect_to_database() as connection, connection.cursor() as cursor:
411417
cursor.execute(
@@ -420,19 +426,39 @@ def update_user_password(self, username: str, password: str) -> None:
420426
if connection is not None:
421427
connection.close()
422428

429+
def is_restart_pending(self) -> bool:
430+
"""Query pg_settings for pending restart."""
431+
connection = None
432+
try:
433+
with self._connect_to_database() as connection, connection.cursor() as cursor:
434+
cursor.execute("SELECT COUNT(*) FROM pg_settings WHERE pending_restart=True;")
435+
return cursor.fetchone()[0] > 0
436+
except psycopg2.OperationalError:
437+
logger.warning("Failed to connect to PostgreSQL.")
438+
return False
439+
except psycopg2.Error as e:
440+
logger.error(f"Failed to check if restart is pending: {e}")
441+
return False
442+
finally:
443+
if connection:
444+
connection.close()
445+
423446
@staticmethod
424447
def build_postgresql_parameters(
425-
profile: str, available_memory: int
426-
) -> Optional[dict[str, str]]:
448+
profile: str, available_memory: int, limit_memory: Optional[int] = None
449+
) -> Optional[Dict[str, str]]:
427450
"""Builds the PostgreSQL parameters.
428451
429452
Args:
430453
profile: the profile to use.
431454
available_memory: available memory to use in calculation in bytes.
455+
limit_memory: (optional) limit memory to use in calculation in bytes.
432456
433457
Returns:
434458
Dictionary with the PostgreSQL parameters.
435459
"""
460+
if limit_memory:
461+
available_memory = min(available_memory, limit_memory)
436462
logger.debug(f"Building PostgreSQL parameters for {profile=} and {available_memory=}")
437463
if profile == "production":
438464
# Use 25% of the available memory for shared_buffers.
@@ -446,3 +472,6 @@ def build_postgresql_parameters(
446472
}
447473

448474
return parameters
475+
else:
476+
# Return default
477+
return {"shared_buffers": "128MB"}

tests/integration/relations/pgbouncer_provider/test_pgbouncer_provider.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ async def test_database_relation_with_charm_libraries(ops_test: OpsTest, pgb_cha
8181
num_units=2,
8282
channel="14/edge",
8383
trust=True,
84+
config={"profile": "testing"},
8485
),
8586
)
8687
await ops_test.model.add_relation(f"{PGB}:{BACKEND_RELATION_NAME}", f"{PG}:database")

tests/integration/relations/test_backend_database.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ async def test_relate_pgbouncer_to_postgres(ops_test: OpsTest, pgb_charm):
5555
trust=True,
5656
),
5757
# Edge 5 is the new postgres charm
58-
ops_test.model.deploy(PG, channel="14/edge", trust=True, num_units=3),
58+
ops_test.model.deploy(
59+
PG, channel="14/edge", trust=True, num_units=3, config={"profile": "testing"}
60+
),
5961
)
6062
await asyncio.gather(
6163
ops_test.model.wait_for_idle(apps=[PGB], status="blocked", timeout=1000),

tests/integration/relations/test_db.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ async def test_create_db_legacy_relation(ops_test: OpsTest, pgb_charm):
5252
series=CHARM_SERIES,
5353
trust=True,
5454
),
55-
ops_test.model.deploy(PG, num_units=3, trust=True, channel="14/edge"),
55+
ops_test.model.deploy(
56+
PG, num_units=3, trust=True, channel="14/edge", config={"profile": "testing"}
57+
),
5658
ops_test.model.deploy("finos-waltz-k8s", application_name=FINOS_WALTZ, channel="edge"),
5759
)
5860

tests/integration/relations/test_db_admin.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@ async def test_create_db_admin_legacy_relation(ops_test: OpsTest, pgb_charm):
4545
series=CHARM_SERIES,
4646
trust=True,
4747
),
48-
ops_test.model.deploy(PG, trust=True, num_units=3, channel="14/edge"),
48+
ops_test.model.deploy(
49+
PG, trust=True, num_units=3, channel="14/edge", config={"profile": "testing"}
50+
),
4951
ops_test.model.deploy(
5052
FIRST_DISCOURSE_APP_NAME, application_name=FIRST_DISCOURSE_APP_NAME
5153
),

tests/integration/relations/test_peers.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ async def test_scaled_relations(ops_test: OpsTest):
5353
async with ops_test.fast_forward():
5454
await asyncio.gather(
5555
# Edge 5 is the new postgres charm
56-
ops_test.model.deploy(PG, channel="14/edge", trust=True, num_units=3),
56+
ops_test.model.deploy(
57+
PG, channel="14/edge", trust=True, num_units=3, config={"profile": "testing"}
58+
),
5759
ops_test.model.deploy("finos-waltz-k8s", application_name=FINOS_WALTZ, channel="edge"),
5860
)
5961

tests/integration/test_tls.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,11 @@ async def test_build_and_deploy(ops_test: OpsTest, pgb_charm):
7272
wait_for_apps = True
7373
# Deploy Postgresql operator
7474
await ops_test.model.deploy(
75-
POSTGRESQL_APP_NAME, channel="14/edge", trust=True, num_units=DATABASE_UNITS
75+
POSTGRESQL_APP_NAME,
76+
channel="14/edge",
77+
trust=True,
78+
num_units=DATABASE_UNITS,
79+
config={"profile": "testing"},
7680
)
7781
await ops_test.model.relate(PGB, POSTGRESQL_APP_NAME)
7882

tests/integration/test_upgrade.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ async def test_in_place_upgrade(ops_test: OpsTest, pgb_charm):
5757
num_units=2,
5858
channel="14/edge",
5959
trust=True,
60+
config={"profile": "testing"},
6061
),
6162
)
6263
await ops_test.model.add_relation(f"{PGB}:{BACKEND_RELATION_NAME}", f"{PG}:database")

0 commit comments

Comments
 (0)