diff --git a/auto_backup/README.rst b/auto_backup/README.rst
index 1b5485c70c3..e79d8b98c35 100644
--- a/auto_backup/README.rst
+++ b/auto_backup/README.rst
@@ -113,7 +113,6 @@ Known issues / Roadmap
changing settings, you need to run the backup from outside of the main
Odoo instance. How to do this is outlined in `this blog
post `__.
-- Backups won't work if list_db=False is configured in the instance.
Bug Tracker
===========
diff --git a/auto_backup/models/db_backup.py b/auto_backup/models/db_backup.py
index 042038e6183..93cc2419d19 100644
--- a/auto_backup/models/db_backup.py
+++ b/auto_backup/models/db_backup.py
@@ -3,10 +3,14 @@
# Copyright 2016 Grupo ESOC Ingenieria de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
+import json
import logging
import os
import shutil
+import subprocess
+import tempfile
import traceback
+import uuid
from contextlib import contextmanager
from datetime import datetime, timedelta
from glob import iglob
@@ -16,6 +20,7 @@
from odoo import _, api, exceptions, fields, models, tools
from odoo.exceptions import UserError
from odoo.service import db
+from odoo.tools.misc import exec_pg_environ, find_pg_tool
_logger = logging.getLogger(__name__)
@@ -151,17 +156,24 @@ def action_backup(self):
except OSError as exc:
_logger.exception(f"Action backup - OSError: {exc}")
- with open(os.path.join(rec.folder, filename), "wb") as destiny:
- # Copy the cached backup
- if backup:
- with open(backup) as cached:
- shutil.copyfileobj(cached, destiny)
- # Generate new backup
- else:
- db.dump_db(
- self.env.cr.dbname, destiny, backup_format=rec.backup_format
- )
- backup = backup or destiny.name
+ # Write to a partial file of our own, renamed once complete,
+ # so that a failed dump leaves no empty or truncated backup
+ destination = os.path.join(rec.folder, filename)
+ partial = f"{destination}.{uuid.uuid4().hex}.part"
+ try:
+ with open(partial, "xb") as destiny:
+ # Copy the cached backup
+ if backup:
+ with open(backup) as cached:
+ shutil.copyfileobj(cached, destiny)
+ # Generate new backup
+ else:
+ self._dump_db(destiny, rec.backup_format)
+ os.replace(partial, destination)
+ finally:
+ if os.path.exists(partial):
+ os.unlink(partial)
+ backup = backup or destination
successful |= rec
# Ensure a local backup exists if we are going to write it remotely
@@ -170,11 +182,9 @@ def action_backup(self):
for rec in sftp:
filename = self.filename(datetime.now(), ext=rec.backup_format)
with rec.backup_log():
- cached = db.dump_db(
- self.env.cr.dbname, None, backup_format=rec.backup_format
- )
-
- with cached:
+ with tempfile.TemporaryFile() as cached:
+ self._dump_db(cached, rec.backup_format)
+ cached.seek(0)
with rec.sftp_connection() as remote:
try:
remote.makedirs(rec.folder)
@@ -196,6 +206,53 @@ def action_backup_all(self):
"""Run all scheduled backups."""
return self.search([]).action_backup()
+ def _dump_db(self, stream, backup_format):
+ """Dump the current database into ``stream``, raising if it fails.
+
+ ``odoo.service.db.dump_db`` is guarded by
+ ``check_db_management_enabled``, which refuses to run when
+ ``list_db = False``. Switching ``list_db`` back on for the dump would
+ reopen the database manager routes, ``/web/database/list`` included,
+ to every request served meanwhile by the same process. The dump is
+ therefore built here with the same core tools and the same layout as
+ ``dump_db``, taking the manifest from the undecorated
+ ``dump_db_manifest``; ``list_db`` is never touched.
+ """
+ db_name = self.env.cr.dbname
+ pg_dump = [find_pg_tool("pg_dump"), "--no-owner"]
+ env = exec_pg_environ()
+ if backup_format == "zip":
+ with tempfile.TemporaryDirectory() as dump_dir:
+ filestore = tools.config.filestore(db_name)
+ if os.path.exists(filestore):
+ shutil.copytree(filestore, os.path.join(dump_dir, "filestore"))
+ with open(os.path.join(dump_dir, "manifest.json"), "w") as fh:
+ manifest = db.dump_db_manifest.__wrapped__(self.env.cr)
+ json.dump(manifest, fh, indent=4)
+ dump_file = "--file=" + os.path.join(dump_dir, "dump.sql")
+ subprocess.run(
+ pg_dump + [dump_file, db_name],
+ env=env,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.STDOUT,
+ check=True,
+ )
+ tools.osutil.zip_dir(
+ dump_dir,
+ stream,
+ include_dir=False,
+ fnct_sort=lambda file_name: file_name != "dump.sql",
+ )
+ else:
+ stream.flush()
+ subprocess.run(
+ pg_dump + ["--format=c", db_name],
+ env=env,
+ stdin=subprocess.DEVNULL,
+ stdout=stream,
+ check=True,
+ )
+
@contextmanager
def backup_log(self):
"""Log a backup result."""
diff --git a/auto_backup/readme/ROADMAP.md b/auto_backup/readme/ROADMAP.md
index 93e7ad75415..79625b7c1e9 100644
--- a/auto_backup/readme/ROADMAP.md
+++ b/auto_backup/readme/ROADMAP.md
@@ -3,4 +3,3 @@
changing settings, you need to run the backup from outside of the main
Odoo instance. How to do this is outlined in [this blog
post](https://blog.laslabs.com/2016/10/running-python-scripts-within-odoos-environment/).
-- Backups won't work if list_db=False is configured in the instance.
diff --git a/auto_backup/static/description/index.html b/auto_backup/static/description/index.html
index 997ce0aa76c..7f102ee6389 100644
--- a/auto_backup/static/description/index.html
+++ b/auto_backup/static/description/index.html
@@ -469,7 +469,6 @@
changing settings, you need to run the backup from outside of the main
Odoo instance. How to do this is outlined in this blog
post.
-Backups won’t work if list_db=False is configured in the instance.
diff --git a/auto_backup/tests/test_db_backup.py b/auto_backup/tests/test_db_backup.py
index 6ab7236ebfa..0e44f68e0fb 100644
--- a/auto_backup/tests/test_db_backup.py
+++ b/auto_backup/tests/test_db_backup.py
@@ -6,6 +6,10 @@
import logging
import os
+import shutil
+import subprocess
+import tempfile
+import zipfile
from contextlib import contextmanager
from datetime import datetime, timedelta
from unittest.mock import PropertyMock, patch
@@ -40,12 +44,14 @@ def mock_assets(self):
with patch(f"{model}.db") as db:
with patch(f"{model}.os") as os:
with patch(f"{model}.shutil") as shutil:
- os.path.join.return_value = self.path_join_val
- yield {
- "db": db,
- "os": os,
- "shutil": shutil,
- }
+ with patch(f"{class_name}._dump_db") as dump_db:
+ os.path.join.return_value = self.path_join_val
+ yield {
+ "db": db,
+ "dump_db": dump_db,
+ "os": os,
+ "shutil": shutil,
+ }
@contextmanager
def patch_filtered_sftp(self, record):
@@ -119,6 +125,61 @@ def test_action_backup_local(self):
generated_backup = [f for f in os.listdir(rec_id.folder) if f >= filename]
self.assertEqual(1, len(generated_backup))
+ def new_local_record_in_temp_folder(self, backup_format="zip"):
+ """Local backup record writing to its own, empty folder"""
+ rec_id = self.new_record("local")
+ folder = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, folder, ignore_errors=True)
+ rec_id.write({"folder": folder, "backup_format": backup_format})
+ return rec_id
+
+ def backup_with_list_db_disabled(self, rec_id):
+ """Run a backup with list_db disabled; return list_db as pg_dump saw it"""
+ list_db_seen = []
+ run = subprocess.run
+
+ def spy_run(*args, **kwargs):
+ list_db_seen.append(tools.config["list_db"])
+ return run(*args, **kwargs)
+
+ with patch.dict(tools.config.options, {"list_db": False}):
+ with patch("subprocess.run", side_effect=spy_run):
+ rec_id.action_backup()
+ return list_db_seen
+
+ def test_action_backup_local_list_db_disabled_zip(self):
+ """It should backup locally in zip, list_db staying disabled"""
+ rec_id = self.new_local_record_in_temp_folder("zip")
+ self.assertEqual([False], self.backup_with_list_db_disabled(rec_id))
+ generated_backup = os.listdir(rec_id.folder)
+ self.assertEqual(1, len(generated_backup))
+ backup_path = os.path.join(rec_id.folder, generated_backup[0])
+ self.assertGreater(os.path.getsize(backup_path), 0)
+ with zipfile.ZipFile(backup_path) as backup:
+ self.assertIn("dump.sql", backup.namelist())
+ self.assertIn("manifest.json", backup.namelist())
+
+ def test_action_backup_local_list_db_disabled_dump(self):
+ """It should backup locally in dump, list_db staying disabled"""
+ rec_id = self.new_local_record_in_temp_folder("dump")
+ self.assertEqual([False], self.backup_with_list_db_disabled(rec_id))
+ generated_backup = os.listdir(rec_id.folder)
+ self.assertEqual(1, len(generated_backup))
+ backup_path = os.path.join(rec_id.folder, generated_backup[0])
+ with open(backup_path, "rb") as backup:
+ self.assertEqual(b"PGDMP", backup.read(5))
+
+ def test_action_backup_local_failed_dump(self):
+ """A failed dump should leave no backup file behind"""
+ rec_id = self.new_local_record_in_temp_folder("zip")
+ failure = subprocess.CalledProcessError(1, "pg_dump")
+ with self.assertLogs(model, level="ERROR") as logs:
+ with patch("subprocess.run", side_effect=failure):
+ rec_id.action_backup()
+ self.assertIn("Database backup failed", logs.output[0])
+ self.assertEqual([], os.listdir(rec_id.folder))
+ self.assertIn("Database backup failed.", rec_id.message_ids[0].body)
+
def test_action_backup_local_cleanup(self):
"""Backup local database and cleanup old databases"""
rec_id = self.new_record("local")