Restore DirectAdmin websites into empty web roots
This commit is contained in:
1 parent
2b4895df4f
commit
581566b80b
6 files changed
+288
-3
No files matched your search
@@ -420,6 +420,27 @@ command writes regular files with owner-only permissions and reports
|
|||||||
the file count, size and number of skipped links or special entries.
|
the file count, size and number of skipped links or special entries.
|
||||||
The staging directory is separate from the live web root.
|
The staging directory is separate from the live web root.
|
||||||
|
|
||||||
|
### Restore a DirectAdmin website on a web node
|
||||||
|
|
||||||
|
Apply the account's web deployment manifest on the web node, then run
|
||||||
|
the following command with the same manifest and the original backup.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/coulobre/bin/coulobre-web-node restore-directadmin coulobre-web-plan-1.json user.admin.customer.tar.zst
|
||||||
|
```
|
||||||
|
|
||||||
|
The command restores the manifest's domain into an empty document root.
|
||||||
|
It reads and validates the entire backup before placing the files. Use
|
||||||
|
`--source-root private_html` to restore that source directory instead.
|
||||||
|
The report includes the file count, size and number of skipped entries.
|
||||||
|
|
||||||
|
The hosting account owns the restored files. Apache can read public
|
||||||
|
files through the `www-data` group. Hidden entries and entries with
|
||||||
|
private source permissions stay private to the hosting account. The
|
||||||
|
managed Apache configuration controls the restored site. Any restored
|
||||||
|
`.htaccess` files are available for review. See the
|
||||||
|
[Apache AllowOverride reference](https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride).
|
||||||
|
|
||||||
## Request an Apache configuration preview
|
## Request an Apache configuration preview
|
||||||
|
|
||||||
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
|
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ def stage_website(backup, domain, destination, *, source_root="public_html"):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def copy_website(backup, domain, source_root, destination):
|
def copy_website(backup, domain, source_root, destination, *, on_copy=None):
|
||||||
account = BackupInventory()
|
account = BackupInventory()
|
||||||
matches = {}
|
matches = {}
|
||||||
source_name = None
|
source_name = None
|
||||||
@@ -78,6 +78,9 @@ def copy_website(backup, domain, source_root, destination):
|
|||||||
total_bytes += member.size
|
total_bytes += member.size
|
||||||
else:
|
else:
|
||||||
skipped += 1
|
skipped += 1
|
||||||
|
continue
|
||||||
|
if on_copy is not None:
|
||||||
|
on_copy(member, target)
|
||||||
|
|
||||||
if account.username is None:
|
if account.username is None:
|
||||||
raise ValueError("Expected a DirectAdmin account backup with backup/user.conf.")
|
raise ValueError("Expected a DirectAdmin account backup with backup/user.conf.")
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import gzip
|
||||||
|
import json
|
||||||
|
import stat
|
||||||
|
import tarfile
|
||||||
|
from contextlib import redirect_stdout
|
||||||
|
from io import BytesIO, StringIO
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from coulobre.web_node import WebSite, main
|
||||||
|
from coulobre.web_node_restore import copy_website, restore_website
|
||||||
|
|
||||||
|
|
||||||
|
class DirectAdminWebRestoreTests(SimpleTestCase):
|
||||||
|
def setUp(self):
|
||||||
|
root = Path(self.enterContext(TemporaryDirectory()))
|
||||||
|
self.site = WebSite(42, "example.net")
|
||||||
|
self.backup = root / "directadmin.tar.gz"
|
||||||
|
self.state = root / "state"
|
||||||
|
self.state.mkdir()
|
||||||
|
self.marker = self.state / "42.json"
|
||||||
|
self.marker.write_text(json.dumps(self.site.manifest()), encoding="utf-8")
|
||||||
|
(self.state / "apply.lock").touch()
|
||||||
|
self.account = root / "web/42"
|
||||||
|
self.public = self.account / "public"
|
||||||
|
self.public.mkdir(parents=True)
|
||||||
|
self.enterContext(patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state))
|
||||||
|
self.enterContext(
|
||||||
|
patch("coulobre.web_node_apply.WEB_ROOT", self.account.parent)
|
||||||
|
)
|
||||||
|
self.enterContext(patch("coulobre.web_node_restore.os.geteuid", return_value=0))
|
||||||
|
self.enterContext(patch("coulobre.web_node_apply.require_root_directory"))
|
||||||
|
self.enterContext(
|
||||||
|
patch("coulobre.web_node_apply.read_root_file", side_effect=Path.read_text)
|
||||||
|
)
|
||||||
|
self.installation = self.enterContext(
|
||||||
|
patch("coulobre.web_node_apply.check_installation", return_value=(1001, 33))
|
||||||
|
)
|
||||||
|
self.owner = self.enterContext(patch("coulobre.web_node_restore.os.chown"))
|
||||||
|
|
||||||
|
entries = [
|
||||||
|
("backup/user.conf", b"username=client\ndomain=example.net\n", 0o600),
|
||||||
|
("domains/example.net/public_html/index.php", b"demo", 0o755),
|
||||||
|
("domains/example.net/public_html/.env", b"private", 0o644),
|
||||||
|
("domains/example.net/public_html/app.ini", b"private", 0o600),
|
||||||
|
("domains/example.net/public_html/assets/site.css", b"assets", 0o644),
|
||||||
|
("domains/example.net/public_html/.secret/hidden.txt", b"private", 0o644),
|
||||||
|
("domains/example.net/public_html/logs", None, 0o700),
|
||||||
|
("domains/example.net/public_html/logs/app.log", b"private", 0o644),
|
||||||
|
("domains/other.example/public_html/index.php", b"other", 0o644),
|
||||||
|
]
|
||||||
|
tar = BytesIO()
|
||||||
|
with tarfile.open(fileobj=tar, mode="w") as archive:
|
||||||
|
for name, payload, mode in entries:
|
||||||
|
member = tarfile.TarInfo(name)
|
||||||
|
member.mode = mode
|
||||||
|
if payload is None:
|
||||||
|
member.type = tarfile.DIRTYPE
|
||||||
|
archive.addfile(member)
|
||||||
|
else:
|
||||||
|
member.size = len(payload)
|
||||||
|
archive.addfile(member, BytesIO(payload))
|
||||||
|
self.backup.write_bytes(gzip.compress(tar.getvalue()))
|
||||||
|
|
||||||
|
def restore(self):
|
||||||
|
return restore_website(self.site, self.backup, "public_html")
|
||||||
|
|
||||||
|
def test_restore_cli_publishes_files_with_hosting_permissions(self):
|
||||||
|
manifest = self.state.parent / "site.json"
|
||||||
|
manifest.write_text(json.dumps(self.site.manifest()), encoding="utf-8")
|
||||||
|
output = self.enterContext(redirect_stdout(StringIO()))
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
main(["restore-directadmin", str(manifest), str(self.backup)]),
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
|
||||||
|
report = json.loads(output.getvalue())
|
||||||
|
self.assertEqual(report["kind"], "directadmin_website_restore")
|
||||||
|
self.assertEqual(report["files"], 6)
|
||||||
|
self.assertEqual(report["document_root"], str(self.public))
|
||||||
|
self.assertEqual(report["domain"], self.site.domain)
|
||||||
|
self.assertEqual((self.public / "index.php").read_bytes(), b"demo")
|
||||||
|
self.assertEqual(list(self.account.iterdir()), [self.public])
|
||||||
|
modes = {
|
||||||
|
".": 0o750,
|
||||||
|
"index.php": 0o640,
|
||||||
|
".env": 0o600,
|
||||||
|
"app.ini": 0o600,
|
||||||
|
"assets": 0o750,
|
||||||
|
"assets/site.css": 0o640,
|
||||||
|
".secret": 0o700,
|
||||||
|
"logs": 0o700,
|
||||||
|
}
|
||||||
|
for entry, mode in modes.items():
|
||||||
|
with self.subTest(entry=entry):
|
||||||
|
self.assertEqual(
|
||||||
|
stat.S_IMODE((self.public / entry).stat().st_mode), mode
|
||||||
|
)
|
||||||
|
self.assertEqual(self.owner.call_count, 10)
|
||||||
|
for call in self.owner.call_args_list:
|
||||||
|
self.assertEqual(call.args[1:], (1001, 33))
|
||||||
|
|
||||||
|
def test_non_empty_document_root_refuses_restore(self):
|
||||||
|
existing = self.public / "index.php"
|
||||||
|
existing.write_bytes(b"existing")
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(ValueError, "empty document root"):
|
||||||
|
self.restore()
|
||||||
|
|
||||||
|
self.assertEqual(list(self.public.iterdir()), [existing])
|
||||||
|
self.assertEqual(existing.read_bytes(), b"existing")
|
||||||
|
|
||||||
|
def test_atomic_publish_preserves_a_file_created_during_restore(self):
|
||||||
|
existing = self.public / "new.txt"
|
||||||
|
|
||||||
|
def write_to_live_root(*args, **kwargs):
|
||||||
|
summary = copy_website(*args, **kwargs)
|
||||||
|
existing.write_bytes(b"new data")
|
||||||
|
return summary
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"coulobre.web_node_restore.copy_website", side_effect=write_to_live_root
|
||||||
|
),
|
||||||
|
self.assertRaisesRegex(ValueError, "empty document root"),
|
||||||
|
):
|
||||||
|
self.restore()
|
||||||
|
|
||||||
|
self.assertEqual(list(self.public.iterdir()), [existing])
|
||||||
|
self.assertEqual(existing.read_bytes(), b"new data")
|
||||||
|
self.assertEqual(list(self.account.iterdir()), [self.public])
|
||||||
|
|
||||||
|
def test_incomplete_backup_leaves_live_document_root_untouched(self):
|
||||||
|
inode = self.public.stat().st_ino
|
||||||
|
self.backup.write_bytes(self.backup.read_bytes()[:-4])
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(
|
||||||
|
ValueError, "not a readable or complete tar archive"
|
||||||
|
):
|
||||||
|
self.restore()
|
||||||
|
|
||||||
|
self.assertEqual(self.public.stat().st_ino, inode)
|
||||||
|
self.assertEqual(list(self.public.iterdir()), [])
|
||||||
|
self.assertEqual(list(self.account.iterdir()), [self.public])
|
||||||
|
|
||||||
|
def test_restore_checks_manifest_against_registered_site_first(self):
|
||||||
|
self.marker.write_text(
|
||||||
|
json.dumps(WebSite(42, "different.example").manifest()), encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(ValueError, "different manifest"):
|
||||||
|
self.restore()
|
||||||
|
|
||||||
|
self.installation.assert_not_called()
|
||||||
|
self.assertEqual(list(self.public.iterdir()), [])
|
||||||
@@ -6,6 +6,7 @@ from importlib.resources import files
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from string import Template
|
from string import Template
|
||||||
|
|
||||||
|
from .directadmin import DOCUMENT_ROOTS
|
||||||
from .domain_names import canonical_domain
|
from .domain_names import canonical_domain
|
||||||
|
|
||||||
MANIFEST_VERSION = 1
|
MANIFEST_VERSION = 1
|
||||||
@@ -79,6 +80,13 @@ def main(argv=None):
|
|||||||
"status", help="Check a site's local configuration and services."
|
"status", help="Check a site's local configuration and services."
|
||||||
)
|
)
|
||||||
status.add_argument("manifest", type=Path)
|
status.add_argument("manifest", type=Path)
|
||||||
|
restore = commands.add_parser(
|
||||||
|
"restore-directadmin",
|
||||||
|
help="Restore a DirectAdmin website into an empty web root.",
|
||||||
|
)
|
||||||
|
restore.add_argument("manifest", type=Path)
|
||||||
|
restore.add_argument("backup", type=Path)
|
||||||
|
restore.add_argument("--source-root", choices=DOCUMENT_ROOTS, default="public_html")
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -95,6 +103,14 @@ def main(argv=None):
|
|||||||
report = site_status(site)
|
report = site_status(site)
|
||||||
print(json.dumps(report, indent=2))
|
print(json.dumps(report, indent=2))
|
||||||
return 0 if report["state"] == "configured" else 2
|
return 0 if report["state"] == "configured" else 2
|
||||||
|
elif args.command == "restore-directadmin":
|
||||||
|
from .web_node_restore import restore_website
|
||||||
|
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
restore_website(site, args.backup, args.source_root), indent=2
|
||||||
|
)
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
sys.stdout.write(site.render(args.configuration))
|
sys.stdout.write(site.render(args.configuration))
|
||||||
except (OSError, ValueError) as error:
|
except (OSError, ValueError) as error:
|
||||||
|
|||||||
@@ -85,14 +85,25 @@ def site_status(site):
|
|||||||
with (STATE_DIRECTORY / "apply.lock").open("r") as lock:
|
with (STATE_DIRECTORY / "apply.lock").open("r") as lock:
|
||||||
fcntl.flock(lock, fcntl.LOCK_SH)
|
fcntl.flock(lock, fcntl.LOCK_SH)
|
||||||
try:
|
try:
|
||||||
if json.loads(read_root_file(marker)) != site.manifest():
|
check_reservation(site)
|
||||||
raise ValueError("The account is reserved with a different manifest.")
|
|
||||||
check_installation(site, SitePaths.for_site(site))
|
check_installation(site, SitePaths.for_site(site))
|
||||||
except (OSError, ValueError) as error:
|
except (OSError, ValueError) as error:
|
||||||
return {**report, "state": "needs_attention", "problem": str(error)}
|
return {**report, "state": "needs_attention", "problem": str(error)}
|
||||||
return {**report, "state": "configured"}
|
return {**report, "state": "configured"}
|
||||||
|
|
||||||
|
|
||||||
|
def check_reservation(site):
|
||||||
|
marker = STATE_DIRECTORY / f"{site.account_id}.json"
|
||||||
|
try:
|
||||||
|
saved = json.loads(read_root_file(marker))
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise ValueError(
|
||||||
|
"Apply the site manifest before restoring website files."
|
||||||
|
) from None
|
||||||
|
if saved != site.manifest():
|
||||||
|
raise ValueError("The account is reserved with a different manifest.")
|
||||||
|
|
||||||
|
|
||||||
def check_installation(site, paths):
|
def check_installation(site, paths):
|
||||||
for directory in (
|
for directory in (
|
||||||
paths.account,
|
paths.account,
|
||||||
@@ -111,6 +122,7 @@ def check_installation(site, paths):
|
|||||||
check_services()
|
check_services()
|
||||||
if not socket_exists(paths.socket):
|
if not socket_exists(paths.socket):
|
||||||
raise ValueError(f"PHP-FPM is missing the site socket at {paths.socket}.")
|
raise ValueError(f"PHP-FPM is missing the site socket at {paths.socket}.")
|
||||||
|
return uid, gid
|
||||||
|
|
||||||
|
|
||||||
def check_services():
|
def check_services():
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import errno
|
||||||
|
import fcntl
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
|
||||||
|
from . import web_node_apply
|
||||||
|
from .directadmin_website import copy_website
|
||||||
|
|
||||||
|
|
||||||
|
def restore_website(site, backup, source_root):
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
raise ValueError("Run restore-directadmin as root on the web node.")
|
||||||
|
|
||||||
|
web_node_apply.require_root_directory(web_node_apply.STATE_DIRECTORY)
|
||||||
|
with (web_node_apply.STATE_DIRECTORY / "apply.lock").open("r") as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||||
|
web_node_apply.check_reservation(site)
|
||||||
|
paths = web_node_apply.SitePaths.for_site(site)
|
||||||
|
uid, gid = web_node_apply.check_installation(site, paths)
|
||||||
|
public = paths.account / "public"
|
||||||
|
if any(public.iterdir()):
|
||||||
|
raise ValueError("Restore requires an empty document root.")
|
||||||
|
|
||||||
|
with TemporaryDirectory(
|
||||||
|
dir=paths.account, prefix=".directadmin-restore-"
|
||||||
|
) as directory:
|
||||||
|
staged = Path(directory) / "public"
|
||||||
|
staged.mkdir(mode=0o700)
|
||||||
|
private = set()
|
||||||
|
|
||||||
|
def remember_private_entry(member, target):
|
||||||
|
access = 0o011 if member.isdir() else 0o044
|
||||||
|
if not member.mode & access:
|
||||||
|
private.add(target)
|
||||||
|
|
||||||
|
summary = copy_website(
|
||||||
|
backup, site.domain, source_root, staged, on_copy=remember_private_entry
|
||||||
|
)
|
||||||
|
prepare_web_permissions(staged, uid, gid, private)
|
||||||
|
try:
|
||||||
|
# A directory rename can replace the live root only while it is empty.
|
||||||
|
os.replace(staged, public)
|
||||||
|
except OSError as error:
|
||||||
|
if error.errno not in (errno.ENOTEMPTY, errno.EEXIST):
|
||||||
|
raise
|
||||||
|
raise ValueError("Restore requires an empty document root.") from None
|
||||||
|
|
||||||
|
return {
|
||||||
|
**site.manifest(),
|
||||||
|
"kind": "directadmin_website_restore",
|
||||||
|
"source_root": source_root,
|
||||||
|
"document_root": str(public),
|
||||||
|
**summary,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_web_permissions(root, uid, gid, private):
|
||||||
|
root_is_private = root in private
|
||||||
|
for directory, _, filenames in root.walk(top_down=False, on_error=raise_walk_error):
|
||||||
|
for filename in filenames:
|
||||||
|
path = directory / filename
|
||||||
|
restricted = root_is_private or path in private or filename.startswith(".")
|
||||||
|
path.chmod(0o600 if restricted else 0o640)
|
||||||
|
os.chown(path, uid, gid, follow_symlinks=False)
|
||||||
|
restricted = directory != root and (
|
||||||
|
root_is_private or directory in private or directory.name.startswith(".")
|
||||||
|
)
|
||||||
|
directory.chmod(0o700 if restricted else 0o750)
|
||||||
|
os.chown(directory, uid, gid, follow_symlinks=False)
|
||||||
|
|
||||||
|
|
||||||
|
def raise_walk_error(error):
|
||||||
|
raise error
|
||||||
Reference in new issue
Block a user