mirror of
https://github.com/kevinveenbirkenbach/docker-volume-backup.git
synced 2026-07-17 06:05:13 +00:00
Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 45d3b0ad7c | |||
| fe5bed8254 | |||
| 7a7ec57b54 | |||
| 2bbe7d180a | |||
|
|
286ef179da | ||
|
|
6cb0b8a548 | ||
| e1f1b602d3 | |||
| b9a8b391f0 | |||
| c949f2c5cf | |||
| 96e6b3ea93 | |||
| 79214e64e8 | |||
| e9030e8443 | |||
| 57ea4592c1 | |||
| ad5d8fcda3 | |||
| bfa596ae30 | |||
| 21b4d237d3 | |||
| ec051b4c2b | |||
| ed78f69b3b | |||
| a69074c302 | |||
| 0b4696f649 | |||
| e3f28098bd | |||
| babadcb038 | |||
| fbfdb8615f | |||
| 2f5882f5c1 | |||
| 522391fdd3 | |||
| b3c9cf5ce1 | |||
| 2ed3472527 |
21
.github/dependabot.yml
vendored
Normal file
21
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: github-actions
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: weekly
|
||||||
|
groups:
|
||||||
|
actions:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
- package-ecosystem: docker
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: weekly
|
||||||
|
|
||||||
|
- package-ecosystem: pip
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: weekly
|
||||||
8
.github/workflows/ci.yml
vendored
8
.github/workflows/ci.yml
vendored
@@ -22,7 +22,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Show docker info
|
- name: Show docker info
|
||||||
run: |
|
run: |
|
||||||
@@ -35,7 +35,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload E2E artifacts (always)
|
- name: Upload E2E artifacts (always)
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
name: e2e-artifacts
|
name: e2e-artifacts
|
||||||
path: artifacts
|
path: artifacts
|
||||||
@@ -49,7 +49,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout (full history for tags)
|
- name: Checkout (full history for tags)
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v7
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
@@ -67,7 +67,7 @@ jobs:
|
|||||||
git push -f origin stable
|
git push -f origin stable
|
||||||
|
|
||||||
- name: Login to GHCR
|
- name: Login to GHCR
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v4
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
|
|||||||
29
.github/workflows/dependabot-auto-merge.yml
vendored
Normal file
29
.github/workflows/dependabot-auto-merge.yml
vendored
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
name: Dependabot auto-merge
|
||||||
|
|
||||||
|
on: pull_request
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
auto-merge:
|
||||||
|
# Enable auto-merge for minor/patch dependency bumps; majors stay manual.
|
||||||
|
# The merge only happens once every required status check (make test) is
|
||||||
|
# green, so the CI stays the gate.
|
||||||
|
if: github.actor == 'dependabot[bot]'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Fetch dependency metadata
|
||||||
|
id: metadata
|
||||||
|
uses: dependabot/fetch-metadata@v3
|
||||||
|
with:
|
||||||
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Enable auto-merge (minor + patch)
|
||||||
|
if: steps.metadata.outputs.update-type != 'version-update:semver-major'
|
||||||
|
run: gh pr merge --auto --squash "$PR_URL"
|
||||||
|
env:
|
||||||
|
PR_URL: ${{ github.event.pull_request.html_url }}
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,4 +1,5 @@
|
|||||||
__pycache__
|
__pycache__
|
||||||
artifacts/
|
artifacts/
|
||||||
*.egg-info
|
*.egg-info
|
||||||
dist/
|
dist/
|
||||||
|
build/
|
||||||
65
CHANGELOG.md
65
CHANGELOG.md
@@ -1,3 +1,68 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## [1.8.1] - 2026-07-12
|
||||||
|
|
||||||
|
- Restore: the postgres empty mode also drops user-owned collations in
|
||||||
|
public; dumps containing CREATE COLLATION (e.g. OpenProject's ICU
|
||||||
|
collation versions_name) no longer abort the replay with 'collation
|
||||||
|
already exists'.
|
||||||
|
- Maintenance: base image bumped from python 3.11-slim to 3.14-slim.
|
||||||
|
|
||||||
|
## [1.8.0] - 2026-07-11
|
||||||
|
|
||||||
|
Swarm-aware backups and replayable restores.
|
||||||
|
|
||||||
|
- Backup: swarm task containers are never stopped or started manually
|
||||||
|
anymore; they are skipped visibly and backed up hot, while the sql dump
|
||||||
|
stays the consistent database backup.
|
||||||
|
- Backup: a container that vanishes between listing and inspect no longer
|
||||||
|
aborts the run; a failing inspect on a container that still exists keeps
|
||||||
|
failing loudly.
|
||||||
|
- Backup: pg_dump runs with the no-owner and no-privileges flags so dumps
|
||||||
|
are replayable by the owning app user.
|
||||||
|
- Restore: the mariadb empty mode drops all tables in one client session
|
||||||
|
with FOREIGN_KEY_CHECKS disabled; FK-linked parent tables no longer abort
|
||||||
|
the replay with ERROR 1451.
|
||||||
|
- Restore: the postgres empty mode drops only current-user-owned objects,
|
||||||
|
and the replay skips superuser-only dump lines without ever touching
|
||||||
|
COPY data blocks.
|
||||||
|
- Restore: the replay streams the dump through a temp file instead of
|
||||||
|
buffering it in memory; multi-GB dumps no longer OOM the restore.
|
||||||
|
- Tooling: the e2e runner reaches the DinD daemon via docker exec instead
|
||||||
|
of a host-published unencrypted API port.
|
||||||
|
- Tooling: new end-to-end test reproducing the swarm stop flake, plus unit
|
||||||
|
tests for the restore filters and the swarm probes; the suite is 36 unit,
|
||||||
|
9 integration and 30 e2e tests.
|
||||||
|
- Tooling: Dependabot with auto-merge for minor and patch updates.
|
||||||
|
|
||||||
|
## [1.7.1] - 2026-05-26
|
||||||
|
|
||||||
|
* 🔌 MariaDB SQL backups now connect over TCP loopback so the dump always matches the same wildcard-host grant the application uses — no more surprise `ERROR 1045 Access denied` when a localhost-bound auth row preempts.
|
||||||
|
* 🧪 New regression and bug-repro tests pin the TCP behaviour and prove it under the exact preemption setup that caused the production failure on MariaDB 12.
|
||||||
|
* 🩺 E2E test infrastructure: DinD bridge and inner daemon now default to MTU 1280 so registry pulls survive host paths with broken PMTUD (override via `E2E_DIND_MTU`).
|
||||||
|
|
||||||
|
|
||||||
|
## [1.7.0] - 2026-02-07
|
||||||
|
|
||||||
|
* 🚀 Backup jobs now support all valid Docker Compose file names – case-insensitive and hassle-free.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.6.0] - 2026-02-06
|
||||||
|
|
||||||
|
* Compose handling is now fully delegated to the Infinito.Nexus compose wrapper or plain docker compose, removing all custom env and file detection to ensure a single, consistent source of truth.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.5.0] - 2026-01-31
|
||||||
|
|
||||||
|
* * Make `databases.csv` optional: missing or empty files now emit warnings and no longer break backups
|
||||||
|
* Fix Docker CLI compatibility by switching to `docker-ce-cli` and required build tools
|
||||||
|
|
||||||
|
|
||||||
|
## [1.4.0] - 2026-01-31
|
||||||
|
|
||||||
|
* Baudolo now restarts Docker Compose stacks in a wrapper-aware way (with a `docker compose` fallback), ensuring that all Compose overrides and env files are applied identically to the Infinito.Nexus workflow.
|
||||||
|
|
||||||
|
|
||||||
## [1.3.0] - 2026-01-10
|
## [1.3.0] - 2026-01-10
|
||||||
|
|
||||||
* Empty databases.csv no longer causes baudolo-seed to fail
|
* Empty databases.csv no longer causes baudolo-seed to fail
|
||||||
|
|||||||
35
Dockerfile
35
Dockerfile
@@ -1,34 +1,37 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
FROM python:3.11-slim
|
FROM python:3.14-slim
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Runtime + build essentials:
|
# Base deps for build/runtime + docker repo key
|
||||||
# - rsync: required for file backup/restore
|
|
||||||
# - ca-certificates: TLS
|
|
||||||
# - docker-cli: needed if you want to control the host Docker engine (via /var/run/docker.sock mount)
|
|
||||||
# - make: to delegate install logic to Makefile
|
|
||||||
#
|
|
||||||
# Notes:
|
|
||||||
# - On Debian slim, the docker client package is typically "docker.io".
|
|
||||||
# - If you only want restore-without-docker, you can drop docker.io later.
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
make \
|
make \
|
||||||
rsync \
|
rsync \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
docker-cli \
|
bash \
|
||||||
|
curl \
|
||||||
|
gnupg \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install Docker CLI (docker-ce-cli) from Docker's official apt repo
|
||||||
|
RUN bash -lc "set -euo pipefail \
|
||||||
|
&& install -m 0755 -d /etc/apt/keyrings \
|
||||||
|
&& curl -fsSL https://download.docker.com/linux/debian/gpg \
|
||||||
|
| gpg --dearmor -o /etc/apt/keyrings/docker.gpg \
|
||||||
|
&& chmod a+r /etc/apt/keyrings/docker.gpg \
|
||||||
|
&& . /etc/os-release \
|
||||||
|
&& echo \"deb [arch=\$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \${VERSION_CODENAME} stable\" \
|
||||||
|
> /etc/apt/sources.list.d/docker.list \
|
||||||
|
&& apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends docker-ce-cli \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*"
|
||||||
|
|
||||||
# Fail fast if docker client is missing
|
# Fail fast if docker client is missing
|
||||||
|
RUN docker version || true
|
||||||
RUN command -v docker
|
RUN command -v docker
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# All install decisions are handled by the Makefile.
|
|
||||||
RUN make install
|
RUN make install
|
||||||
|
|
||||||
# Sensible defaults (can be overridden at runtime)
|
|
||||||
ENV PYTHONUNBUFFERED=1
|
ENV PYTHONUNBUFFERED=1
|
||||||
|
|
||||||
# Default: show CLI help
|
|
||||||
CMD ["baudolo", "--help"]
|
CMD ["baudolo", "--help"]
|
||||||
|
|||||||
4
Makefile
4
Makefile
@@ -49,9 +49,9 @@ test: test-unit test-integration test-e2e
|
|||||||
test-unit: clean build
|
test-unit: clean build
|
||||||
@echo ">> Running unit tests"
|
@echo ">> Running unit tests"
|
||||||
@docker run --rm -t $(IMAGE) \
|
@docker run --rm -t $(IMAGE) \
|
||||||
sh -lc 'python -m unittest discover -t . -s tests/unit -p "test_*.py" -v'
|
bash -lc 'python -m unittest discover -t . -s tests/unit -p "test_*.py" -v'
|
||||||
|
|
||||||
test-integration: clean build
|
test-integration: clean build
|
||||||
@echo ">> Running integration tests"
|
@echo ">> Running integration tests"
|
||||||
@docker run --rm -t $(IMAGE) \
|
@docker run --rm -t $(IMAGE) \
|
||||||
sh -lc 'python -m unittest discover -t . -s tests/integration -p "test_*.py" -v'
|
bash -lc 'python -m unittest discover -t . -s tests/integration -p "test_*.py" -v'
|
||||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "backup-docker-to-local"
|
name = "backup-docker-to-local"
|
||||||
version = "1.3.0"
|
version = "1.8.1"
|
||||||
description = "Backup Docker volumes to local with rsync and optional DB dumps."
|
description = "Backup Docker volumes to local with rsync and optional DB dumps."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.9"
|
requires-python = ">=3.9"
|
||||||
|
|||||||
@@ -16,15 +16,24 @@ DIND="${E2E_DIND_NAME:-baudolo-e2e-dind}"
|
|||||||
DIND_VOL="${E2E_DIND_VOL:-baudolo-e2e-dind-data}"
|
DIND_VOL="${E2E_DIND_VOL:-baudolo-e2e-dind-data}"
|
||||||
E2E_TMP_VOL="${E2E_TMP_VOL:-baudolo-e2e-tmp}"
|
E2E_TMP_VOL="${E2E_TMP_VOL:-baudolo-e2e-tmp}"
|
||||||
|
|
||||||
DIND_HOST="${E2E_DIND_HOST:-tcp://127.0.0.1:2375}"
|
# Host-side access to the DinD daemon goes through `docker exec` (dind()
|
||||||
|
# below) instead of a host-published port: port publishing is not reachable
|
||||||
|
# from every environment (sandboxed runners, hosts with broken loopback
|
||||||
|
# publishing), while exec only needs the outer docker socket. The TCP
|
||||||
|
# listener stays for the test container inside the dedicated network.
|
||||||
DIND_HOST_IN_NET="${E2E_DIND_HOST_IN_NET:-tcp://${DIND}:2375}"
|
DIND_HOST_IN_NET="${E2E_DIND_HOST_IN_NET:-tcp://${DIND}:2375}"
|
||||||
|
|
||||||
|
dind() { docker exec "${DIND}" docker "$@"; }
|
||||||
|
dind_stdin() { docker exec -i "${DIND}" docker "$@"; }
|
||||||
|
|
||||||
IMG="${E2E_IMAGE:-baudolo:local}"
|
IMG="${E2E_IMAGE:-baudolo:local}"
|
||||||
RSYNC_IMG="${E2E_RSYNC_IMAGE:-ghcr.io/kevinveenbirkenbach/alpine-rsync}"
|
RSYNC_IMG="${E2E_RSYNC_IMAGE:-ghcr.io/kevinveenbirkenbach/alpine-rsync}"
|
||||||
|
|
||||||
READY_TIMEOUT_SECONDS="${E2E_READY_TIMEOUT_SECONDS:-120}"
|
READY_TIMEOUT_SECONDS="${E2E_READY_TIMEOUT_SECONDS:-120}"
|
||||||
ARTIFACTS_DIR="${E2E_ARTIFACTS_DIR:-./artifacts}"
|
ARTIFACTS_DIR="${E2E_ARTIFACTS_DIR:-./artifacts}"
|
||||||
|
|
||||||
|
DIND_MTU="${E2E_DIND_MTU:-1280}"
|
||||||
|
|
||||||
KEEP_ON_FAIL="${E2E_KEEP_ON_FAIL:-0}"
|
KEEP_ON_FAIL="${E2E_KEEP_ON_FAIL:-0}"
|
||||||
KEEP_VOLUMES="${E2E_KEEP_VOLUMES:-0}"
|
KEEP_VOLUMES="${E2E_KEEP_VOLUMES:-0}"
|
||||||
DEBUG_SHELL="${E2E_DEBUG_SHELL:-0}"
|
DEBUG_SHELL="${E2E_DEBUG_SHELL:-0}"
|
||||||
@@ -46,8 +55,8 @@ dump_debug() {
|
|||||||
echo "=== Host docker info ==="
|
echo "=== Host docker info ==="
|
||||||
docker info || true
|
docker info || true
|
||||||
echo
|
echo
|
||||||
echo "=== DinD reachable? (docker -H ${DIND_HOST} version) ==="
|
echo "=== DinD reachable? (docker exec ${DIND} docker version) ==="
|
||||||
docker -H "${DIND_HOST}" version || true
|
dind version || true
|
||||||
echo
|
echo
|
||||||
} > "${ARTIFACTS_DIR}/debug-host-${TS}.txt" 2>&1 || true
|
} > "${ARTIFACTS_DIR}/debug-host-${TS}.txt" 2>&1 || true
|
||||||
|
|
||||||
@@ -56,48 +65,34 @@ dump_debug() {
|
|||||||
|
|
||||||
# DinD state
|
# DinD state
|
||||||
{
|
{
|
||||||
echo "=== docker -H ps -a ==="
|
echo "=== dind ps -a ==="
|
||||||
docker -H "${DIND_HOST}" ps -a || true
|
dind ps -a || true
|
||||||
echo
|
echo
|
||||||
echo "=== docker -H images ==="
|
echo "=== dind images ==="
|
||||||
docker -H "${DIND_HOST}" images || true
|
dind images || true
|
||||||
echo
|
echo
|
||||||
echo "=== docker -H network ls ==="
|
echo "=== dind network ls ==="
|
||||||
docker -H "${DIND_HOST}" network ls || true
|
dind network ls || true
|
||||||
echo
|
echo
|
||||||
echo "=== docker -H volume ls ==="
|
echo "=== dind volume ls ==="
|
||||||
docker -H "${DIND_HOST}" volume ls || true
|
dind volume ls || true
|
||||||
echo
|
echo
|
||||||
echo "=== docker -H system df ==="
|
echo "=== dind system df ==="
|
||||||
docker -H "${DIND_HOST}" system df || true
|
dind system df || true
|
||||||
} > "${ARTIFACTS_DIR}/debug-dind-${TS}.txt" 2>&1 || true
|
} > "${ARTIFACTS_DIR}/debug-dind-${TS}.txt" 2>&1 || true
|
||||||
|
|
||||||
# Try to capture recent events (best effort; might be noisy)
|
# Try to capture recent events (best effort; might be noisy)
|
||||||
docker -H "${DIND_HOST}" events --since 10m --until 0s \
|
dind events --since 10m --until 0s \
|
||||||
> "${ARTIFACTS_DIR}/dind-events-${TS}.txt" 2>&1 || true
|
> "${ARTIFACTS_DIR}/dind-events-${TS}.txt" 2>&1 || true
|
||||||
|
|
||||||
# Dump shared /tmp content from the tmp volume:
|
# The shared tmp volume is mounted at /tmp inside the DinD container
|
||||||
# We create a temporary container that mounts the volume, then tar its content.
|
# itself, so tar it there and copy it out with the outer daemon.
|
||||||
# (Does not rely on host filesystem paths.)
|
|
||||||
log "DEBUG: archiving shared /tmp (volume ${E2E_TMP_VOL})"
|
log "DEBUG: archiving shared /tmp (volume ${E2E_TMP_VOL})"
|
||||||
docker -H "${DIND_HOST}" run --rm \
|
docker exec "${DIND}" tar -czf "/tmpdump-${TS}.tar.gz" -C /tmp . >/dev/null 2>&1 || true
|
||||||
-v "${E2E_TMP_VOL}:/tmp" \
|
docker cp "${DIND}:/tmpdump-${TS}.tar.gz" "${ARTIFACTS_DIR}/e2e-tmp-${TS}.tar.gz" >/dev/null 2>&1 || true
|
||||||
alpine:3.20 \
|
|
||||||
sh -lc 'cd /tmp && tar -czf /out.tar.gz . || true' \
|
|
||||||
>/dev/null 2>&1 || true
|
|
||||||
|
|
||||||
# The above writes inside the container FS, not to host. So do it properly:
|
|
||||||
# Use "docker cp" from a temp container.
|
|
||||||
local tmpc="baudolo-e2e-tmpdump-${TS}"
|
|
||||||
docker -H "${DIND_HOST}" rm -f "${tmpc}" >/dev/null 2>&1 || true
|
|
||||||
docker -H "${DIND_HOST}" create --name "${tmpc}" -v "${E2E_TMP_VOL}:/tmp" alpine:3.20 \
|
|
||||||
sh -lc 'cd /tmp && tar -czf /tmpdump.tar.gz . || true' >/dev/null
|
|
||||||
docker -H "${DIND_HOST}" start -a "${tmpc}" >/dev/null 2>&1 || true
|
|
||||||
docker -H "${DIND_HOST}" cp "${tmpc}:/tmpdump.tar.gz" "${ARTIFACTS_DIR}/e2e-tmp-${TS}.tar.gz" >/dev/null 2>&1 || true
|
|
||||||
docker -H "${DIND_HOST}" rm -f "${tmpc}" >/dev/null 2>&1 || true
|
|
||||||
|
|
||||||
log "DEBUG: artifacts written:"
|
log "DEBUG: artifacts written:"
|
||||||
ls -la "${ARTIFACTS_DIR}" | sed 's/^/ /' || true
|
find "${ARTIFACTS_DIR}" -maxdepth 1 -mindepth 1 -print | sed 's/^/ /' || true
|
||||||
}
|
}
|
||||||
|
|
||||||
cleanup() {
|
cleanup() {
|
||||||
@@ -105,9 +100,9 @@ cleanup() {
|
|||||||
log "KEEP_ON_FAIL=1 and failure detected -> skipping cleanup."
|
log "KEEP_ON_FAIL=1 and failure detected -> skipping cleanup."
|
||||||
log "Next steps:"
|
log "Next steps:"
|
||||||
echo " - Inspect DinD logs: docker logs ${DIND} | less"
|
echo " - Inspect DinD logs: docker logs ${DIND} | less"
|
||||||
echo " - Use DinD daemon: docker -H ${DIND_HOST} ps -a"
|
echo " - Use DinD daemon: docker exec ${DIND} docker ps -a"
|
||||||
echo " - Shared tmp vol: docker -H ${DIND_HOST} run --rm -v ${E2E_TMP_VOL}:/tmp alpine:3.20 ls -la /tmp"
|
echo " - Shared tmp vol: docker exec ${DIND} ls -la /tmp"
|
||||||
echo " - DinD docker root: docker -H ${DIND_HOST} run --rm -v ${DIND_VOL}:/var/lib/docker alpine:3.20 ls -la /var/lib/docker/volumes"
|
echo " - DinD docker root: docker exec ${DIND} ls -la /var/lib/docker/volumes"
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -124,8 +119,11 @@ cleanup() {
|
|||||||
}
|
}
|
||||||
trap cleanup EXIT INT TERM
|
trap cleanup EXIT INT TERM
|
||||||
|
|
||||||
log "Creating network ${NET} (if missing)"
|
log "(Re)creating network ${NET} with MTU ${DIND_MTU}"
|
||||||
docker network inspect "${NET}" >/dev/null 2>&1 || docker network create "${NET}" >/dev/null
|
docker network rm "${NET}" >/dev/null 2>&1 || true
|
||||||
|
docker network create \
|
||||||
|
--opt com.docker.network.driver.mtu="${DIND_MTU}" \
|
||||||
|
"${NET}" >/dev/null
|
||||||
|
|
||||||
log "Removing old ${DIND} (if any)"
|
log "Removing old ${DIND} (if any)"
|
||||||
docker rm -f "${DIND}" >/dev/null 2>&1 || true
|
docker rm -f "${DIND}" >/dev/null 2>&1 || true
|
||||||
@@ -145,14 +143,14 @@ docker run -d --privileged \
|
|||||||
-e DOCKER_TLS_CERTDIR="" \
|
-e DOCKER_TLS_CERTDIR="" \
|
||||||
-v "${DIND_VOL}:/var/lib/docker" \
|
-v "${DIND_VOL}:/var/lib/docker" \
|
||||||
-v "${E2E_TMP_VOL}:/tmp" \
|
-v "${E2E_TMP_VOL}:/tmp" \
|
||||||
-p 2375:2375 \
|
|
||||||
docker:dind \
|
docker:dind \
|
||||||
--host=tcp://0.0.0.0:2375 \
|
--host=tcp://0.0.0.0:2375 \
|
||||||
--tls=false >/dev/null
|
--tls=false \
|
||||||
|
--mtu="${DIND_MTU}" >/dev/null
|
||||||
|
|
||||||
log "Waiting for DinD to be ready..."
|
log "Waiting for DinD to be ready..."
|
||||||
for i in $(seq 1 "${READY_TIMEOUT_SECONDS}"); do
|
for i in $(seq 1 "${READY_TIMEOUT_SECONDS}"); do
|
||||||
if docker -H "${DIND_HOST}" version >/dev/null 2>&1; then
|
if dind version >/dev/null 2>&1; then
|
||||||
log "DinD is ready."
|
log "DinD is ready."
|
||||||
break
|
break
|
||||||
fi
|
fi
|
||||||
@@ -168,13 +166,13 @@ done
|
|||||||
|
|
||||||
log "Pre-pulling helper images in DinD..."
|
log "Pre-pulling helper images in DinD..."
|
||||||
log " - Pulling: ${RSYNC_IMG}"
|
log " - Pulling: ${RSYNC_IMG}"
|
||||||
docker -H "${DIND_HOST}" pull "${RSYNC_IMG}"
|
dind pull "${RSYNC_IMG}"
|
||||||
|
|
||||||
log "Ensuring alpine exists in DinD (for debug helpers)"
|
log "Ensuring alpine exists in DinD (for debug helpers)"
|
||||||
docker -H "${DIND_HOST}" pull alpine:3.20 >/dev/null
|
dind pull alpine:3.20 >/dev/null
|
||||||
|
|
||||||
log "Loading ${IMG} image into DinD..."
|
log "Loading ${IMG} image into DinD..."
|
||||||
docker save "${IMG}" | docker -H "${DIND_HOST}" load >/dev/null
|
docker save "${IMG}" | dind_stdin load >/dev/null
|
||||||
|
|
||||||
log "Running E2E tests inside DinD"
|
log "Running E2E tests inside DinD"
|
||||||
set +e
|
set +e
|
||||||
@@ -187,7 +185,7 @@ if [ "${DEBUG_SHELL}" = "1" ]; then
|
|||||||
-v "${DIND_VOL}:/var/lib/docker:ro" \
|
-v "${DIND_VOL}:/var/lib/docker:ro" \
|
||||||
-v "${E2E_TMP_VOL}:/tmp" \
|
-v "${E2E_TMP_VOL}:/tmp" \
|
||||||
"${IMG}" \
|
"${IMG}" \
|
||||||
sh -lc '
|
bash -lc '
|
||||||
set -e
|
set -e
|
||||||
if [ ! -f /etc/machine-id ]; then
|
if [ ! -f /etc/machine-id ]; then
|
||||||
mkdir -p /etc
|
mkdir -p /etc
|
||||||
@@ -195,7 +193,7 @@ if [ "${DEBUG_SHELL}" = "1" ]; then
|
|||||||
fi
|
fi
|
||||||
echo ">> DOCKER_HOST=${DOCKER_HOST}"
|
echo ">> DOCKER_HOST=${DOCKER_HOST}"
|
||||||
docker ps -a || true
|
docker ps -a || true
|
||||||
exec sh
|
exec bash
|
||||||
'
|
'
|
||||||
rc=$?
|
rc=$?
|
||||||
else
|
else
|
||||||
@@ -206,7 +204,7 @@ else
|
|||||||
-v "${DIND_VOL}:/var/lib/docker:ro" \
|
-v "${DIND_VOL}:/var/lib/docker:ro" \
|
||||||
-v "${E2E_TMP_VOL}:/tmp" \
|
-v "${E2E_TMP_VOL}:/tmp" \
|
||||||
"${IMG}" \
|
"${IMG}" \
|
||||||
sh -lc '
|
bash -lc '
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
set -x
|
set -x
|
||||||
export PYTHONUNBUFFERED=1
|
export PYTHONUNBUFFERED=1
|
||||||
|
|||||||
@@ -2,10 +2,12 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import pathlib
|
import pathlib
|
||||||
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
import pandas
|
import pandas
|
||||||
from dirval import create_stamp_file
|
from dirval import create_stamp_file
|
||||||
|
from pandas.errors import EmptyDataError
|
||||||
|
|
||||||
from .cli import parse_args
|
from .cli import parse_args
|
||||||
from .compose import handle_docker_compose_services
|
from .compose import handle_docker_compose_services
|
||||||
@@ -14,8 +16,10 @@ from .docker import (
|
|||||||
change_containers_status,
|
change_containers_status,
|
||||||
containers_using_volume,
|
containers_using_volume,
|
||||||
docker_volume_names,
|
docker_volume_names,
|
||||||
|
filter_stoppable,
|
||||||
get_image_info,
|
get_image_info,
|
||||||
has_image,
|
has_image,
|
||||||
|
is_swarm_task,
|
||||||
)
|
)
|
||||||
from .shell import execute_shell_command
|
from .shell import execute_shell_command
|
||||||
from .volume import backup_volume
|
from .volume import backup_volume
|
||||||
@@ -64,9 +68,13 @@ def volume_is_fully_ignored(
|
|||||||
|
|
||||||
def requires_stop(containers: list[str], images_no_stop_required: list[str]) -> bool:
|
def requires_stop(containers: list[str], images_no_stop_required: list[str]) -> bool:
|
||||||
"""
|
"""
|
||||||
Stop is required if ANY container image is NOT in the whitelist patterns.
|
Stop is required if ANY stoppable container image is NOT in the
|
||||||
|
whitelist patterns. Swarm task containers never count: baudolo must
|
||||||
|
not cycle them (see docker.is_swarm_task).
|
||||||
"""
|
"""
|
||||||
for c in containers:
|
for c in containers:
|
||||||
|
if is_swarm_task(c):
|
||||||
|
continue
|
||||||
img = get_image_info(c)
|
img = get_image_info(c)
|
||||||
if not any(pat in img for pat in images_no_stop_required):
|
if not any(pat in img for pat in images_no_stop_required):
|
||||||
return True
|
return True
|
||||||
@@ -96,6 +104,42 @@ def backup_mariadb_or_postgres(
|
|||||||
return False, False
|
return False, False
|
||||||
|
|
||||||
|
|
||||||
|
def _empty_databases_df() -> "pandas.DataFrame":
|
||||||
|
"""
|
||||||
|
Create an empty DataFrame with the expected schema for databases.csv.
|
||||||
|
|
||||||
|
This allows the backup to continue without DB dumps when the CSV is missing
|
||||||
|
or empty (pandas EmptyDataError).
|
||||||
|
"""
|
||||||
|
return pandas.DataFrame(columns=["instance", "database", "username", "password"])
|
||||||
|
|
||||||
|
|
||||||
|
def _load_databases_df(csv_path: str) -> "pandas.DataFrame":
|
||||||
|
"""
|
||||||
|
Load databases.csv robustly.
|
||||||
|
|
||||||
|
- Missing file -> warn, continue with empty df
|
||||||
|
- Empty file -> warn, continue with empty df
|
||||||
|
- Valid CSV -> return dataframe
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return pandas.read_csv(csv_path, sep=";", keep_default_na=False, dtype=str)
|
||||||
|
except FileNotFoundError:
|
||||||
|
print(
|
||||||
|
f"WARNING: databases.csv not found: {csv_path}. Continuing without database dumps.",
|
||||||
|
file=sys.stderr,
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return _empty_databases_df()
|
||||||
|
except EmptyDataError:
|
||||||
|
print(
|
||||||
|
f"WARNING: databases.csv exists but is empty: {csv_path}. Continuing without database dumps.",
|
||||||
|
file=sys.stderr,
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return _empty_databases_df()
|
||||||
|
|
||||||
|
|
||||||
def _backup_dumps_for_volume(
|
def _backup_dumps_for_volume(
|
||||||
*,
|
*,
|
||||||
containers: list[str],
|
containers: list[str],
|
||||||
@@ -136,9 +180,10 @@ def main() -> int:
|
|||||||
# IMPORTANT:
|
# IMPORTANT:
|
||||||
# - keep_default_na=False prevents empty fields from turning into NaN
|
# - keep_default_na=False prevents empty fields from turning into NaN
|
||||||
# - dtype=str keeps all columns stable for comparisons/validation
|
# - dtype=str keeps all columns stable for comparisons/validation
|
||||||
databases_df = pandas.read_csv(
|
#
|
||||||
args.databases_csv, sep=";", keep_default_na=False, dtype=str
|
# Robust behavior:
|
||||||
)
|
# - if the file is missing or empty, we continue without DB dumps.
|
||||||
|
databases_df = _load_databases_df(args.databases_csv)
|
||||||
|
|
||||||
print("💾 Start volume backups...", flush=True)
|
print("💾 Start volume backups...", flush=True)
|
||||||
|
|
||||||
@@ -168,7 +213,8 @@ def main() -> int:
|
|||||||
if found_db:
|
if found_db:
|
||||||
if not dumped_any:
|
if not dumped_any:
|
||||||
print(
|
print(
|
||||||
f"WARNING: dump-only-sql requested but no DB dump was produced for DB volume '{volume_name}'. Falling back to file backup.",
|
f"WARNING: dump-only-sql requested but no DB dump was produced for DB volume '{volume_name}'. "
|
||||||
|
"Falling back to file backup.",
|
||||||
flush=True,
|
flush=True,
|
||||||
)
|
)
|
||||||
# fall through to file backup below
|
# fall through to file backup below
|
||||||
@@ -179,20 +225,22 @@ def main() -> int:
|
|||||||
|
|
||||||
if args.everything:
|
if args.everything:
|
||||||
# "everything": always do pre-rsync, then stop + rsync again
|
# "everything": always do pre-rsync, then stop + rsync again
|
||||||
|
stoppable = filter_stoppable(containers)
|
||||||
backup_volume(versions_dir, volume_name, vol_dir)
|
backup_volume(versions_dir, volume_name, vol_dir)
|
||||||
change_containers_status(containers, "stop")
|
change_containers_status(stoppable, "stop")
|
||||||
backup_volume(versions_dir, volume_name, vol_dir)
|
backup_volume(versions_dir, volume_name, vol_dir)
|
||||||
if not args.shutdown:
|
if not args.shutdown:
|
||||||
change_containers_status(containers, "start")
|
change_containers_status(stoppable, "start")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# default: rsync, and if needed stop + rsync
|
# default: rsync, and if needed stop + rsync
|
||||||
backup_volume(versions_dir, volume_name, vol_dir)
|
backup_volume(versions_dir, volume_name, vol_dir)
|
||||||
if requires_stop(containers, args.images_no_stop_required):
|
if requires_stop(containers, args.images_no_stop_required):
|
||||||
change_containers_status(containers, "stop")
|
stoppable = filter_stoppable(containers)
|
||||||
|
change_containers_status(stoppable, "stop")
|
||||||
backup_volume(versions_dir, volume_name, vol_dir)
|
backup_volume(versions_dir, volume_name, vol_dir)
|
||||||
if not args.shutdown:
|
if not args.shutdown:
|
||||||
change_containers_status(containers, "start")
|
change_containers_status(stoppable, "start")
|
||||||
|
|
||||||
# Stamp the backup version directory using dirval (python lib)
|
# Stamp the backup version directory using dirval (python lib)
|
||||||
stamp_directory(version_dir)
|
stamp_directory(version_dir)
|
||||||
|
|||||||
@@ -1,17 +1,82 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
|
||||||
|
def _build_compose_cmd(project_dir: str, passthrough: List[str]) -> List[str]:
|
||||||
|
"""
|
||||||
|
Build the compose command for this project directory.
|
||||||
|
|
||||||
|
Policy:
|
||||||
|
- If `compose` wrapper exists (Infinito.Nexus): use it and delegate ALL logic to it.
|
||||||
|
- Else: use plain `docker compose` with --chdir.
|
||||||
|
- NO custom compose file/env detection in this project.
|
||||||
|
"""
|
||||||
|
pdir = Path(project_dir).resolve()
|
||||||
|
|
||||||
|
wrapper = shutil.which("compose")
|
||||||
|
if wrapper:
|
||||||
|
# "--" ensures wrapper stops parsing its own args.
|
||||||
|
return [wrapper, "--chdir", str(pdir), "--", *passthrough]
|
||||||
|
|
||||||
|
docker = shutil.which("docker")
|
||||||
|
if docker:
|
||||||
|
return [docker, "compose", "--chdir", str(pdir), *passthrough]
|
||||||
|
|
||||||
|
raise RuntimeError("Neither 'compose' nor 'docker' found in PATH")
|
||||||
|
|
||||||
|
|
||||||
|
def _find_compose_file(project_dir: str) -> Optional[Path]:
|
||||||
|
"""
|
||||||
|
Detect a compose file in `project_dir` (case-insensitive).
|
||||||
|
|
||||||
|
Supported names:
|
||||||
|
- compose.yml / compose.yaml
|
||||||
|
- docker-compose.yml / docker-compose.yaml
|
||||||
|
"""
|
||||||
|
pdir = Path(project_dir)
|
||||||
|
if not pdir.is_dir():
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Map lowercase filename -> actual Path (preserves original casing)
|
||||||
|
by_lower = {p.name.lower(): p for p in pdir.iterdir() if p.is_file()}
|
||||||
|
|
||||||
|
# Preferred order (policy decision)
|
||||||
|
candidates = [
|
||||||
|
"docker-compose.yml",
|
||||||
|
"docker-compose.yaml",
|
||||||
|
"compose.yml",
|
||||||
|
"compose.yaml",
|
||||||
|
]
|
||||||
|
|
||||||
|
for name in candidates:
|
||||||
|
found = by_lower.get(name)
|
||||||
|
if found is not None:
|
||||||
|
return found
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def hard_restart_docker_services(dir_path: str) -> None:
|
def hard_restart_docker_services(dir_path: str) -> None:
|
||||||
print(f"Hard restart docker-compose services in: {dir_path}", flush=True)
|
print(f"Hard restart compose services in: {dir_path}", flush=True)
|
||||||
subprocess.run(["docker-compose", "down"], cwd=dir_path, check=True)
|
|
||||||
subprocess.run(["docker-compose", "up", "-d"], cwd=dir_path, check=True)
|
down_cmd = _build_compose_cmd(dir_path, ["down"])
|
||||||
|
up_cmd = _build_compose_cmd(dir_path, ["up", "-d"])
|
||||||
|
|
||||||
|
print(">>> " + " ".join(down_cmd), flush=True)
|
||||||
|
subprocess.run(down_cmd, check=True)
|
||||||
|
|
||||||
|
print(">>> " + " ".join(up_cmd), flush=True)
|
||||||
|
subprocess.run(up_cmd, check=True)
|
||||||
|
|
||||||
|
|
||||||
def handle_docker_compose_services(
|
def handle_docker_compose_services(
|
||||||
parent_directory: str, hard_restart_required: list[str]
|
parent_directory: str,
|
||||||
|
hard_restart_required: list[str],
|
||||||
) -> None:
|
) -> None:
|
||||||
for entry in os.scandir(parent_directory):
|
for entry in os.scandir(parent_directory):
|
||||||
if not entry.is_dir():
|
if not entry.is_dir():
|
||||||
@@ -19,11 +84,12 @@ def handle_docker_compose_services(
|
|||||||
|
|
||||||
dir_path = entry.path
|
dir_path = entry.path
|
||||||
name = os.path.basename(dir_path)
|
name = os.path.basename(dir_path)
|
||||||
compose_file = os.path.join(dir_path, "docker-compose.yml")
|
|
||||||
|
|
||||||
print(f"Checking directory: {dir_path}", flush=True)
|
print(f"Checking directory: {dir_path}", flush=True)
|
||||||
if not os.path.isfile(compose_file):
|
|
||||||
print("No docker-compose.yml found. Skipping.", flush=True)
|
compose_file = _find_compose_file(dir_path)
|
||||||
|
if compose_file is None:
|
||||||
|
print("No supported compose file found. Skipping.", flush=True)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if name in hard_restart_required:
|
if name in hard_restart_required:
|
||||||
|
|||||||
@@ -115,8 +115,10 @@ def backup_database(
|
|||||||
dump_file = os.path.join(out_dir, f"{db_name}.backup.sql")
|
dump_file = os.path.join(out_dir, f"{db_name}.backup.sql")
|
||||||
|
|
||||||
if db_type == "mariadb":
|
if db_type == "mariadb":
|
||||||
|
# Force TCP so auth matches '<user>'@'%' instead of socket -> 'localhost'.
|
||||||
cmd = (
|
cmd = (
|
||||||
f"docker exec {container} /usr/bin/mariadb-dump "
|
f"docker exec {container} /usr/bin/mariadb-dump "
|
||||||
|
f"-h 127.0.0.1 --protocol=tcp "
|
||||||
f"-u {user} -p{password} {db_name}"
|
f"-u {user} -p{password} {db_name}"
|
||||||
)
|
)
|
||||||
_atomic_write_cmd(cmd, dump_file)
|
_atomic_write_cmd(cmd, dump_file)
|
||||||
@@ -127,7 +129,8 @@ def backup_database(
|
|||||||
try:
|
try:
|
||||||
cmd = (
|
cmd = (
|
||||||
f"PGPASSWORD={password} docker exec -i {container} "
|
f"PGPASSWORD={password} docker exec -i {container} "
|
||||||
f"pg_dump -U {user} -d {db_name} -h localhost"
|
f"pg_dump -U {user} -d {db_name} -h localhost "
|
||||||
|
f"--no-owner --no-privileges"
|
||||||
)
|
)
|
||||||
_atomic_write_cmd(cmd, dump_file)
|
_atomic_write_cmd(cmd, dump_file)
|
||||||
produced = True
|
produced = True
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from .shell import execute_shell_command
|
from .shell import BackupException, execute_shell_command
|
||||||
|
|
||||||
|
|
||||||
def get_image_info(container: str) -> str:
|
def get_image_info(container: str) -> str:
|
||||||
@@ -24,6 +24,43 @@ def containers_using_volume(volume_name: str) -> list[str]:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_swarm_task(container: str) -> bool:
|
||||||
|
"""Swarm-managed task containers must never be stopped or started
|
||||||
|
manually: the orchestrator replaces the stopped task and a later
|
||||||
|
`docker start` fails on the detached overlay network. A container that
|
||||||
|
vanished between listing and inspect (--rm one-shots, task-history GC)
|
||||||
|
counts as not stoppable instead of aborting the whole backup run; if the
|
||||||
|
container still exists the inspect failure re-raises, so a broken daemon
|
||||||
|
keeps failing the run loudly instead of silently skipping the stop."""
|
||||||
|
try:
|
||||||
|
out = execute_shell_command(
|
||||||
|
"docker inspect --format "
|
||||||
|
f"'{{{{index .Config.Labels \"com.docker.swarm.task.id\"}}}}' {container}"
|
||||||
|
)
|
||||||
|
except BackupException:
|
||||||
|
still_listed = execute_shell_command(
|
||||||
|
f"docker ps -a --filter name=^{container}$ --format '{{{{.Names}}}}'"
|
||||||
|
)
|
||||||
|
if still_listed and still_listed[0].strip():
|
||||||
|
raise
|
||||||
|
return True
|
||||||
|
return bool(out and out[0].strip())
|
||||||
|
|
||||||
|
|
||||||
|
def filter_stoppable(containers: list[str]) -> list[str]:
|
||||||
|
"""Containers baudolo may stop/start itself (everything but swarm tasks)."""
|
||||||
|
stoppable = []
|
||||||
|
for container in containers:
|
||||||
|
if is_swarm_task(container):
|
||||||
|
print(
|
||||||
|
f"Skipping stop/start for swarm task container '{container}'.",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
stoppable.append(container)
|
||||||
|
return stoppable
|
||||||
|
|
||||||
|
|
||||||
def change_containers_status(containers: list[str], status: str) -> None:
|
def change_containers_status(containers: list[str], status: str) -> None:
|
||||||
"""Stop or start a list of containers."""
|
"""Stop or start a list of containers."""
|
||||||
if not containers:
|
if not containers:
|
||||||
|
|||||||
@@ -47,18 +47,6 @@ def restore_mariadb_sql(
|
|||||||
# IMPORTANT:
|
# IMPORTANT:
|
||||||
# Do NOT hardcode 'mysql' here. Use the detected client.
|
# Do NOT hardcode 'mysql' here. Use the detected client.
|
||||||
# MariaDB 11 images may not contain the mysql binary at all.
|
# MariaDB 11 images may not contain the mysql binary at all.
|
||||||
docker_exec(
|
|
||||||
container,
|
|
||||||
[
|
|
||||||
client,
|
|
||||||
"-u",
|
|
||||||
user,
|
|
||||||
f"--password={password}",
|
|
||||||
"-e",
|
|
||||||
"SET FOREIGN_KEY_CHECKS=0;",
|
|
||||||
],
|
|
||||||
)
|
|
||||||
|
|
||||||
result = docker_exec(
|
result = docker_exec(
|
||||||
container,
|
container,
|
||||||
[
|
[
|
||||||
@@ -74,7 +62,16 @@ def restore_mariadb_sql(
|
|||||||
)
|
)
|
||||||
tables = result.stdout.decode().split()
|
tables = result.stdout.decode().split()
|
||||||
|
|
||||||
for tbl in tables:
|
if tables:
|
||||||
|
# SET FOREIGN_KEY_CHECKS is session-scoped, so it must share one
|
||||||
|
# client session with the DROPs or FK constraints still fire.
|
||||||
|
drop_sql = (
|
||||||
|
"SET FOREIGN_KEY_CHECKS=0; "
|
||||||
|
+ " ".join(
|
||||||
|
f"DROP TABLE IF EXISTS `{db_name}`.`{tbl}`;" for tbl in tables
|
||||||
|
)
|
||||||
|
+ " SET FOREIGN_KEY_CHECKS=1;"
|
||||||
|
)
|
||||||
docker_exec(
|
docker_exec(
|
||||||
container,
|
container,
|
||||||
[
|
[
|
||||||
@@ -83,22 +80,10 @@ def restore_mariadb_sql(
|
|||||||
user,
|
user,
|
||||||
f"--password={password}",
|
f"--password={password}",
|
||||||
"-e",
|
"-e",
|
||||||
f"DROP TABLE IF EXISTS `{db_name}`.`{tbl}`;",
|
drop_sql,
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
docker_exec(
|
|
||||||
container,
|
|
||||||
[
|
|
||||||
client,
|
|
||||||
"-u",
|
|
||||||
user,
|
|
||||||
f"--password={password}",
|
|
||||||
"-e",
|
|
||||||
"SET FOREIGN_KEY_CHECKS=1;",
|
|
||||||
],
|
|
||||||
)
|
|
||||||
|
|
||||||
with open(sql_path, "rb") as f:
|
with open(sql_path, "rb") as f:
|
||||||
docker_exec(
|
docker_exec(
|
||||||
container, [client, "-u", user, f"--password={password}", db_name], stdin=f
|
container, [client, "-u", user, f"--password={password}", db_name], stdin=f
|
||||||
|
|||||||
@@ -1,9 +1,41 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import tempfile
|
||||||
|
from collections.abc import Iterable, Iterator
|
||||||
|
|
||||||
from ..run import docker_exec
|
from ..run import docker_exec
|
||||||
|
|
||||||
|
_SUPERUSER_ONLY_PREFIXES = (b"COMMENT ON EXTENSION", b"ALTER DEFAULT PRIVILEGES")
|
||||||
|
|
||||||
|
|
||||||
|
def filter_superuser_only_lines(lines: Iterable[bytes]) -> Iterator[bytes]:
|
||||||
|
"""Drop superuser-only statements an app-level psql replay cannot run.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
lines: dump lines including their trailing newlines.
|
||||||
|
|
||||||
|
Yields:
|
||||||
|
Every line except top-level statements starting with a superuser-only
|
||||||
|
prefix. Lines inside COPY ... FROM stdin data blocks are passed
|
||||||
|
through untouched: a data row may legally start with the same bytes,
|
||||||
|
and dropping it would silently corrupt the restored table.
|
||||||
|
"""
|
||||||
|
in_copy = False
|
||||||
|
for line in lines:
|
||||||
|
if in_copy:
|
||||||
|
yield line
|
||||||
|
if line.rstrip(b"\r\n") == b"\\.":
|
||||||
|
in_copy = False
|
||||||
|
continue
|
||||||
|
if line.startswith(b"COPY ") and line.rstrip(b"\r\n").endswith(b"FROM stdin;"):
|
||||||
|
in_copy = True
|
||||||
|
yield line
|
||||||
|
continue
|
||||||
|
if line.startswith(_SUPERUSER_ONLY_PREFIXES):
|
||||||
|
continue
|
||||||
|
yield line
|
||||||
|
|
||||||
|
|
||||||
def restore_postgres_sql(
|
def restore_postgres_sql(
|
||||||
*,
|
*,
|
||||||
@@ -21,17 +53,48 @@ def restore_postgres_sql(
|
|||||||
docker_env = {"PGPASSWORD": password}
|
docker_env = {"PGPASSWORD": password}
|
||||||
|
|
||||||
if empty:
|
if empty:
|
||||||
|
# Owner-filtered: extension members (pg_trgm's set_limit) are superuser-owned; IF EXISTS absorbs CASCADE fallout.
|
||||||
drop_sql = r"""
|
drop_sql = r"""
|
||||||
DO $$ DECLARE r RECORD;
|
DO $$ DECLARE r RECORD;
|
||||||
BEGIN
|
BEGIN
|
||||||
FOR r IN (
|
FOR r IN (
|
||||||
SELECT table_name AS name, 'TABLE' AS type FROM information_schema.tables WHERE table_schema='public'
|
SELECT c.relname AS name,
|
||||||
|
CASE c.relkind
|
||||||
|
WHEN 'v' THEN 'VIEW'
|
||||||
|
WHEN 'm' THEN 'MATERIALIZED VIEW'
|
||||||
|
WHEN 'f' THEN 'FOREIGN TABLE'
|
||||||
|
ELSE 'TABLE'
|
||||||
|
END AS type
|
||||||
|
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||||
|
WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
||||||
|
AND pg_get_userbyid(c.relowner) = current_user
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT routine_name AS name, 'FUNCTION' AS type FROM information_schema.routines WHERE specific_schema='public'
|
SELECT p.proname AS name,
|
||||||
|
CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END AS type
|
||||||
|
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
||||||
|
WHERE n.nspname = 'public' AND p.prokind IN ('f', 'p', 'w')
|
||||||
|
AND pg_get_userbyid(p.proowner) = current_user
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT sequence_name AS name, 'SEQUENCE' AS type FROM information_schema.sequences WHERE sequence_schema='public'
|
SELECT c.relname AS name, 'SEQUENCE' AS type
|
||||||
|
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||||
|
WHERE n.nspname = 'public' AND c.relkind = 'S'
|
||||||
|
AND pg_get_userbyid(c.relowner) = current_user
|
||||||
|
UNION ALL
|
||||||
|
SELECT t.typname AS name, 'TYPE' AS type
|
||||||
|
FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace
|
||||||
|
WHERE n.nspname = 'public'
|
||||||
|
AND pg_get_userbyid(t.typowner) = current_user
|
||||||
|
AND (t.typtype IN ('e', 'd')
|
||||||
|
OR (t.typtype = 'c' AND EXISTS (
|
||||||
|
SELECT 1 FROM pg_class c2
|
||||||
|
WHERE c2.oid = t.typrelid AND c2.relkind = 'c')))
|
||||||
|
UNION ALL
|
||||||
|
SELECT col.collname AS name, 'COLLATION' AS type
|
||||||
|
FROM pg_collation col JOIN pg_namespace n ON n.oid = col.collnamespace
|
||||||
|
WHERE n.nspname = 'public'
|
||||||
|
AND pg_get_userbyid(col.collowner) = current_user
|
||||||
) LOOP
|
) LOOP
|
||||||
EXECUTE format('DROP %s public.%I CASCADE', r.type, r.name);
|
EXECUTE format('DROP %s IF EXISTS public.%I CASCADE', r.type, r.name);
|
||||||
END LOOP;
|
END LOOP;
|
||||||
END $$;
|
END $$;
|
||||||
"""
|
"""
|
||||||
@@ -42,11 +105,17 @@ END $$;
|
|||||||
docker_env=docker_env,
|
docker_env=docker_env,
|
||||||
)
|
)
|
||||||
|
|
||||||
with open(sql_path, "rb") as f:
|
# Filter into a spooled temp file instead of building the whole dump in
|
||||||
|
# memory: production dumps reach many GB and the previous read/splitlines/
|
||||||
|
# join needed roughly three times the dump size in RSS.
|
||||||
|
with open(sql_path, "rb") as src, tempfile.TemporaryFile() as filtered:
|
||||||
|
for line in filter_superuser_only_lines(src):
|
||||||
|
filtered.write(line)
|
||||||
|
filtered.seek(0)
|
||||||
docker_exec(
|
docker_exec(
|
||||||
container,
|
container,
|
||||||
["psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db_name],
|
["psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db_name],
|
||||||
stdin=f,
|
stdin=filtered,
|
||||||
docker_env=docker_env,
|
docker_env=docker_env,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
162
tests/e2e/test_e2e_mariadb_anonymous_preemption.py
Normal file
162
tests/e2e/test_e2e_mariadb_anonymous_preemption.py
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
Bug-repro for: mariadb-dump fails with `ERROR 1045 Access denied for user
|
||||||
|
'<u>'@'localhost' (using password: YES)` when only '<u>'@'%' is granted and a
|
||||||
|
preempting ''@'localhost' user is present.
|
||||||
|
|
||||||
|
The fix forces TCP loopback in baudolo.backup.db so the dump matches the
|
||||||
|
'<u>'@'%' grant instead of the socket->localhost auth row.
|
||||||
|
|
||||||
|
This file:
|
||||||
|
- builds the exact preconditions that triggered the production failure,
|
||||||
|
- as a NEGATIVE control, runs a socket-based mariadb-dump (== the old code path)
|
||||||
|
and asserts that it fails with the literal 1045 / @'localhost' error,
|
||||||
|
- as a POSITIVE proof, calls backup_database() (where the fix lives) against
|
||||||
|
the same DB container and asserts the dump file is produced and contains the
|
||||||
|
seed data.
|
||||||
|
|
||||||
|
Note: the volume-rsync stage of baudolo is intentionally NOT exercised here.
|
||||||
|
That stage needs root on /var/lib/docker/volumes, which is provided by the
|
||||||
|
DinD wrapper in `make test-e2e` but not by an on-host invocation. The bug we
|
||||||
|
are verifying is in the DB-dump stage, so testing backup_database() directly
|
||||||
|
keeps the assertion focused and the test runnable both on-host and in DinD.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import pandas
|
||||||
|
|
||||||
|
from baudolo.backup import db as db_mod
|
||||||
|
|
||||||
|
from .helpers import (
|
||||||
|
cleanup_docker,
|
||||||
|
require_docker,
|
||||||
|
run,
|
||||||
|
unique,
|
||||||
|
wait_for_mariadb,
|
||||||
|
wait_for_mariadb_sql,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestE2EMariaDBAnonymousPreemption(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls) -> None:
|
||||||
|
require_docker()
|
||||||
|
cls.prefix = unique("baudolo-e2e-mariadb-anon")
|
||||||
|
cls.db_container = f"{cls.prefix}-mariadb"
|
||||||
|
cls.db_volume = f"{cls.prefix}-mariadb-vol"
|
||||||
|
cls.containers = [cls.db_container]
|
||||||
|
cls.volumes = [cls.db_volume]
|
||||||
|
|
||||||
|
cls.db_name = "appdb"
|
||||||
|
cls.db_user = "tcponly"
|
||||||
|
cls.db_password = "tcponlypw"
|
||||||
|
cls.root_password = "rootpw"
|
||||||
|
|
||||||
|
run(["docker", "volume", "create", cls.db_volume])
|
||||||
|
|
||||||
|
# Boot WITHOUT MARIADB_USER/MARIADB_PASSWORD/MARIADB_DATABASE so the
|
||||||
|
# entrypoint does not auto-create '<u>'@'%'. We provision the user
|
||||||
|
# explicitly below to mirror the SQL path used by svc-db-mariadb.
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"run",
|
||||||
|
"-d",
|
||||||
|
"--name",
|
||||||
|
cls.db_container,
|
||||||
|
"-e",
|
||||||
|
f"MARIADB_ROOT_PASSWORD={cls.root_password}",
|
||||||
|
"-v",
|
||||||
|
f"{cls.db_volume}:/var/lib/mysql",
|
||||||
|
"mariadb:12.2",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
wait_for_mariadb(
|
||||||
|
cls.db_container, root_password=cls.root_password, timeout_s=120
|
||||||
|
)
|
||||||
|
|
||||||
|
# Provision: '<u>'@'%' (the app/backup grant) + anonymous ''@'localhost'
|
||||||
|
# (the preemption trigger). Mirrors the production state that produced
|
||||||
|
# `ERROR 1045 ... '<u>'@'localhost' (using password: YES)`.
|
||||||
|
bootstrap_sql = (
|
||||||
|
f"CREATE DATABASE {cls.db_name};"
|
||||||
|
f"CREATE USER '{cls.db_user}'@'%' IDENTIFIED BY '{cls.db_password}';"
|
||||||
|
f"GRANT ALL PRIVILEGES ON {cls.db_name}.* TO '{cls.db_user}'@'%';"
|
||||||
|
f"CREATE USER ''@'localhost' IDENTIFIED BY 'anonpw-not-{cls.db_password}';"
|
||||||
|
"FLUSH PRIVILEGES;"
|
||||||
|
f"CREATE TABLE {cls.db_name}.t (id INT PRIMARY KEY, v VARCHAR(50));"
|
||||||
|
f"INSERT INTO {cls.db_name}.t VALUES (1,'ok');"
|
||||||
|
)
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"exec",
|
||||||
|
cls.db_container,
|
||||||
|
"sh",
|
||||||
|
"-lc",
|
||||||
|
f'mariadb -uroot --protocol=socket -e "{bootstrap_sql}"',
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Sanity: '<u>' can log in over TCP (matches '%'). If THIS fails,
|
||||||
|
# the precondition for the fix to even apply is broken.
|
||||||
|
wait_for_mariadb_sql(
|
||||||
|
cls.db_container, user=cls.db_user, password=cls.db_password, timeout_s=60
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls) -> None:
|
||||||
|
cleanup_docker(containers=cls.containers, volumes=cls.volumes)
|
||||||
|
|
||||||
|
def test_negative_control_socket_dump_fails_with_1045(self) -> None:
|
||||||
|
# Reproduces the OLD code path (no -h/--protocol). MUST fail with 1045
|
||||||
|
# under the configured preemption. If this ever starts passing, either
|
||||||
|
# the MariaDB auth semantics changed or the anonymous-user setup did
|
||||||
|
# not take effect — in both cases the positive test below loses its
|
||||||
|
# ability to discriminate "fix works" vs "bug never reproduced".
|
||||||
|
p = run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"exec",
|
||||||
|
self.db_container,
|
||||||
|
"sh",
|
||||||
|
"-lc",
|
||||||
|
f"mariadb-dump -u{self.db_user} -p{self.db_password} {self.db_name}",
|
||||||
|
],
|
||||||
|
capture=True,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
self.assertNotEqual(p.returncode, 0, "socket-based dump unexpectedly succeeded")
|
||||||
|
self.assertIn("1045", (p.stderr or "") + (p.stdout or ""))
|
||||||
|
self.assertIn("@'localhost'", (p.stderr or "") + (p.stdout or ""))
|
||||||
|
|
||||||
|
def test_backup_database_succeeds_with_tcp_fix(self) -> None:
|
||||||
|
# Drives the function where the fix lives. No rsync, no privileged
|
||||||
|
# paths — just the dump that the negative-control proved is failing
|
||||||
|
# under the same preemption setup.
|
||||||
|
with tempfile.TemporaryDirectory() as volume_dir:
|
||||||
|
df = pandas.DataFrame(
|
||||||
|
[(self.db_container, self.db_name, self.db_user, self.db_password)],
|
||||||
|
columns=["instance", "database", "username", "password"],
|
||||||
|
)
|
||||||
|
produced = db_mod.backup_database(
|
||||||
|
container=self.db_container,
|
||||||
|
volume_dir=volume_dir,
|
||||||
|
db_type="mariadb",
|
||||||
|
databases_df=df,
|
||||||
|
database_containers=[self.db_container],
|
||||||
|
)
|
||||||
|
self.assertTrue(produced, "backup_database did not produce a dump")
|
||||||
|
dump_path = os.path.join(volume_dir, "sql", f"{self.db_name}.backup.sql")
|
||||||
|
self.assertTrue(os.path.isfile(dump_path), f"expected dump at {dump_path}")
|
||||||
|
with open(dump_path, "r", encoding="utf-8", errors="replace") as f:
|
||||||
|
content = f.read()
|
||||||
|
self.assertIn("INSERT INTO", content)
|
||||||
|
self.assertIn("'ok'", content)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main(verbosity=2)
|
||||||
196
tests/e2e/test_e2e_swarm_task_skip.py
Normal file
196
tests/e2e/test_e2e_swarm_task_skip.py
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
# tests/e2e/test_e2e_swarm_task_skip.py
|
||||||
|
#
|
||||||
|
# Reproduces the swarm flake fixed on this branch: baudolo used to stop a
|
||||||
|
# swarm task container around the volume file backup because its image was
|
||||||
|
# not whitelisted; the orchestrator immediately replaced the stopped task and
|
||||||
|
# the later `docker start` failed on the detached overlay network, killing
|
||||||
|
# the backup run. With the fix the task container is skipped (backed up hot):
|
||||||
|
# the backup succeeds, the very same container instance keeps running, and
|
||||||
|
# the service never has to replace a task.
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from .helpers import (
|
||||||
|
backup_path,
|
||||||
|
backup_run,
|
||||||
|
create_minimal_compose_dir,
|
||||||
|
ensure_empty_dir,
|
||||||
|
latest_version_dir,
|
||||||
|
require_docker,
|
||||||
|
run,
|
||||||
|
unique,
|
||||||
|
write_databases_csv,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _swarm_state() -> str:
|
||||||
|
return run(
|
||||||
|
["docker", "info", "--format", "{{.Swarm.LocalNodeState}}"]
|
||||||
|
).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _task_container_id(service: str, timeout_s: int = 60) -> str:
|
||||||
|
deadline = time.time() + timeout_s
|
||||||
|
while time.time() < deadline:
|
||||||
|
out = run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"ps",
|
||||||
|
"--filter",
|
||||||
|
f"label=com.docker.swarm.service.name={service}",
|
||||||
|
"--format",
|
||||||
|
"{{.ID}}",
|
||||||
|
]
|
||||||
|
).stdout.strip()
|
||||||
|
if out:
|
||||||
|
return out.splitlines()[0]
|
||||||
|
time.sleep(2)
|
||||||
|
raise RuntimeError(f"No running task container for service {service}")
|
||||||
|
|
||||||
|
|
||||||
|
def _started_at(container_id: str) -> str:
|
||||||
|
return run(
|
||||||
|
["docker", "inspect", "--format", "{{.State.StartedAt}}", container_id]
|
||||||
|
).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
class TestE2ESwarmTaskSkip(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls) -> None:
|
||||||
|
require_docker()
|
||||||
|
cls.prefix = unique("baudolo-e2e-swarm-skip")
|
||||||
|
cls.backups_dir = f"/tmp/{cls.prefix}/Backups"
|
||||||
|
ensure_empty_dir(cls.backups_dir)
|
||||||
|
cls.compose_dir = create_minimal_compose_dir(f"/tmp/{cls.prefix}")
|
||||||
|
cls.repo_name = cls.prefix
|
||||||
|
|
||||||
|
cls.swarm_initted = False
|
||||||
|
if _swarm_state() != "active":
|
||||||
|
run(["docker", "swarm", "init", "--advertise-addr", "127.0.0.1"])
|
||||||
|
cls.swarm_initted = True
|
||||||
|
|
||||||
|
cls.volume = f"{cls.prefix}-vol"
|
||||||
|
cls.service = f"{cls.prefix}-svc"
|
||||||
|
cls.volumes = [cls.volume]
|
||||||
|
|
||||||
|
run(["docker", "volume", "create", cls.volume])
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"-v",
|
||||||
|
f"{cls.volume}:/data",
|
||||||
|
"alpine:3.20",
|
||||||
|
"sh",
|
||||||
|
"-lc",
|
||||||
|
"echo 'swarm-payload' > /data/payload.txt",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"service",
|
||||||
|
"create",
|
||||||
|
"--name",
|
||||||
|
cls.service,
|
||||||
|
"--replicas",
|
||||||
|
"1",
|
||||||
|
"--mount",
|
||||||
|
f"type=volume,source={cls.volume},target=/data",
|
||||||
|
"alpine:3.20",
|
||||||
|
"sleep",
|
||||||
|
"3600",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
cls.task_cid = _task_container_id(cls.service)
|
||||||
|
cls.task_started_at = _started_at(cls.task_cid)
|
||||||
|
|
||||||
|
cls.databases_csv = f"/tmp/{cls.prefix}/databases.csv"
|
||||||
|
write_databases_csv(cls.databases_csv, [])
|
||||||
|
|
||||||
|
# Whitelist that matches nothing: on main this forces a stop of every
|
||||||
|
# container at the volume, i.e. exactly the flake; on this branch the
|
||||||
|
# swarm task must be skipped instead. (An empty list would leave the
|
||||||
|
# --images-no-stop-required flag without arguments and argparse-fail.)
|
||||||
|
backup_run(
|
||||||
|
backups_dir=cls.backups_dir,
|
||||||
|
repo_name=cls.repo_name,
|
||||||
|
compose_dir=cls.compose_dir,
|
||||||
|
databases_csv=cls.databases_csv,
|
||||||
|
database_containers=["dummy-db"],
|
||||||
|
images_no_stop_required=["image-that-matches-nothing"],
|
||||||
|
)
|
||||||
|
cls.hash, cls.version = latest_version_dir(cls.backups_dir, cls.repo_name)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls) -> None:
|
||||||
|
run(["docker", "service", "rm", cls.service], check=False)
|
||||||
|
deadline = time.time() + 30
|
||||||
|
while time.time() < deadline:
|
||||||
|
out = run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"ps",
|
||||||
|
"-aq",
|
||||||
|
"--filter",
|
||||||
|
f"label=com.docker.swarm.service.name={cls.service}",
|
||||||
|
],
|
||||||
|
check=False,
|
||||||
|
).stdout.strip()
|
||||||
|
if not out:
|
||||||
|
break
|
||||||
|
time.sleep(2)
|
||||||
|
for v in cls.volumes:
|
||||||
|
run(["docker", "volume", "rm", "-f", v], check=False)
|
||||||
|
if cls.swarm_initted:
|
||||||
|
run(["docker", "swarm", "leave", "--force"], check=False)
|
||||||
|
|
||||||
|
def test_volume_backed_up_hot(self) -> None:
|
||||||
|
p = (
|
||||||
|
backup_path(
|
||||||
|
self.backups_dir,
|
||||||
|
self.repo_name,
|
||||||
|
self.version,
|
||||||
|
self.volume,
|
||||||
|
)
|
||||||
|
/ "files"
|
||||||
|
/ "payload.txt"
|
||||||
|
)
|
||||||
|
self.assertTrue(p.is_file(), f"Expected backed up file at: {p}")
|
||||||
|
|
||||||
|
def test_task_container_never_stopped(self) -> None:
|
||||||
|
out = run(
|
||||||
|
["docker", "ps", "-q", "--no-trunc", "--filter", f"id={self.task_cid}"]
|
||||||
|
).stdout.strip()
|
||||||
|
self.assertTrue(
|
||||||
|
out.startswith(self.task_cid) or self.task_cid.startswith(out.strip()[:12]),
|
||||||
|
f"Task container {self.task_cid} is no longer running",
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
self.task_started_at,
|
||||||
|
_started_at(self.task_cid),
|
||||||
|
"Task container was restarted during the backup",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_service_never_replaced_the_task(self) -> None:
|
||||||
|
states = run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"service",
|
||||||
|
"ps",
|
||||||
|
self.service,
|
||||||
|
"--format",
|
||||||
|
"{{.DesiredState}} {{.CurrentState}}",
|
||||||
|
]
|
||||||
|
).stdout.strip()
|
||||||
|
lines = [line for line in states.splitlines() if line.strip()]
|
||||||
|
self.assertEqual(
|
||||||
|
len(lines), 1, f"Service task history shows replacements:\n{states}"
|
||||||
|
)
|
||||||
|
self.assertIn("Running", lines[0])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
0
tests/unit/backup/__init__.py
Normal file
0
tests/unit/backup/__init__.py
Normal file
77
tests/unit/backup/test_app_databases_csv.py
Normal file
77
tests/unit/backup/test_app_databases_csv.py
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import io
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from contextlib import redirect_stderr
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
# Adjust if your package name/import path differs.
|
||||||
|
from baudolo.backup.app import _load_databases_df
|
||||||
|
|
||||||
|
|
||||||
|
EXPECTED_COLUMNS = ["instance", "database", "username", "password"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestLoadDatabasesDf(unittest.TestCase):
|
||||||
|
def test_missing_csv_is_handled_with_warning_and_empty_df(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
missing_path = os.path.join(td, "does-not-exist.csv")
|
||||||
|
|
||||||
|
buf = io.StringIO()
|
||||||
|
with redirect_stderr(buf):
|
||||||
|
df = _load_databases_df(missing_path)
|
||||||
|
|
||||||
|
stderr = buf.getvalue()
|
||||||
|
self.assertIn("WARNING:", stderr)
|
||||||
|
self.assertIn("databases.csv not found", stderr)
|
||||||
|
|
||||||
|
self.assertIsInstance(df, pd.DataFrame)
|
||||||
|
self.assertListEqual(list(df.columns), EXPECTED_COLUMNS)
|
||||||
|
self.assertTrue(df.empty)
|
||||||
|
|
||||||
|
def test_empty_csv_is_handled_with_warning_and_empty_df(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
empty_path = os.path.join(td, "databases.csv")
|
||||||
|
# Create an empty file (0 bytes)
|
||||||
|
with open(empty_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write("")
|
||||||
|
|
||||||
|
buf = io.StringIO()
|
||||||
|
with redirect_stderr(buf):
|
||||||
|
df = _load_databases_df(empty_path)
|
||||||
|
|
||||||
|
stderr = buf.getvalue()
|
||||||
|
self.assertIn("WARNING:", stderr)
|
||||||
|
self.assertIn("exists but is empty", stderr)
|
||||||
|
|
||||||
|
self.assertIsInstance(df, pd.DataFrame)
|
||||||
|
self.assertListEqual(list(df.columns), EXPECTED_COLUMNS)
|
||||||
|
self.assertTrue(df.empty)
|
||||||
|
|
||||||
|
def test_valid_csv_loads_without_warning(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
csv_path = os.path.join(td, "databases.csv")
|
||||||
|
|
||||||
|
content = "instance;database;username;password\nmyapp;*;dbuser;secret\n"
|
||||||
|
with open(csv_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(content)
|
||||||
|
|
||||||
|
buf = io.StringIO()
|
||||||
|
with redirect_stderr(buf):
|
||||||
|
df = _load_databases_df(csv_path)
|
||||||
|
|
||||||
|
stderr = buf.getvalue()
|
||||||
|
self.assertEqual(stderr, "") # no warning expected
|
||||||
|
|
||||||
|
self.assertIsInstance(df, pd.DataFrame)
|
||||||
|
self.assertListEqual(list(df.columns), EXPECTED_COLUMNS)
|
||||||
|
self.assertEqual(len(df), 1)
|
||||||
|
self.assertEqual(df.loc[0, "instance"], "myapp")
|
||||||
|
self.assertEqual(df.loc[0, "database"], "*")
|
||||||
|
self.assertEqual(df.loc[0, "username"], "dbuser")
|
||||||
|
self.assertEqual(df.loc[0, "password"], "secret")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
255
tests/unit/backup/test_compose.py
Normal file
255
tests/unit/backup/test_compose.py
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
|
||||||
|
def _touch(p: Path) -> None:
|
||||||
|
p.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# If the path already exists as a directory (e.g. ".env" created by ".env/env"),
|
||||||
|
# remove it so we can create a file with the same name.
|
||||||
|
if p.exists() and p.is_dir():
|
||||||
|
shutil.rmtree(p)
|
||||||
|
|
||||||
|
p.write_text("x", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _setup_compose_dir(
|
||||||
|
tmp_path: Path,
|
||||||
|
name: str = "mailu",
|
||||||
|
*,
|
||||||
|
compose_name: str = "docker-compose.yml",
|
||||||
|
with_override: bool = False,
|
||||||
|
with_ca_override: bool = False,
|
||||||
|
env_layout: str | None = None, # None | ".env" | ".env/env"
|
||||||
|
) -> Path:
|
||||||
|
d = tmp_path / name
|
||||||
|
d.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
_touch(d / compose_name)
|
||||||
|
|
||||||
|
if with_override:
|
||||||
|
_touch(d / "docker-compose.override.yml")
|
||||||
|
|
||||||
|
if with_ca_override:
|
||||||
|
_touch(d / "docker-compose.ca.override.yml")
|
||||||
|
|
||||||
|
if env_layout == ".env":
|
||||||
|
_touch(d / ".env")
|
||||||
|
elif env_layout == ".env/env":
|
||||||
|
_touch(d / ".env" / "env")
|
||||||
|
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
class TestCompose(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls) -> None:
|
||||||
|
from baudolo.backup import compose as mod
|
||||||
|
|
||||||
|
cls.compose_mod = mod
|
||||||
|
|
||||||
|
def test_find_compose_file_supports_all_valid_names_case_insensitive(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
tmp_path = Path(td)
|
||||||
|
|
||||||
|
variants = [
|
||||||
|
"compose.yml",
|
||||||
|
"compose.yaml",
|
||||||
|
"docker-compose.yml",
|
||||||
|
"docker-compose.yaml",
|
||||||
|
"docker-compose.yAml",
|
||||||
|
]
|
||||||
|
|
||||||
|
for i, name in enumerate(variants):
|
||||||
|
d = _setup_compose_dir(
|
||||||
|
tmp_path,
|
||||||
|
name=f"project{i}",
|
||||||
|
compose_name=name,
|
||||||
|
)
|
||||||
|
found = self.compose_mod._find_compose_file(str(d))
|
||||||
|
self.assertIsNotNone(found)
|
||||||
|
self.assertEqual(found.name, name)
|
||||||
|
|
||||||
|
def test_find_compose_file_returns_none_when_missing(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
tmp_path = Path(td)
|
||||||
|
d = tmp_path / "empty"
|
||||||
|
d.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
found = self.compose_mod._find_compose_file(str(d))
|
||||||
|
self.assertIsNone(found)
|
||||||
|
|
||||||
|
def test_build_cmd_uses_wrapper_when_present(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
tmp_path = Path(td)
|
||||||
|
d = _setup_compose_dir(
|
||||||
|
tmp_path,
|
||||||
|
with_override=True,
|
||||||
|
with_ca_override=True,
|
||||||
|
env_layout=".env",
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_which(name: str):
|
||||||
|
if name == "compose":
|
||||||
|
return "/usr/local/bin/compose"
|
||||||
|
return None
|
||||||
|
|
||||||
|
with patch.object(self.compose_mod.shutil, "which", fake_which):
|
||||||
|
cmd = self.compose_mod._build_compose_cmd(str(d), ["up", "-d"])
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
cmd,
|
||||||
|
[
|
||||||
|
"/usr/local/bin/compose",
|
||||||
|
"--chdir",
|
||||||
|
str(d.resolve()),
|
||||||
|
"--",
|
||||||
|
"up",
|
||||||
|
"-d",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_build_cmd_fallback_uses_plain_docker_compose_chdir(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
tmp_path = Path(td)
|
||||||
|
d = _setup_compose_dir(
|
||||||
|
tmp_path,
|
||||||
|
with_override=True,
|
||||||
|
with_ca_override=True,
|
||||||
|
env_layout=".env",
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_which(name: str):
|
||||||
|
if name == "compose":
|
||||||
|
return None
|
||||||
|
if name == "docker":
|
||||||
|
return "/usr/bin/docker"
|
||||||
|
return None
|
||||||
|
|
||||||
|
with patch.object(self.compose_mod.shutil, "which", fake_which):
|
||||||
|
cmd = self.compose_mod._build_compose_cmd(
|
||||||
|
str(d), ["up", "-d", "--force-recreate"]
|
||||||
|
)
|
||||||
|
|
||||||
|
expected: List[str] = [
|
||||||
|
"/usr/bin/docker",
|
||||||
|
"compose",
|
||||||
|
"--chdir",
|
||||||
|
str(d.resolve()),
|
||||||
|
"up",
|
||||||
|
"-d",
|
||||||
|
"--force-recreate",
|
||||||
|
]
|
||||||
|
self.assertEqual(cmd, expected)
|
||||||
|
|
||||||
|
def test_hard_restart_calls_run_twice_with_correct_cmds_wrapper(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
tmp_path = Path(td)
|
||||||
|
d = _setup_compose_dir(tmp_path, name="mailu", env_layout=".env")
|
||||||
|
|
||||||
|
def fake_which(name: str):
|
||||||
|
if name == "compose":
|
||||||
|
return "/usr/local/bin/compose"
|
||||||
|
return None
|
||||||
|
|
||||||
|
with patch.object(self.compose_mod.shutil, "which", fake_which):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_run(cmd, check: bool):
|
||||||
|
calls.append((cmd, check))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
with patch.object(self.compose_mod.subprocess, "run", fake_run):
|
||||||
|
self.compose_mod.hard_restart_docker_services(str(d))
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
calls,
|
||||||
|
[
|
||||||
|
(
|
||||||
|
[
|
||||||
|
"/usr/local/bin/compose",
|
||||||
|
"--chdir",
|
||||||
|
str(d.resolve()),
|
||||||
|
"--",
|
||||||
|
"down",
|
||||||
|
],
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
[
|
||||||
|
"/usr/local/bin/compose",
|
||||||
|
"--chdir",
|
||||||
|
str(d.resolve()),
|
||||||
|
"--",
|
||||||
|
"up",
|
||||||
|
"-d",
|
||||||
|
],
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_hard_restart_calls_run_twice_with_correct_cmds_fallback(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
tmp_path = Path(td)
|
||||||
|
d = _setup_compose_dir(
|
||||||
|
tmp_path,
|
||||||
|
name="mailu",
|
||||||
|
with_override=True,
|
||||||
|
with_ca_override=True,
|
||||||
|
env_layout=".env/env",
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_which(name: str):
|
||||||
|
if name == "compose":
|
||||||
|
return None
|
||||||
|
if name == "docker":
|
||||||
|
return "/usr/bin/docker"
|
||||||
|
return None
|
||||||
|
|
||||||
|
with patch.object(self.compose_mod.shutil, "which", fake_which):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_run(cmd, check: bool):
|
||||||
|
calls.append((cmd, check))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
with patch.object(self.compose_mod.subprocess, "run", fake_run):
|
||||||
|
self.compose_mod.hard_restart_docker_services(str(d))
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
calls,
|
||||||
|
[
|
||||||
|
(
|
||||||
|
[
|
||||||
|
"/usr/bin/docker",
|
||||||
|
"compose",
|
||||||
|
"--chdir",
|
||||||
|
str(d.resolve()),
|
||||||
|
"down",
|
||||||
|
],
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
[
|
||||||
|
"/usr/bin/docker",
|
||||||
|
"compose",
|
||||||
|
"--chdir",
|
||||||
|
str(d.resolve()),
|
||||||
|
"up",
|
||||||
|
"-d",
|
||||||
|
],
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main(verbosity=2)
|
||||||
70
tests/unit/backup/test_db_mariadb_dump.py
Normal file
70
tests/unit/backup/test_db_mariadb_dump.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pandas
|
||||||
|
|
||||||
|
from baudolo.backup import db as db_mod
|
||||||
|
|
||||||
|
|
||||||
|
def _df(rows):
|
||||||
|
return pandas.DataFrame(
|
||||||
|
rows, columns=["instance", "database", "username", "password"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _capture_commands(*, db_type, rows, container):
|
||||||
|
captured = []
|
||||||
|
|
||||||
|
def _capture(cmd):
|
||||||
|
captured.append(cmd)
|
||||||
|
return []
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
with patch.object(db_mod, "execute_shell_command", side_effect=_capture):
|
||||||
|
db_mod.backup_database(
|
||||||
|
container=container,
|
||||||
|
volume_dir=td,
|
||||||
|
db_type=db_type,
|
||||||
|
databases_df=_df(rows),
|
||||||
|
database_containers=[container],
|
||||||
|
)
|
||||||
|
return captured
|
||||||
|
|
||||||
|
|
||||||
|
class TestMariaDBDumpUsesTCP(unittest.TestCase):
|
||||||
|
# Regression guard for 'Access denied for user <user>@localhost' when only
|
||||||
|
# '<user>'@'%' is granted: the in-container mariadb-dump MUST force TCP so
|
||||||
|
# the connection is auth-matched against '%' instead of socket->localhost.
|
||||||
|
|
||||||
|
def test_mariadb_dump_forces_tcp_loopback(self):
|
||||||
|
captured = _capture_commands(
|
||||||
|
db_type="mariadb",
|
||||||
|
rows=[("mariadb", "appdb", "appuser", "s3cret")],
|
||||||
|
container="mariadb",
|
||||||
|
)
|
||||||
|
dump_cmds = [c for c in captured if "mariadb-dump" in c]
|
||||||
|
self.assertEqual(
|
||||||
|
len(dump_cmds), 1, f"expected one dump command, got: {captured}"
|
||||||
|
)
|
||||||
|
|
||||||
|
cmd = dump_cmds[0]
|
||||||
|
self.assertIn("-h 127.0.0.1", cmd)
|
||||||
|
self.assertIn("--protocol=tcp", cmd)
|
||||||
|
self.assertIn("-u appuser", cmd)
|
||||||
|
self.assertIn("-ps3cret", cmd)
|
||||||
|
self.assertIn(" appdb", cmd)
|
||||||
|
|
||||||
|
def test_postgres_dump_unaffected(self):
|
||||||
|
captured = _capture_commands(
|
||||||
|
db_type="postgres",
|
||||||
|
rows=[("pg", "appdb", "appuser", "s3cret")],
|
||||||
|
container="pg",
|
||||||
|
)
|
||||||
|
dump_cmds = [c for c in captured if "pg_dump" in c and "pg_dumpall" not in c]
|
||||||
|
self.assertEqual(len(dump_cmds), 1)
|
||||||
|
self.assertNotIn("--protocol=tcp", dump_cmds[0])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main(verbosity=2)
|
||||||
53
tests/unit/backup/test_docker_swarm.py
Normal file
53
tests/unit/backup/test_docker_swarm.py
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from baudolo.backup import docker as docker_mod
|
||||||
|
from baudolo.backup.shell import BackupException
|
||||||
|
|
||||||
|
|
||||||
|
class TestIsSwarmTask(unittest.TestCase):
|
||||||
|
@patch.object(docker_mod, "execute_shell_command", return_value=["task-id-123"])
|
||||||
|
def test_true_when_task_label_present(self, _mock) -> None:
|
||||||
|
self.assertTrue(docker_mod.is_swarm_task("c1"))
|
||||||
|
|
||||||
|
@patch.object(docker_mod, "execute_shell_command", return_value=[""])
|
||||||
|
def test_false_when_label_empty(self, _mock) -> None:
|
||||||
|
self.assertFalse(docker_mod.is_swarm_task("c1"))
|
||||||
|
|
||||||
|
@patch.object(docker_mod, "execute_shell_command", return_value=[])
|
||||||
|
def test_false_when_no_output(self, _mock) -> None:
|
||||||
|
self.assertFalse(docker_mod.is_swarm_task("c1"))
|
||||||
|
|
||||||
|
@patch.object(
|
||||||
|
docker_mod,
|
||||||
|
"execute_shell_command",
|
||||||
|
side_effect=[BackupException("gone"), []],
|
||||||
|
)
|
||||||
|
def test_vanished_container_counts_as_not_stoppable(self, _mock) -> None:
|
||||||
|
# A container removed between listing and inspect must not abort the
|
||||||
|
# whole backup run; treating it as a swarm task keeps it out of every
|
||||||
|
# stop/start and image-inspect path.
|
||||||
|
self.assertTrue(docker_mod.is_swarm_task("gone-container"))
|
||||||
|
|
||||||
|
@patch.object(
|
||||||
|
docker_mod,
|
||||||
|
"execute_shell_command",
|
||||||
|
side_effect=[BackupException("daemon hiccup"), ["still-here"]],
|
||||||
|
)
|
||||||
|
def test_inspect_failure_on_existing_container_still_fails(self, _mock) -> None:
|
||||||
|
# If the container still exists, an inspect failure must keep failing
|
||||||
|
# the run: silently skipping the stop would back up a hot volume and
|
||||||
|
# report green without the stop guarantee.
|
||||||
|
with self.assertRaises(BackupException):
|
||||||
|
docker_mod.is_swarm_task("still-here")
|
||||||
|
|
||||||
|
|
||||||
|
class TestFilterStoppable(unittest.TestCase):
|
||||||
|
@patch.object(docker_mod, "is_swarm_task", side_effect=[False, True, False])
|
||||||
|
def test_mixed_list_keeps_order_and_drops_tasks(self, _mock) -> None:
|
||||||
|
result = docker_mod.filter_stoppable(["plain-1", "swarm-task", "plain-2"])
|
||||||
|
self.assertEqual(result, ["plain-1", "plain-2"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
0
tests/unit/restore/__init__.py
Normal file
0
tests/unit/restore/__init__.py
Normal file
44
tests/unit/restore/test_mariadb_empty_drop.py
Normal file
44
tests/unit/restore/test_mariadb_empty_drop.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from baudolo.restore.db import mariadb as mariadb_mod
|
||||||
|
|
||||||
|
|
||||||
|
class TestMariadbEmptyDrop(unittest.TestCase):
|
||||||
|
def test_drops_run_in_one_session_with_fk_checks_off(self) -> None:
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def _capture(container, argv, **kwargs):
|
||||||
|
calls.append(argv)
|
||||||
|
result = MagicMock()
|
||||||
|
result.stdout = b"users\nfetches\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".sql") as sql:
|
||||||
|
sql.write(b"CREATE TABLE t (id int);\n")
|
||||||
|
sql.flush()
|
||||||
|
with (
|
||||||
|
patch.object(mariadb_mod, "docker_exec", side_effect=_capture),
|
||||||
|
patch.object(mariadb_mod, "_pick_client", return_value="mariadb"),
|
||||||
|
):
|
||||||
|
mariadb_mod.restore_mariadb_sql(
|
||||||
|
container="db",
|
||||||
|
db_name="mailu",
|
||||||
|
user="mailu",
|
||||||
|
password="pw",
|
||||||
|
sql_path=sql.name,
|
||||||
|
empty=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
drop_calls = [argv for argv in calls if any("DROP TABLE" in a for a in argv)]
|
||||||
|
self.assertEqual(len(drop_calls), 1, f"expected ONE drop session: {calls}")
|
||||||
|
drop_sql = drop_calls[0][-1]
|
||||||
|
self.assertTrue(drop_sql.startswith("SET FOREIGN_KEY_CHECKS=0; "))
|
||||||
|
self.assertIn("DROP TABLE IF EXISTS `mailu`.`users`;", drop_sql)
|
||||||
|
self.assertIn("DROP TABLE IF EXISTS `mailu`.`fetches`;", drop_sql)
|
||||||
|
self.assertTrue(drop_sql.endswith("SET FOREIGN_KEY_CHECKS=1;"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
43
tests/unit/restore/test_postgres_empty_drop.py
Normal file
43
tests/unit/restore/test_postgres_empty_drop.py
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
"""The --empty pre-clean drop must cover every object class a dump can
|
||||||
|
re-CREATE ahead of tables; a missed class aborts the replay under
|
||||||
|
ON_ERROR_STOP (OpenProject's ICU collation public.versions_name did)."""
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from baudolo.restore.db import postgres
|
||||||
|
|
||||||
|
|
||||||
|
class TestPostgresEmptyDrop(unittest.TestCase):
|
||||||
|
def _drop_sql(self) -> str:
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".sql") as fh:
|
||||||
|
Path(fh.name).write_bytes(b"SELECT 1;\n")
|
||||||
|
with mock.patch.object(postgres, "docker_exec") as run:
|
||||||
|
postgres.restore_postgres_sql(
|
||||||
|
container="c",
|
||||||
|
db_name="db",
|
||||||
|
user="u",
|
||||||
|
password="p",
|
||||||
|
sql_path=fh.name,
|
||||||
|
empty=True,
|
||||||
|
)
|
||||||
|
first_call = run.call_args_list[0]
|
||||||
|
return first_call.kwargs["stdin"].decode()
|
||||||
|
|
||||||
|
def test_drop_covers_collations(self) -> None:
|
||||||
|
sql = self._drop_sql()
|
||||||
|
self.assertIn("pg_collation", sql)
|
||||||
|
self.assertIn("'COLLATION' AS type", sql)
|
||||||
|
self.assertIn("pg_get_userbyid(col.collowner) = current_user", sql)
|
||||||
|
|
||||||
|
def test_drop_still_covers_the_other_classes(self) -> None:
|
||||||
|
sql = self._drop_sql()
|
||||||
|
for marker in ("pg_class", "pg_proc", "'SEQUENCE' AS type", "'TYPE' AS type"):
|
||||||
|
self.assertIn(marker, sql)
|
||||||
|
self.assertIn("DROP %s IF EXISTS public.%I CASCADE", sql)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
63
tests/unit/restore/test_postgres_filter.py
Normal file
63
tests/unit/restore/test_postgres_filter.py
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from baudolo.restore.db.postgres import filter_superuser_only_lines
|
||||||
|
|
||||||
|
|
||||||
|
def _filter(raw: bytes) -> bytes:
|
||||||
|
return b"".join(filter_superuser_only_lines(raw.splitlines(keepends=True)))
|
||||||
|
|
||||||
|
|
||||||
|
class TestFilterSuperuserOnlyLines(unittest.TestCase):
|
||||||
|
def test_drops_superuser_only_statements(self) -> None:
|
||||||
|
raw = (
|
||||||
|
b"CREATE TABLE t (id int);\n"
|
||||||
|
b"COMMENT ON EXTENSION pg_trgm IS 'trigram';\n"
|
||||||
|
b"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO x;\n"
|
||||||
|
b"INSERT INTO t VALUES (1);\n"
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
_filter(raw),
|
||||||
|
b"CREATE TABLE t (id int);\nINSERT INTO t VALUES (1);\n",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_copy_data_rows_are_never_filtered(self) -> None:
|
||||||
|
raw = (
|
||||||
|
b"COPY public.snippets (body) FROM stdin;\n"
|
||||||
|
b"COMMENT ON EXTENSION looks like sql but is data\n"
|
||||||
|
b"ALTER DEFAULT PRIVILEGES stored as text\n"
|
||||||
|
b"\\.\n"
|
||||||
|
b"ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON TABLES FROM y;\n"
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
_filter(raw),
|
||||||
|
b"COPY public.snippets (body) FROM stdin;\n"
|
||||||
|
b"COMMENT ON EXTENSION looks like sql but is data\n"
|
||||||
|
b"ALTER DEFAULT PRIVILEGES stored as text\n"
|
||||||
|
b"\\.\n",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_consecutive_copy_blocks_keep_state(self) -> None:
|
||||||
|
raw = (
|
||||||
|
b"COPY public.a (v) FROM stdin;\n"
|
||||||
|
b"row-a\n"
|
||||||
|
b"\\.\n"
|
||||||
|
b"COMMENT ON EXTENSION dropme IS 'x';\n"
|
||||||
|
b"COPY public.b (v) FROM stdin;\n"
|
||||||
|
b"COMMENT ON EXTENSION kept-as-data\n"
|
||||||
|
b"\\.\n"
|
||||||
|
)
|
||||||
|
out = _filter(raw)
|
||||||
|
self.assertNotIn(b"dropme", out)
|
||||||
|
self.assertIn(b"COMMENT ON EXTENSION kept-as-data\n", out)
|
||||||
|
|
||||||
|
def test_everything_else_passes_through_verbatim(self) -> None:
|
||||||
|
raw = (
|
||||||
|
b"SET statement_timeout = 0;\n"
|
||||||
|
b"CREATE EXTENSION IF NOT EXISTS pg_trgm;\n"
|
||||||
|
b"GRANT ALL ON SCHEMA public TO app;\n"
|
||||||
|
)
|
||||||
|
self.assertEqual(_filter(raw), raw)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
0
tests/unit/seed/__init__.py
Normal file
0
tests/unit/seed/__init__.py
Normal file
@@ -1,4 +1,3 @@
|
|||||||
# tests/unit/src/baudolo/seed/test_main.py
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import unittest
|
import unittest
|
||||||
@@ -33,6 +32,30 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
seed_main._validate_database_value("bad name", instance="x")
|
seed_main._validate_database_value("bad name", instance="x")
|
||||||
|
|
||||||
|
def _mock_df_mask_any(self, *, any_value: bool) -> MagicMock:
|
||||||
|
"""
|
||||||
|
Build a DataFrame-like mock such that:
|
||||||
|
mask = (df["instance"] == instance) & (df["database"] == database)
|
||||||
|
mask.any() returns any_value
|
||||||
|
"""
|
||||||
|
df = MagicMock(spec=pd.DataFrame)
|
||||||
|
|
||||||
|
left = MagicMock()
|
||||||
|
right = MagicMock()
|
||||||
|
|
||||||
|
mask = MagicMock()
|
||||||
|
mask.any.return_value = any_value
|
||||||
|
|
||||||
|
# (left & right) => mask
|
||||||
|
left.__and__.return_value = mask
|
||||||
|
|
||||||
|
# df["instance"] / df["database"] => return objects whose == produces left/right
|
||||||
|
col = MagicMock()
|
||||||
|
col.__eq__.side_effect = [left, right]
|
||||||
|
df.__getitem__.return_value = col
|
||||||
|
|
||||||
|
return df
|
||||||
|
|
||||||
@patch("baudolo.seed.__main__.os.path.exists", return_value=False)
|
@patch("baudolo.seed.__main__.os.path.exists", return_value=False)
|
||||||
@patch("baudolo.seed.__main__.pd.read_csv")
|
@patch("baudolo.seed.__main__.pd.read_csv")
|
||||||
@patch("baudolo.seed.__main__._empty_df")
|
@patch("baudolo.seed.__main__._empty_df")
|
||||||
@@ -44,11 +67,7 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
read_csv: MagicMock,
|
read_csv: MagicMock,
|
||||||
exists: MagicMock,
|
exists: MagicMock,
|
||||||
) -> None:
|
) -> None:
|
||||||
df_existing = MagicMock(spec=pd.DataFrame)
|
df_existing = self._mock_df_mask_any(any_value=False)
|
||||||
series_mask = MagicMock()
|
|
||||||
series_mask.any.return_value = False
|
|
||||||
|
|
||||||
df_existing.__getitem__.return_value = series_mask # for df["instance"] etc.
|
|
||||||
empty_df.return_value = df_existing
|
empty_df.return_value = df_existing
|
||||||
|
|
||||||
df_out = MagicMock(spec=pd.DataFrame)
|
df_out = MagicMock(spec=pd.DataFrame)
|
||||||
@@ -82,16 +101,7 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
read_csv: MagicMock,
|
read_csv: MagicMock,
|
||||||
exists: MagicMock,
|
exists: MagicMock,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
df_existing = self._mock_df_mask_any(any_value=False)
|
||||||
Key regression test:
|
|
||||||
If file exists but is empty => warn, create header columns, then proceed.
|
|
||||||
"""
|
|
||||||
df_existing = MagicMock(spec=pd.DataFrame)
|
|
||||||
series_mask = MagicMock()
|
|
||||||
series_mask.any.return_value = False
|
|
||||||
|
|
||||||
# emulate df["instance"] and df["database"] usage
|
|
||||||
df_existing.__getitem__.return_value = series_mask
|
|
||||||
empty_df.return_value = df_existing
|
empty_df.return_value = df_existing
|
||||||
|
|
||||||
df_out = MagicMock(spec=pd.DataFrame)
|
df_out = MagicMock(spec=pd.DataFrame)
|
||||||
@@ -108,15 +118,23 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
exists.assert_called_once_with("/tmp/databases.csv")
|
exists.assert_called_once_with("/tmp/databases.csv")
|
||||||
read_csv.assert_called_once()
|
read_csv.assert_called_once()
|
||||||
empty_df.assert_called_once()
|
empty_df.assert_called_once()
|
||||||
|
|
||||||
# warning was printed to stderr
|
|
||||||
self.assertTrue(print_.called)
|
|
||||||
args, kwargs = print_.call_args
|
|
||||||
self.assertIn("WARNING: databases.csv exists but is empty", args[0])
|
|
||||||
self.assertIn("file", kwargs)
|
|
||||||
self.assertEqual(kwargs["file"], seed_main.sys.stderr)
|
|
||||||
|
|
||||||
concat.assert_called_once()
|
concat.assert_called_once()
|
||||||
|
|
||||||
|
# Assert: at least one print call contains the WARNING and prints to stderr
|
||||||
|
warning_calls = []
|
||||||
|
for call in print_.call_args_list:
|
||||||
|
args, kwargs = call
|
||||||
|
if args and "WARNING: databases.csv exists but is empty" in str(args[0]):
|
||||||
|
warning_calls.append((args, kwargs))
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
warning_calls,
|
||||||
|
"Expected a WARNING print when databases.csv is empty, but none was found.",
|
||||||
|
)
|
||||||
|
# Ensure the warning goes to stderr
|
||||||
|
_, warn_kwargs = warning_calls[0]
|
||||||
|
self.assertEqual(warn_kwargs.get("file"), seed_main.sys.stderr)
|
||||||
|
|
||||||
df_out.to_csv.assert_called_once_with(
|
df_out.to_csv.assert_called_once_with(
|
||||||
"/tmp/databases.csv", sep=";", index=False
|
"/tmp/databases.csv", sep=";", index=False
|
||||||
)
|
)
|
||||||
@@ -128,22 +146,7 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
read_csv: MagicMock,
|
read_csv: MagicMock,
|
||||||
exists: MagicMock,
|
exists: MagicMock,
|
||||||
) -> None:
|
) -> None:
|
||||||
df = MagicMock(spec=pd.DataFrame)
|
df = self._mock_df_mask_any(any_value=True)
|
||||||
|
|
||||||
# mask.any() => True triggers update branch
|
|
||||||
mask = MagicMock()
|
|
||||||
mask.any.return_value = True
|
|
||||||
|
|
||||||
# df["instance"] etc => return something that supports comparisons;
|
|
||||||
# simplest: just return an object that makes mask flow work.
|
|
||||||
df.__getitem__.return_value = MagicMock()
|
|
||||||
# Force the computed mask to be our mask
|
|
||||||
# by making (df["instance"] == instance) & (df["database"] == database) return `mask`
|
|
||||||
left = MagicMock()
|
|
||||||
right = MagicMock()
|
|
||||||
left.__and__.return_value = mask
|
|
||||||
df.__getitem__.return_value.__eq__.side_effect = [left, right] # two == calls
|
|
||||||
|
|
||||||
read_csv.return_value = df
|
read_csv.return_value = df
|
||||||
|
|
||||||
seed_main.check_and_add_entry(
|
seed_main.check_and_add_entry(
|
||||||
@@ -154,9 +157,6 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
password="pass",
|
password="pass",
|
||||||
)
|
)
|
||||||
|
|
||||||
# update branch: df.loc[mask, ["username","password"]] = ...
|
|
||||||
# we can't easily assert the assignment, but we can assert .loc was accessed
|
|
||||||
self.assertTrue(hasattr(df, "loc"))
|
|
||||||
df.to_csv.assert_called_once_with("/tmp/databases.csv", sep=";", index=False)
|
df.to_csv.assert_called_once_with("/tmp/databases.csv", sep=";", index=False)
|
||||||
|
|
||||||
@patch("baudolo.seed.__main__.check_and_add_entry")
|
@patch("baudolo.seed.__main__.check_and_add_entry")
|
||||||
@@ -205,7 +205,6 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
|
|
||||||
seed_main.main()
|
seed_main.main()
|
||||||
|
|
||||||
# prints error to stderr and exits with 1
|
|
||||||
self.assertTrue(print_.called)
|
self.assertTrue(print_.called)
|
||||||
_, kwargs = print_.call_args
|
_, kwargs = print_.call_args
|
||||||
self.assertEqual(kwargs.get("file"), seed_main.sys.stderr)
|
self.assertEqual(kwargs.get("file"), seed_main.sys.stderr)
|
||||||
@@ -213,4 +212,4 @@ class TestSeedMain(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main(verbosity=2)
|
||||||
@@ -4,10 +4,11 @@ from unittest.mock import patch
|
|||||||
from baudolo.backup.app import requires_stop
|
from baudolo.backup.app import requires_stop
|
||||||
|
|
||||||
|
|
||||||
|
@patch("baudolo.backup.app.is_swarm_task", return_value=False)
|
||||||
class TestRequiresStop(unittest.TestCase):
|
class TestRequiresStop(unittest.TestCase):
|
||||||
@patch("baudolo.backup.app.get_image_info")
|
@patch("baudolo.backup.app.get_image_info")
|
||||||
def test_requires_stop_false_when_all_images_are_whitelisted(
|
def test_requires_stop_false_when_all_images_are_whitelisted(
|
||||||
self, mock_get_image_info
|
self, mock_get_image_info, _mock_is_swarm_task
|
||||||
):
|
):
|
||||||
# All containers use images containing allowed substrings
|
# All containers use images containing allowed substrings
|
||||||
mock_get_image_info.side_effect = [
|
mock_get_image_info.side_effect = [
|
||||||
@@ -20,7 +21,7 @@ class TestRequiresStop(unittest.TestCase):
|
|||||||
|
|
||||||
@patch("baudolo.backup.app.get_image_info")
|
@patch("baudolo.backup.app.get_image_info")
|
||||||
def test_requires_stop_true_when_any_image_is_not_whitelisted(
|
def test_requires_stop_true_when_any_image_is_not_whitelisted(
|
||||||
self, mock_get_image_info
|
self, mock_get_image_info, _mock_is_swarm_task
|
||||||
):
|
):
|
||||||
mock_get_image_info.side_effect = [
|
mock_get_image_info.side_effect = [
|
||||||
"repo/mastodon:v4",
|
"repo/mastodon:v4",
|
||||||
@@ -31,10 +32,23 @@ class TestRequiresStop(unittest.TestCase):
|
|||||||
self.assertTrue(requires_stop(containers, whitelist))
|
self.assertTrue(requires_stop(containers, whitelist))
|
||||||
|
|
||||||
@patch("baudolo.backup.app.get_image_info")
|
@patch("baudolo.backup.app.get_image_info")
|
||||||
def test_requires_stop_true_when_whitelist_empty(self, mock_get_image_info):
|
def test_requires_stop_true_when_whitelist_empty(
|
||||||
|
self, mock_get_image_info, _mock_is_swarm_task
|
||||||
|
):
|
||||||
mock_get_image_info.return_value = "repo/anything:latest"
|
mock_get_image_info.return_value = "repo/anything:latest"
|
||||||
self.assertTrue(requires_stop(["c1"], []))
|
self.assertTrue(requires_stop(["c1"], []))
|
||||||
|
|
||||||
|
|
||||||
|
class TestRequiresStopSwarm(unittest.TestCase):
|
||||||
|
@patch("baudolo.backup.app.get_image_info")
|
||||||
|
@patch("baudolo.backup.app.is_swarm_task", return_value=True)
|
||||||
|
def test_swarm_tasks_never_require_stop(
|
||||||
|
self, _mock_is_swarm_task, mock_get_image_info
|
||||||
|
):
|
||||||
|
mock_get_image_info.return_value = "repo/not-whitelisted:latest"
|
||||||
|
self.assertFalse(requires_stop(["c1"], []))
|
||||||
|
mock_get_image_info.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user