Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions lib/charms/postgresql_k8s/v0/postgresql.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 55
LIBPATCH = 52
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting to stale version, so we don't release this on the v0 track.


# Groups to distinguish HBA access
ACCESS_GROUP_IDENTITY = "identity_access"
Expand Down Expand Up @@ -751,7 +751,7 @@ def list_users_from_relation(self, current_host=False) -> Set[str]:
"SELECT usename "
"FROM pg_catalog.pg_user "
"WHERE usename LIKE 'relation_id_%' OR usename LIKE 'relation-%' "
"OR usename LIKE 'pgbouncer_auth_relation_id_%' OR usename LIKE '%_user_%_%';"
"OR usename LIKE 'pgbouncer_auth_relation_%' OR usename LIKE '%_user_%_%';"
)
usernames = cursor.fetchall()
return {username[0] for username in usernames}
Expand Down Expand Up @@ -831,7 +831,7 @@ def set_up_database(self, temp_location: Optional[str] = None) -> None:
END IF;
END LOOP;
-- Remove users that don't exist anymore from the pg_hba file.
FOR rec IN SELECT h.lines FROM pg_hba AS h LEFT JOIN relation_users AS r ON SPLIT_PART(h.lines, ' ', 3) = r.user WHERE r.user IS NULL AND (SPLIT_PART(h.lines, ' ', 3) LIKE 'relation_id_%' OR SPLIT_PART(h.lines, ' ', 3) LIKE 'pgbouncer_auth_relation_id_%' OR SPLIT_PART(h.lines, ' ', 3) LIKE '%_user_%_%')
FOR rec IN SELECT h.lines FROM pg_hba AS h LEFT JOIN relation_users AS r ON SPLIT_PART(h.lines, ' ', 3) = r.user WHERE r.user IS NULL AND (SPLIT_PART(h.lines, ' ', 3) LIKE 'relation_id_%' OR SPLIT_PART(h.lines, ' ', 3) LIKE 'pgbouncer_auth_relation_%' OR SPLIT_PART(h.lines, ' ', 3) LIKE '%_user_%_%')
LOOP
DELETE FROM pg_hba WHERE lines = rec.lines;
changes := changes + 1;
Expand Down Expand Up @@ -1081,3 +1081,21 @@ def validate_group_map(self, group_map: Optional[str]) -> bool:
return False

return True

def is_user_in_hba(self, username: str) -> bool:
"""Check if user was added in pg_hba."""
connection = None
try:
with self._connect_to_database() as connection, connection.cursor() as cursor:
cursor.execute(
SQL(
"SELECT COUNT(*) FROM pg_hba_file_rules WHERE {} = ANY(user_name);"
).format(Literal(username))
)
return cursor.fetchone()[0] > 0
except psycopg2.Error as e:
logger.debug(f"Failed to check pg_hba: {e}")
return False
finally:
if connection:
connection.close()
96 changes: 5 additions & 91 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pyproject.toml
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bump linting and dependency python to noble (3.12).

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ package-mode = false
requires-poetry = ">=2.0.0"

[tool.poetry.dependencies]
python = "^3.10"
python = "^3.12"
ops = "^2.22.0"
boto3 = "^1.38.27"
pgconnstr = "^1.0.1"
Expand Down Expand Up @@ -94,7 +94,7 @@ markers = ["juju3", "juju_secrets"]
[tool.ruff]
# preview and explicit preview are enabled for CPY001
preview = true
target-version = "py310"
target-version = "py312"
src = ["src", "."]
line-length = 99

Expand Down
12 changes: 5 additions & 7 deletions src/backups.py
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Linting changes.

Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import re
import tempfile
import time
from datetime import datetime, timezone
from datetime import UTC, datetime
from io import BytesIO

import boto3
Expand Down Expand Up @@ -371,9 +371,7 @@ def _generate_backup_list_output(self) -> str:
backup_reference, _ = self._parse_backup_id(backup["reference"][-1])
lsn_start_stop = f"{backup['lsn']['start']} / {backup['lsn']['stop']}"
time_start, time_stop = (
datetime.strftime(
datetime.fromtimestamp(stamp, timezone.utc), "%Y-%m-%dT%H:%M:%SZ"
)
datetime.strftime(datetime.fromtimestamp(stamp, UTC), "%Y-%m-%dT%H:%M:%SZ")
for stamp in backup["timestamp"].values()
)
backup_timeline = (
Expand Down Expand Up @@ -465,7 +463,7 @@ def _list_timelines(self) -> dict[str, tuple[str, str]]:

return dict[str, tuple[str, str]]({
datetime.strftime(
datetime.fromtimestamp(timeline_object["time"], timezone.utc),
datetime.fromtimestamp(timeline_object["time"], UTC),
"%Y-%m-%dT%H:%M:%SZ",
): (
timeline.split("/")[1],
Expand Down Expand Up @@ -513,8 +511,8 @@ def _parse_psql_timestamp(self, timestamp: str) -> datetime:
t = re.sub(r"\.(\d+)", lambda x: f".{x[1]:06}", t)
dt = datetime.fromisoformat(t)
# Convert to the timezone-naive
if dt.tzinfo is not None and dt.tzinfo is not timezone.utc:
dt = dt.astimezone(tz=timezone.utc)
if dt.tzinfo is not None and dt.tzinfo is not UTC:
dt = dt.astimezone(tz=UTC)
return dt.replace(tzinfo=None)

def _parse_backup_id(self, label) -> tuple[str, str]:
Expand Down
4 changes: 0 additions & 4 deletions src/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,4 @@

DATABASE = "database"

ENDPOINT_SIMULTANEOUSLY_BLOCKING_MESSAGE = (
"Please choose one endpoint to use. No need to relate all of them simultaneously!"
)

PGBACKREST_LOGROTATE_FILE = "/etc/logrotate.d/pgbackrest.logrotate"
Loading