Merge pull request 'Add DirectAdmin website staging and restore' (#10) from feature/directadmin-website-migration into main
Reviewed-on: #10
This commit was merged in pull request #10.
This commit is contained in:
commit
4bbe265915
9 files changed
+609
-15
No files matched your search
@@ -404,6 +404,43 @@ for the original account. A domain conflict or a change to the original
|
||||
account's domain or requests can block the import. A blocked import prints
|
||||
its report and exits with code `2`.
|
||||
|
||||
### Stage DirectAdmin website files
|
||||
|
||||
Run the following command with a path for a new directory. The command
|
||||
publishes the selected site's files under `document-root` inside that
|
||||
directory after successfully reading the backup.
|
||||
|
||||
```sh
|
||||
coulobre-directadmin stage-website user.admin.customer.tar.zst example.net ./example-net-stage
|
||||
```
|
||||
|
||||
The default source is the domain's `public_html` directory. Use
|
||||
`--source-root private_html` for a separate HTTPS document root. The
|
||||
command writes regular files with owner-only permissions and reports
|
||||
the file count, size and number of skipped links or special entries.
|
||||
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
|
||||
|
||||
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
|
||||
|
||||
+42
-12
@@ -15,6 +15,7 @@ from .mail_node import MailboxSpec
|
||||
MAX_METADATA_SIZE = 8 * 1024 * 1024
|
||||
ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
|
||||
HOME_ARCHIVES = {"home.tar", "home.tar.gz", "home.tar.zst"}
|
||||
DOCUMENT_ROOTS = ("public_html", "private_html")
|
||||
|
||||
|
||||
class BackupTarInfo(tarfile.TarInfo):
|
||||
@@ -64,10 +65,7 @@ class BackupInventory:
|
||||
return inventory
|
||||
|
||||
def visit(self, archive, member):
|
||||
path = PurePosixPath(member.name)
|
||||
parts = path.parts
|
||||
if path.is_absolute() or ".." in parts:
|
||||
raise ValueError("The archive contains an unsafe member path.")
|
||||
parts = member_path(member)
|
||||
if not member.isreg():
|
||||
if not member.isdir():
|
||||
self.skipped_non_regular_entries += 1
|
||||
@@ -213,22 +211,40 @@ def check_tar_padding(archive):
|
||||
raise ValueError("The tar archive is missing its end marker.")
|
||||
|
||||
|
||||
def inspect_backup(path):
|
||||
inventory = BackupInventory()
|
||||
def member_path(member):
|
||||
path = PurePosixPath(member.name)
|
||||
if path.is_absolute() or ".." in path.parts:
|
||||
raise ValueError("The archive contains an unsafe member path.")
|
||||
return path.parts
|
||||
|
||||
|
||||
@contextmanager
|
||||
def open_backup(path):
|
||||
try:
|
||||
with (
|
||||
archive_stream(path) as stream,
|
||||
tarfile.open(fileobj=stream, mode="r|", tarinfo=BackupTarInfo) as archive,
|
||||
):
|
||||
while (member := archive.next()) is not None:
|
||||
inventory.visit(archive, member)
|
||||
# The reader only walks forward and does not need tarfile's member cache.
|
||||
archive.members.clear()
|
||||
check_tar_padding(archive)
|
||||
yield archive
|
||||
except (EOFError, tarfile.TarError, zlib.error, gzip.BadGzipFile):
|
||||
raise ValueError(
|
||||
"The backup is not a readable or complete tar archive."
|
||||
) from None
|
||||
|
||||
|
||||
def backup_members(archive):
|
||||
while (member := archive.next()) is not None:
|
||||
yield member
|
||||
# The reader only walks forward and does not need tarfile's member cache.
|
||||
archive.members.clear()
|
||||
check_tar_padding(archive)
|
||||
|
||||
|
||||
def inspect_backup(path):
|
||||
inventory = BackupInventory()
|
||||
with open_backup(path) as archive:
|
||||
for member in backup_members(archive):
|
||||
inventory.visit(archive, member)
|
||||
return inventory.report()
|
||||
|
||||
|
||||
@@ -239,9 +255,23 @@ def main(argv=None):
|
||||
"inspect", help="Inventory a DirectAdmin account backup."
|
||||
)
|
||||
inspect.add_argument("backup", type=Path)
|
||||
stage = commands.add_parser(
|
||||
"stage-website", help="Stage one DirectAdmin website in a new local directory."
|
||||
)
|
||||
stage.add_argument("backup", type=Path)
|
||||
stage.add_argument("domain")
|
||||
stage.add_argument("destination", type=Path)
|
||||
stage.add_argument("--source-root", choices=DOCUMENT_ROOTS, default="public_html")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
report = inspect_backup(args.backup)
|
||||
if args.command == "stage-website":
|
||||
from .directadmin_website import stage_website
|
||||
|
||||
report = stage_website(
|
||||
args.backup, args.domain, args.destination, source_root=args.source_root
|
||||
)
|
||||
else:
|
||||
report = inspect_backup(args.backup)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.exit(1, f"coulobre-directadmin: {error}\n")
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import os
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from shutil import copyfileobj
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from .directadmin import (
|
||||
DOCUMENT_ROOTS,
|
||||
BackupInventory,
|
||||
backup_members,
|
||||
member_path,
|
||||
open_backup,
|
||||
)
|
||||
from .domain_names import canonical_domain
|
||||
|
||||
|
||||
def stage_website(backup, domain, destination, *, source_root="public_html"):
|
||||
domain = canonical_domain(domain)
|
||||
if source_root not in DOCUMENT_ROOTS:
|
||||
raise ValueError("Choose public_html or private_html from the backup.")
|
||||
|
||||
destination.mkdir(mode=0o700)
|
||||
document_root = destination / "document-root"
|
||||
try:
|
||||
with TemporaryDirectory(dir=destination, prefix=".staging-") as directory:
|
||||
staged = Path(directory) / "document-root"
|
||||
staged.mkdir(mode=0o700)
|
||||
summary = copy_website(backup, domain, source_root, staged)
|
||||
staged.rename(document_root)
|
||||
except BaseException:
|
||||
with suppress(OSError):
|
||||
destination.rmdir()
|
||||
raise
|
||||
return {
|
||||
"version": 1,
|
||||
"kind": "directadmin_website_stage",
|
||||
"domain": domain,
|
||||
"source_root": source_root,
|
||||
"document_root": str(document_root),
|
||||
**summary,
|
||||
}
|
||||
|
||||
|
||||
def copy_website(backup, domain, source_root, destination, *, on_copy=None):
|
||||
account = BackupInventory()
|
||||
matches = {}
|
||||
source_name = None
|
||||
found_root = False
|
||||
files = total_bytes = skipped = 0
|
||||
with open_backup(backup) as archive:
|
||||
for member in backup_members(archive):
|
||||
parts = member_path(member)
|
||||
if parts == ("backup", "user.conf"):
|
||||
account.visit(archive, member)
|
||||
if len(parts) < 3 or parts[0] != "domains" or parts[2] != source_root:
|
||||
continue
|
||||
name = parts[1]
|
||||
if name not in matches:
|
||||
matches[name] = canonical_domain(name) == domain
|
||||
if not matches[name]:
|
||||
continue
|
||||
if source_name is not None and name != source_name:
|
||||
raise ValueError(
|
||||
"The backup contains multiple source directories for this domain."
|
||||
)
|
||||
source_name = name
|
||||
|
||||
target = destination.joinpath(*parts[3:])
|
||||
if member.isdir():
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
found_root = True
|
||||
elif member.isreg():
|
||||
if len(parts) == 3:
|
||||
raise ValueError("The selected website document root is a file.")
|
||||
copy_member(archive, member, target)
|
||||
found_root = True
|
||||
files += 1
|
||||
total_bytes += member.size
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if on_copy is not None:
|
||||
on_copy(member, target)
|
||||
|
||||
if account.username is None:
|
||||
raise ValueError("Expected a DirectAdmin account backup with backup/user.conf.")
|
||||
if not found_root:
|
||||
raise ValueError(
|
||||
"The backup does not contain the selected website document root."
|
||||
)
|
||||
return {
|
||||
"source_username": account.username,
|
||||
"files": files,
|
||||
"bytes": total_bytes,
|
||||
"skipped_non_regular_entries": skipped,
|
||||
}
|
||||
|
||||
|
||||
def copy_member(archive, member, target):
|
||||
if member.size < 0:
|
||||
raise ValueError("A website file has an invalid size in the archive.")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with target.open("xb") as output, archive.extractfile(member) as source:
|
||||
os.fchmod(output.fileno(), 0o600)
|
||||
copyfileobj(source, output, length=1024 * 1024)
|
||||
if output.tell() != member.size:
|
||||
raise ValueError("A website file in the archive is incomplete.")
|
||||
@@ -25,7 +25,7 @@ def make_tar(entries):
|
||||
member.linkname = "public_html"
|
||||
archive.addfile(member)
|
||||
else:
|
||||
data = payload.encode("utf-8")
|
||||
data = payload.encode("utf-8") if isinstance(payload, str) else payload
|
||||
member.size = len(data)
|
||||
archive.addfile(member, BytesIO(data))
|
||||
return output.getvalue()
|
||||
|
||||
@@ -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 django.test import SimpleTestCase
|
||||
|
||||
from coulobre.directadmin import main
|
||||
from coulobre.directadmin_website import stage_website
|
||||
|
||||
from .test_directadmin import make_tar
|
||||
|
||||
|
||||
class DirectAdminWebsiteTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
directory = Path(self.enterContext(TemporaryDirectory()))
|
||||
self.backup = directory / "client.tar.gz"
|
||||
self.destination = directory / "site"
|
||||
self.entries = [
|
||||
("backup/user.conf", "username=client\ndomain=bücher.example\n"),
|
||||
("./domains/Bücher.Example/public_html/index.php", "demo PHP source"),
|
||||
("domains/Bücher.Example/public_html/.htaccess", "demo configuration"),
|
||||
("domains/Bücher.Example/public_html/assets/example.bin", b"\x00\xff\x12"),
|
||||
("domains/Bücher.Example/public_html/assets/site-link", None),
|
||||
("domains/Bücher.Example/private_html/index.html", "private document root"),
|
||||
("domains/other.example/public_html/index.html", "another site's data"),
|
||||
]
|
||||
|
||||
def write_backup(self, entries):
|
||||
self.backup.write_bytes(gzip.compress(make_tar(entries)))
|
||||
|
||||
def test_stage_command_copies_one_selected_website_into_a_private_directory(self):
|
||||
self.write_backup(self.entries)
|
||||
output = self.enterContext(redirect_stdout(StringIO()))
|
||||
self.assertEqual(
|
||||
main(
|
||||
[
|
||||
"stage-website",
|
||||
str(self.backup),
|
||||
"BÜCHER.example.",
|
||||
str(self.destination),
|
||||
]
|
||||
),
|
||||
0,
|
||||
)
|
||||
|
||||
report = json.loads(output.getvalue())
|
||||
document_root = self.destination / "document-root"
|
||||
self.assertEqual(list(self.destination.iterdir()), [document_root])
|
||||
self.assertEqual(report["domain"], "xn--bcher-kva.example")
|
||||
self.assertEqual(report["source_username"], "client")
|
||||
self.assertEqual(report["files"], 3)
|
||||
self.assertEqual(report["bytes"], 36)
|
||||
self.assertEqual(report["skipped_non_regular_entries"], 1)
|
||||
self.assertEqual(report["document_root"], str(document_root))
|
||||
self.assertEqual((document_root / "index.php").read_text(), "demo PHP source")
|
||||
self.assertEqual(
|
||||
(document_root / "assets/example.bin").read_bytes(), b"\x00\xff\x12"
|
||||
)
|
||||
self.assertTrue((document_root / ".htaccess").is_file())
|
||||
self.assertFalse((document_root / "assets/site-link").is_symlink())
|
||||
self.assertFalse((document_root / "index.html").exists())
|
||||
self.assertEqual(stat.S_IMODE(self.destination.stat().st_mode), 0o700)
|
||||
self.assertEqual(
|
||||
stat.S_IMODE((document_root / "index.php").stat().st_mode), 0o600
|
||||
)
|
||||
self.assertNotIn("demo PHP source", output.getvalue())
|
||||
|
||||
def test_private_html_can_be_selected_explicitly(self):
|
||||
self.write_backup(self.entries)
|
||||
|
||||
report = stage_website(
|
||||
self.backup, "bücher.example", self.destination, source_root="private_html"
|
||||
)
|
||||
|
||||
self.assertEqual(report["source_root"], "private_html")
|
||||
self.assertEqual(
|
||||
(Path(report["document_root"]) / "index.html").read_text(),
|
||||
"private document root",
|
||||
)
|
||||
|
||||
def test_stage_does_not_replace_an_existing_destination(self):
|
||||
self.write_backup(self.entries)
|
||||
self.destination.mkdir()
|
||||
existing = self.destination / "existing.txt"
|
||||
existing.write_text("existing content")
|
||||
|
||||
with self.assertRaises(FileExistsError):
|
||||
stage_website(self.backup, "bücher.example", self.destination)
|
||||
|
||||
self.assertEqual(list(self.destination.iterdir()), [existing])
|
||||
self.assertEqual(existing.read_text(), "existing content")
|
||||
|
||||
def test_incomplete_archive_does_not_publish_a_document_root(self):
|
||||
self.write_backup(self.entries)
|
||||
self.backup.write_bytes(self.backup.read_bytes()[:-4])
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "not a readable or complete tar archive"
|
||||
):
|
||||
stage_website(self.backup, "bücher.example", self.destination)
|
||||
|
||||
self.assertFalse(self.destination.exists())
|
||||
|
||||
def test_canonical_domains_cannot_select_two_distinct_source_directories(self):
|
||||
self.write_backup(
|
||||
[
|
||||
*self.entries,
|
||||
(
|
||||
"domains/xn--bcher-kva.example/public_html/second.php",
|
||||
"another source directory",
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "multiple source directories"):
|
||||
stage_website(self.backup, "bücher.example", self.destination)
|
||||
|
||||
self.assertFalse(self.destination.exists())
|
||||
|
||||
def test_duplicate_website_members_do_not_overwrite_or_publish_files(self):
|
||||
self.write_backup([*self.entries, self.entries[1]])
|
||||
|
||||
with self.assertRaises(FileExistsError):
|
||||
stage_website(self.backup, "bücher.example", self.destination)
|
||||
|
||||
self.assertFalse(self.destination.exists())
|
||||
|
||||
def test_document_root_cannot_be_a_regular_file(self):
|
||||
self.write_backup(
|
||||
[
|
||||
("backup/user.conf", "username=client\ndomain=example.net\n"),
|
||||
("domains/example.net/public_html", "unexpected file"),
|
||||
]
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "document root is a file"):
|
||||
stage_website(self.backup, "example.net", self.destination)
|
||||
|
||||
self.assertFalse(self.destination.exists())
|
||||
|
||||
def test_explicit_empty_document_root_is_available_for_staging(self):
|
||||
with tarfile.open(self.backup, mode="w:gz") as archive:
|
||||
payload = b"username=client\ndomain=example.net\n"
|
||||
settings = tarfile.TarInfo("backup/user.conf")
|
||||
settings.size = len(payload)
|
||||
archive.addfile(settings, BytesIO(payload))
|
||||
root = tarfile.TarInfo("domains/example.net/public_html")
|
||||
root.type = tarfile.DIRTYPE
|
||||
archive.addfile(root)
|
||||
|
||||
report = stage_website(self.backup, "example.net", self.destination)
|
||||
|
||||
self.assertEqual(report["files"], 0)
|
||||
self.assertEqual(list(Path(report["document_root"]).iterdir()), [])
|
||||
@@ -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 string import Template
|
||||
|
||||
from .directadmin import DOCUMENT_ROOTS
|
||||
from .domain_names import canonical_domain
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
@@ -79,6 +80,13 @@ def main(argv=None):
|
||||
"status", help="Check a site's local configuration and services."
|
||||
)
|
||||
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)
|
||||
|
||||
try:
|
||||
@@ -95,6 +103,14 @@ def main(argv=None):
|
||||
report = site_status(site)
|
||||
print(json.dumps(report, indent=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:
|
||||
sys.stdout.write(site.render(args.configuration))
|
||||
except (OSError, ValueError) as error:
|
||||
|
||||
@@ -85,14 +85,25 @@ def site_status(site):
|
||||
with (STATE_DIRECTORY / "apply.lock").open("r") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_SH)
|
||||
try:
|
||||
if json.loads(read_root_file(marker)) != site.manifest():
|
||||
raise ValueError("The account is reserved with a different manifest.")
|
||||
check_reservation(site)
|
||||
check_installation(site, SitePaths.for_site(site))
|
||||
except (OSError, ValueError) as error:
|
||||
return {**report, "state": "needs_attention", "problem": str(error)}
|
||||
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):
|
||||
for directory in (
|
||||
paths.account,
|
||||
@@ -111,6 +122,7 @@ def check_installation(site, paths):
|
||||
check_services()
|
||||
if not socket_exists(paths.socket):
|
||||
raise ValueError(f"PHP-FPM is missing the site socket at {paths.socket}.")
|
||||
return uid, gid
|
||||
|
||||
|
||||
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