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
73 changes: 70 additions & 3 deletions engines/postgresql.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
from __future__ import annotations

from typing import Any

from core.errors import ValidationError
from core.fields import Field
from core.specs import DatabaseSpec
from engines.base import StandardSqlEngine
from services.ports import PortAllocator

# Physical restores write a data directory into RESTORE_PATH on the agent.
RESTORE_MOUNT = ("./restores", "/restores")


def physical_only(answers: dict[str, Any]) -> bool:
return answers.get("method") == "physical"


def at_least_one_day(value: int) -> int:
if value < 1:
raise ValidationError("full_every_days must be at least 1.")
return value


class PostgresEngine(StandardSqlEngine):
Expand Down Expand Up @@ -65,7 +83,56 @@ class PostgresClusterEngine(StandardSqlEngine):
key, display, default_port = "postgresql-cluster", "PostgreSQL Cluster", 5432
template, slug, db_prefix = "engines/postgresql-cluster.yml.j2", "pg", "pg"
warning = (
"Postgres Cluster requires a superuser. Cluster backup/restore uses "
"pg_dumpall, which dumps all databases and global objects (roles, "
"tablespaces). The provided user must be a Postgres superuser."
"Postgres Cluster with the archive method uses pg_dumpall, which dumps all "
"databases and global objects (roles, tablespaces): the user must be a "
"Postgres superuser. The physical method needs PostgreSQL 17+, a role "
"with REPLICATION, a pg_hba.conf replication line and summarize_wal = on."
)

def option_fields(self) -> list[Field]:
return [
Field(
"method",
"Backup method",
"choice",
default="archive",
choices=("archive", "physical"),
help=(
"archive: pg_dumpall of every database (default). physical: "
"pg_basebackup of the whole cluster, a full backup then "
"incrementals holding only the changed blocks (PostgreSQL 17+). Restores rebuild "
"a data directory in ./restores on the agent host. Requires "
"Agent 1.27.0+ and Dashboard 1.37.0+. Cannot be changed later."
),
),
Field(
"full_every_days",
"Start a new full backup every N days",
"int",
default=7,
validator=at_least_one_day,
when=physical_only,
help=(
"The next backup is a new full once the chain's full is this "
"old. Not applied while the source has a full backup schedule "
"in the dashboard."
),
),
]

@staticmethod
def mount_for(spec: DatabaseSpec) -> tuple[str, str] | None:
return RESTORE_MOUNT if physical_only(spec.options) else None

def generate(
self, *, auth: bool, ports: PortAllocator, answers: dict[str, Any]
) -> DatabaseSpec:
if physical_only(answers.get("options", {})):
# ponytail: a managed container would need summarize_wal and a
# replication pg_hba.conf line; refuse until someone asks for it.
raise ValidationError(
"The physical method needs a server set up for replication, so it "
"only works on an existing database.",
hint="Use --mode existing, or the archive method for a new database.",
)
return super().generate(auth=auth, ports=ports, answers=answers)
5 changes: 5 additions & 0 deletions services/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from core.specs import DatabaseSpec
from engines import registry
from engines.base import DbEngine
from engines.postgresql import RESTORE_MOUNT
from services import auth_providers as ap
from services import settings as cfg
from services.compose_facts import CA_BUNDLE_IN_CONTAINER, ComposeFacts
Expand Down Expand Up @@ -125,6 +126,10 @@ def mounts(self) -> list[tuple[str, str]]:
mounts.append(mount)
return mounts

@property
def restore_path(self) -> str | None:
return RESTORE_MOUNT[1] if RESTORE_MOUNT in self.mounts else None

def validate(self) -> None:
bundle = self.ca_bundle
if bundle and not (self.path / bundle).exists() and not Path(bundle).exists():
Expand Down
1 change: 1 addition & 0 deletions services/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ def render_agent(
"extra_env": [
(name, _var(env, name, inline)) for name in project.extra_env
],
"restore_path": project.restore_path,
"ca_bundle": project.ca_bundle,
"ca_bundle_in_container": CA_BUNDLE_IN_CONTAINER,
"ssl_cert_file_var": _var(env, "SSL_CERT_FILE", inline),
Expand Down
3 changes: 3 additions & 0 deletions templates/agent.yml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ services:
{%- for name, value in extra_env %}
{{ name }}: "{{ value }}"
{%- endfor %}
{%- if restore_path %}
RESTORE_PATH: "{{ restore_path }}"
{%- endif %}
{%- if ca_bundle %}
SSL_CERT_FILE: "{{ ssl_cert_file_var }}"
{%- endif %}
Expand Down
78 changes: 76 additions & 2 deletions tests/engines/postgresql_cluster.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import re
from typing import cast

import pytest
import yaml

from core.errors import ValidationError
from core.specs import DatabaseSpec
from engines import registry
from engines.postgresql import PostgresClusterEngine
from tests.support import EXISTING_ANSWERS, field_specs
from services.project import AgentProject
from tests.support import AGENT_ENV, EXISTING_ANSWERS, agent_service, field_specs
from ui.components.prompt import Prompt
from ui.form import Form

CLUSTER = registry.get("postgresql-cluster")
HEALTH = {"interval": "10s", "timeout": "5s", "retries": 5}
FORM = Form(cast(Prompt, None), non_interactive=True)
PHYSICAL = {"method": "physical", "full_every_days": 7}


def attributes():
Expand Down Expand Up @@ -76,7 +86,11 @@ def fields():
("password", "secret", None),
]
assert CLUSTER.fields_new() == []
assert CLUSTER.option_fields() == []
assert field_specs(CLUSTER.option_fields()) == [
("method", "choice", "archive"),
("full_every_days", "int", 7),
]
assert CLUSTER.option_fields()[0].choices == ("archive", "physical")


def from_existing():
Expand Down Expand Up @@ -133,3 +147,63 @@ def options_are_dropped(ports):
)
assert CLUSTER.non_default_options(spec) == {}
assert "options" not in CLUSTER.agent_entry(spec)


def archive_writes_no_options():
options = FORM.collect(CLUSTER.option_fields(), {"method": "archive"})
spec = CLUSTER.from_existing(EXISTING_ANSWERS).with_options(options)
assert "options" not in CLUSTER.agent_entry(spec)
assert CLUSTER.mount_for(spec) is None


def physical_reaches_the_agent():
options = FORM.collect(CLUSTER.option_fields(), {"method": "physical"})
assert options == PHYSICAL
spec = CLUSTER.from_existing(EXISTING_ANSWERS).with_options(options)
assert CLUSTER.agent_entry(spec)["options"] == {"method": "physical"}
longer = FORM.collect(
CLUSTER.option_fields(), {"method": "physical", "full_every_days": "14"}
)
assert CLUSTER.agent_entry(spec.with_options(longer))["options"] == {
"method": "physical",
"full_every_days": 14,
}


@pytest.mark.parametrize(
("answers", "message"),
[
({"method": "physical", "full_every_days": "0"}, "at least 1"),
({"method": "physical", "full_every_days": "x"}, "whole number"),
({"method": "archive", "full_every_days": "3"}, "does not apply"),
({"method": "wal"}, "Invalid value"),
],
)
def physical_options_are_checked(answers, message):
with pytest.raises(ValidationError, match=message):
FORM.collect(CLUSTER.option_fields(), answers)


def physical_is_refused_on_a_new_database(ports):
with pytest.raises(ValidationError, match="existing"):
CLUSTER.generate(auth=True, ports=ports, answers={"options": PHYSICAL})


def physical_compose_mounts_the_restore_folder(tmp_path, renderer):
project = AgentProject.create(tmp_path, dict(AGENT_ENV), host_gateway=False)
spec = CLUSTER.from_existing(EXISTING_ANSWERS).with_options(PHYSICAL)
project.add(spec, CLUSTER)
project.add(CLUSTER.from_existing(EXISTING_ANSWERS).with_options(PHYSICAL), CLUSTER)
result = renderer.render_agent(project, inline=False)
result.validate()
agent = yaml.safe_load(result.compose)["services"]["agent"]
expected = agent_service("./restores:/restores")
expected["environment"]["RESTORE_PATH"] = "/restores"
assert agent == expected


def archive_compose_has_no_restore_folder(tmp_path, renderer):
project = AgentProject.create(tmp_path, dict(AGENT_ENV), host_gateway=False)
project.add(CLUSTER.from_existing(EXISTING_ANSWERS), CLUSTER)
result = renderer.render_agent(project, inline=False)
assert yaml.safe_load(result.compose)["services"]["agent"] == agent_service()
Loading