Back up and restore mailboxes on a separate mail node #78
No files matched your search
@@ -0,0 +1,20 @@
|
|||||||
|
Match User coulobre-mail-archive-backup,coulobre-mail-archive-restore
|
||||||
|
AuthenticationMethods publickey
|
||||||
|
PubkeyAuthentication yes
|
||||||
|
PasswordAuthentication no
|
||||||
|
KbdInteractiveAuthentication no
|
||||||
|
AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u
|
||||||
|
AuthorizedKeysCommand none
|
||||||
|
TrustedUserCAKeys none
|
||||||
|
DisableForwarding yes
|
||||||
|
PermitTunnel no
|
||||||
|
PermitTTY no
|
||||||
|
PermitUserRC no
|
||||||
|
|
||||||
|
Match User coulobre-mail-archive-backup
|
||||||
|
ForceCommand /usr/bin/socat -t 1810 STDIO UNIX-CONNECT:/run/coulobre-mail-archive-backup.sock
|
||||||
|
|
||||||
|
Match User coulobre-mail-archive-restore
|
||||||
|
ForceCommand /usr/bin/socat -t 1810 STDIO UNIX-CONNECT:/run/coulobre-mail-archive-restore.sock
|
||||||
|
|
||||||
|
Match all
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
Host coulobre-mail-archive-backup
|
||||||
|
User coulobre-mail-archive-backup
|
||||||
|
IdentityFile /etc/coulobre-remote/mail-archive-backup/id_ed25519
|
||||||
|
UserKnownHostsFile /etc/coulobre-remote/mail-archive-backup/known_hosts
|
||||||
|
|
||||||
|
Host coulobre-mail-archive-restore
|
||||||
|
User coulobre-mail-archive-restore
|
||||||
|
IdentityFile /etc/coulobre-remote/mail-archive-restore/id_ed25519
|
||||||
|
UserKnownHostsFile /etc/coulobre-remote/mail-archive-restore/known_hosts
|
||||||
|
|
||||||
|
Host coulobre-mail-archive-*
|
||||||
|
HostName mail.example.org
|
||||||
|
Port 22
|
||||||
|
IdentityAgent none
|
||||||
|
IdentitiesOnly yes
|
||||||
|
PreferredAuthentications publickey
|
||||||
|
GlobalKnownHostsFile none
|
||||||
|
StrictHostKeyChecking yes
|
||||||
|
BatchMode yes
|
||||||
|
ConnectTimeout 5
|
||||||
|
ServerAliveInterval 30
|
||||||
|
ServerAliveCountMax 3
|
||||||
@@ -34,7 +34,9 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
|
|||||||
# COULOBRE_ROUNDCUBE_BRIDGE_KEY=
|
# COULOBRE_ROUNDCUBE_BRIDGE_KEY=
|
||||||
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
|
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
|
||||||
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
|
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
|
||||||
|
# COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1
|
||||||
# COULOBRE_LOCAL_BACKUP_RETENTION=1
|
# COULOBRE_LOCAL_BACKUP_RETENTION=1
|
||||||
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
|
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
|
||||||
# COULOBRE_LOCAL_DATABASE_RESTORE=1
|
# COULOBRE_LOCAL_DATABASE_RESTORE=1
|
||||||
# COULOBRE_LOCAL_MAILBOX_RESTORE=1
|
# COULOBRE_LOCAL_MAILBOX_RESTORE=1
|
||||||
|
# COULOBRE_REMOTE_MAILBOX_RESTORE=1
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[Service]
|
||||||
|
Environment=COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[Service]
|
||||||
|
Environment=COULOBRE_REMOTE_MAILBOX_RESTORE=1
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Coulobre mailbox archive backup socket
|
||||||
|
|
||||||
|
[Socket]
|
||||||
|
ListenStream=/run/coulobre-mail-archive-backup.sock
|
||||||
|
SocketUser=root
|
||||||
|
SocketGroup=coulobre-mail-archive-backup
|
||||||
|
SocketMode=0660
|
||||||
|
Accept=yes
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=sockets.target
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Coulobre mailbox archive backup request
|
||||||
|
After=postfix.service dovecot.service
|
||||||
|
CollectMode=inactive-or-failed
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=exec
|
||||||
|
User=root
|
||||||
|
WorkingDirectory=/opt/coulobre
|
||||||
|
StateDirectory=coulobre/mail-archive-work
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
UMask=0077
|
||||||
|
ExecStart=/opt/coulobre/bin/coulobre-mail-node backup-request
|
||||||
|
StandardInput=socket
|
||||||
|
StandardOutput=socket
|
||||||
|
StandardError=journal
|
||||||
|
RuntimeMaxSec=30min
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectHome=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ReadWritePaths=-/srv/coulobre-mail
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[Service]
|
||||||
|
User=coulobre-mail-archive-backup
|
||||||
|
Group=coulobre-mail-archive-backup
|
||||||
|
StateDirectory=
|
||||||
|
ReadWritePaths=
|
||||||
|
ExecStart=
|
||||||
|
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-archive.conf coulobre-mail-archive-backup
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Coulobre mailbox archive restore socket
|
||||||
|
|
||||||
|
[Socket]
|
||||||
|
ListenStream=/run/coulobre-mail-archive-restore.sock
|
||||||
|
SocketUser=root
|
||||||
|
SocketGroup=coulobre-mail-archive-restore
|
||||||
|
SocketMode=0660
|
||||||
|
Accept=yes
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=sockets.target
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Coulobre mailbox archive restore request
|
||||||
|
After=postfix.service dovecot.service
|
||||||
|
CollectMode=inactive-or-failed
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=exec
|
||||||
|
User=root
|
||||||
|
WorkingDirectory=/opt/coulobre
|
||||||
|
StateDirectory=coulobre/mail-archive-work coulobre/mail-archive-restores
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
UMask=0077
|
||||||
|
ExecStart=/opt/coulobre/bin/coulobre-mail-node restore-request
|
||||||
|
StandardInput=socket
|
||||||
|
StandardOutput=socket
|
||||||
|
StandardError=journal
|
||||||
|
RuntimeMaxSec=30min
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectHome=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ReadWritePaths=-/srv/coulobre-mail
|
||||||
|
CapabilityBoundingSet=~CAP_SYS_RESOURCE
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[Service]
|
||||||
|
User=coulobre-mail-archive-restore
|
||||||
|
Group=coulobre-mail-archive-restore
|
||||||
|
StateDirectory=
|
||||||
|
ReadWritePaths=
|
||||||
|
ExecStart=
|
||||||
|
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-archive.conf coulobre-mail-archive-restore
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# Remove abandoned transfer staging files. Keep the restore journal.
|
||||||
|
e /var/lib/coulobre/mail-archive-work - - - 1d
|
||||||
+113
-7
@@ -586,8 +586,9 @@ worker delivery from recreating an expired archive.
|
|||||||
#### Restore from local account backups in the panel
|
#### Restore from local account backups in the panel
|
||||||
|
|
||||||
Enable local account backups first. Install the restore socket and give the
|
Enable local account backups first. Install the restore socket and give the
|
||||||
backup worker access to it. The archive and the resources being restored
|
backup worker access to it. Website and MariaDB restores use the backup
|
||||||
must be on the same server.
|
host. To restore to a separate mail server, use the
|
||||||
|
[remote mailbox setup](#include-mailboxes-on-a-separate-server).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo groupadd --system coulobre-restore-requests
|
sudo groupadd --system coulobre-restore-requests
|
||||||
@@ -644,7 +645,7 @@ action on a completed backup.
|
|||||||
- **Restore mailbox** offers mailboxes listed in the backup that still
|
- **Restore mailbox** offers mailboxes listed in the backup that still
|
||||||
belong to the account. Use a newly provisioned mailbox with no Maildir.
|
belong to the account. Use a newly provisioned mailbox with no Maildir.
|
||||||
Keep delivery and client access paused for that mailbox during recovery,
|
Keep delivery and client access paused for that mailbox during recovery,
|
||||||
with Postfix and Dovecot running for local checks. The restored mailbox
|
with Postfix and Dovecot running on the destination. The restored mailbox
|
||||||
uses the destination credentials and current quota configuration.
|
uses the destination credentials and current quota configuration.
|
||||||
|
|
||||||
The **Backup restores** section shows each target, source backup, operator,
|
The **Backup restores** section shows each target, source backup, operator,
|
||||||
@@ -652,7 +653,8 @@ and result. Keep the request records under
|
|||||||
`/var/lib/coulobre/account-restores/` while corresponding jobs could still be
|
`/var/lib/coulobre/account-restores/` while corresponding jobs could still be
|
||||||
delivered. If the panel cannot confirm a restore, check the destination
|
delivered. If the panel cannot confirm a restore, check the destination
|
||||||
before submitting another. For resources on separate servers, use the
|
before submitting another. For resources on separate servers, use the
|
||||||
[account bundle commands](development.md#recover-backups-from-the-bundle).
|
[account bundle commands](development.md#recover-backups-from-the-bundle)
|
||||||
|
or the remote mailbox action below.
|
||||||
|
|
||||||
##### Run a backup and restore drill
|
##### Run a backup and restore drill
|
||||||
|
|
||||||
@@ -690,9 +692,113 @@ starting or scheduling an account backup. They can also edit an existing
|
|||||||
schedule that includes mail. If you disable mailbox backups while such a
|
schedule that includes mail. If you disable mailbox backups while such a
|
||||||
schedule is enabled, the subsequent jobs report a failure until you adjust
|
schedule is enabled, the subsequent jobs report a failure until you adjust
|
||||||
the schedule or re-enable local mailbox backups. Provision all listed
|
the schedule or re-enable local mailbox backups. Provision all listed
|
||||||
mailboxes before requesting a backup with mail. For mailboxes on a separate
|
mailboxes before requesting a backup with mail.
|
||||||
server, use the
|
|
||||||
[bundle workflow for separate nodes](development.md#bundle-backups-from-separate-nodes).
|
#### Include mailboxes on a separate server
|
||||||
|
|
||||||
|
Enable local account backups on the panel host and provision the
|
||||||
|
mailboxes on the [separate mail node](#provision-mail-and-dns-on-separate-servers).
|
||||||
|
Upgrade Coulobre on both hosts. The website, database dumps, and completed
|
||||||
|
ZIP stay on the backup host. The mail node streams the native snapshots
|
||||||
|
over SSH and uses temporary disk space while collecting or restoring a
|
||||||
|
mailbox.
|
||||||
|
|
||||||
|
Choose which operations to enable. The examples enable both; use just
|
||||||
|
`backup` in the loops if you only want to collect mail.
|
||||||
|
|
||||||
|
On the backup host, create a dedicated identity and SSH key for each
|
||||||
|
operation, and install its relay socket and service.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo apt install openssh-client
|
||||||
|
sudo install -d -m 0755 /etc/coulobre-remote
|
||||||
|
sudo install -m 0644 deploy/openssh/mail-archive-client.conf.example \
|
||||||
|
/etc/coulobre-remote/mail-archive.conf
|
||||||
|
sudoedit /etc/coulobre-remote/mail-archive.conf
|
||||||
|
for action in backup restore; do
|
||||||
|
unit="coulobre-mail-archive-$action"
|
||||||
|
path="/etc/coulobre-remote/mail-archive-$action"
|
||||||
|
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
|
||||||
|
--shell /usr/sbin/nologin "$unit"
|
||||||
|
sudo install -d -o root -g "$unit" -m 0750 "$path"
|
||||||
|
sudo ssh-keygen -t ed25519 -N '' -f "$path/id_ed25519"
|
||||||
|
sudo chown "$unit:$unit" "$path/id_ed25519"
|
||||||
|
sudo install -m 0644 "deploy/systemd/$unit.socket" \
|
||||||
|
"deploy/systemd/$unit@.service" /etc/systemd/system/
|
||||||
|
sudo install -D -m 0644 "deploy/systemd/$unit@.service.d/relay.conf" \
|
||||||
|
"/etc/systemd/system/$unit@.service.d/relay.conf"
|
||||||
|
sudo cat "$path/id_ed25519.pub"
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
Point the SSH aliases at the mail node that serves these mailboxes. Add
|
||||||
|
its verified host key to each operation's `known_hosts` file. Keep both
|
||||||
|
aliases pointed at the same node while jobs are queued or may be retried.
|
||||||
|
|
||||||
|
On the mail node, save the sender's separate public keys as
|
||||||
|
`backup.pub` and `restore.pub`. Install the receiver accounts, sockets,
|
||||||
|
and forced commands.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo apt install openssh-server socat
|
||||||
|
sudo install -d -m 0755 /etc/ssh/coulobre-node-keys
|
||||||
|
for action in backup restore; do
|
||||||
|
unit="coulobre-mail-archive-$action"
|
||||||
|
sudo useradd --system --user-group --no-create-home --home-dir / \
|
||||||
|
--shell /bin/sh "$unit"
|
||||||
|
sudo install -m 0644 "$action.pub" "/etc/ssh/coulobre-node-keys/$unit"
|
||||||
|
sudo install -m 0644 "deploy/systemd/$unit.socket" \
|
||||||
|
"deploy/systemd/$unit@.service" /etc/systemd/system/
|
||||||
|
sudo systemctl enable --now "$unit.socket"
|
||||||
|
done
|
||||||
|
sudo install -m 0644 deploy/openssh/coulobre-mail-archive.conf.example \
|
||||||
|
/etc/ssh/sshd_config.d/00-coulobre-mail-archive.conf
|
||||||
|
sudo install -m 0644 deploy/tmpfiles.d/coulobre-mail-archive.conf \
|
||||||
|
/etc/tmpfiles.d/coulobre-mail-archive.conf
|
||||||
|
sudo sshd -t
|
||||||
|
sudo systemctl reload-or-restart ssh.service
|
||||||
|
sudo systemctl start systemd-tmpfiles-clean.timer
|
||||||
|
```
|
||||||
|
|
||||||
|
Return to the backup host. Enable the corresponding relay sockets and
|
||||||
|
authorize the operations for the account services.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo install -D -m 0644 deploy/systemd/coulobre-account-backup@.service.d/remote-mail.conf \
|
||||||
|
/etc/systemd/system/coulobre-account-backup@.service.d/remote-mail.conf
|
||||||
|
sudo systemctl enable --now coulobre-mail-archive-backup.socket
|
||||||
|
|
||||||
|
# For restores, install the account restore socket and worker access first.
|
||||||
|
sudo install -D -m 0644 deploy/systemd/coulobre-account-restore@.service.d/remote-mail.conf \
|
||||||
|
/etc/systemd/system/coulobre-account-restore@.service.d/remote-mail.conf
|
||||||
|
sudo systemctl enable --now coulobre-mail-archive-restore.socket
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1` and, if enabled,
|
||||||
|
`COULOBRE_REMOTE_MAILBOX_RESTORE=1` in `/etc/coulobre/panel.env`.
|
||||||
|
Each operation takes one transport. Clear its local setting when
|
||||||
|
switching that operation to SSH. Apply migrations, reload systemd, and
|
||||||
|
restart the panel, scheduler and backup worker.
|
||||||
|
|
||||||
|
Select **Include mailboxes** in manual or scheduled backups. A failed or
|
||||||
|
interrupted transfer reports where mail collection stopped and keeps the
|
||||||
|
incomplete backup out of the ready archives and retention count.
|
||||||
|
|
||||||
|
For recovery, pause delivery and client access for the selected mailbox.
|
||||||
|
Use **Restore mailbox** with the matching, provisioned destination and
|
||||||
|
an absent Maildir. If the connection drops before the result is confirmed,
|
||||||
|
use **Retry remote restore** while the source archive is available. The
|
||||||
|
mail node records results by restore ID and checks the archive checksum
|
||||||
|
and destination before writing. If it reports an interrupted restore,
|
||||||
|
inspect the destination before opening a new request. Keep the mail
|
||||||
|
node's restore journal under `/var/lib/coulobre/mail-archive-restores/`
|
||||||
|
while corresponding jobs can still be retried. The cleanup rule removes
|
||||||
|
abandoned transfer staging files after one day.
|
||||||
|
|
||||||
|
For a recovery drill, follow the [backup and restore drill](#run-a-backup-and-restore-drill)
|
||||||
|
with the mailbox stored on the other node. Verify that the backup on the
|
||||||
|
panel host includes the website, SQL dump, and test message, and that the
|
||||||
|
selected message is recovered on the mail node.
|
||||||
|
|
||||||
## Show local database and mailbox connection details
|
## Show local database and mailbox connection details
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class AccountBackup:
|
|||||||
raise ValueError("The account backup lists a database twice.")
|
raise ValueError("The account backup lists a database twice.")
|
||||||
names.add(database.name)
|
names.add(database.name)
|
||||||
if self.mailboxes is not None and len(self.mailboxes) != len(
|
if self.mailboxes is not None and len(self.mailboxes) != len(
|
||||||
set(self.mailboxes)
|
{mailbox.address for mailbox in self.mailboxes}
|
||||||
):
|
):
|
||||||
raise ValueError("The account backup lists a mailbox twice.")
|
raise ValueError("The account backup lists a mailbox twice.")
|
||||||
|
|
||||||
@@ -180,14 +180,16 @@ def private_path(path, *, new=False):
|
|||||||
return path
|
return path
|
||||||
|
|
||||||
|
|
||||||
def create_backup(backup, archive, socket):
|
def create_backup(backup, archive, socket, *, remote_mail=False):
|
||||||
from .database_node_backup import backup_database
|
from .database_node_backup import backup_database
|
||||||
|
from .mail_archive_transport import download_mailbox_backup
|
||||||
from .mail_node_backup import backup_mailbox
|
from .mail_node_backup import backup_mailbox
|
||||||
from .web_node_backup import backup_website
|
from .web_node_backup import backup_website
|
||||||
|
|
||||||
archive = private_path(archive, new=True)
|
archive = private_path(archive, new=True)
|
||||||
with TemporaryDirectory(dir=archive.parent) as directory:
|
with TemporaryDirectory(dir=archive.parent) as directory:
|
||||||
directory = Path(directory)
|
directory = Path(directory)
|
||||||
|
captured = 0
|
||||||
for resource, _, filename in backup.components():
|
for resource, _, filename in backup.components():
|
||||||
path = directory / filename
|
path = directory / filename
|
||||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
@@ -195,8 +197,19 @@ def create_backup(backup, archive, socket):
|
|||||||
backup_website(resource, path)
|
backup_website(resource, path)
|
||||||
elif isinstance(resource, DatabaseSpec):
|
elif isinstance(resource, DatabaseSpec):
|
||||||
backup_database(resource, socket, path)
|
backup_database(resource, socket, path)
|
||||||
else:
|
elif not remote_mail:
|
||||||
backup_mailbox(resource, path)
|
backup_mailbox(resource, path)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
download_mailbox_backup(resource, path)
|
||||||
|
except (OSError, ValueError) as error:
|
||||||
|
raise ValueError(
|
||||||
|
f"Mail collection stopped at {resource.address} "
|
||||||
|
f"({captured} of {len(backup.mailboxes)} captured). "
|
||||||
|
"No account archive was published. "
|
||||||
|
f"{error}"
|
||||||
|
) from None
|
||||||
|
captured += 1
|
||||||
pack_backup(backup, directory, archive)
|
pack_backup(backup, directory, archive)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from .node_files import check_root_file, locked_root_directory
|
|||||||
from .node_requests import serve_apply_request
|
from .node_requests import serve_apply_request
|
||||||
|
|
||||||
REQUEST_VERSION = 1
|
REQUEST_VERSION = 1
|
||||||
|
REMOTE_MAIL_VERSION = 2
|
||||||
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
|
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
|
||||||
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
|
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
|
||||||
BACKUP_TIMEOUT_SECONDS = 30 * 60
|
BACKUP_TIMEOUT_SECONDS = 30 * 60
|
||||||
@@ -25,6 +26,7 @@ BACKUP_TIMEOUT_SECONDS = 30 * 60
|
|||||||
class AccountBackupRequest:
|
class AccountBackupRequest:
|
||||||
backup_id: UUID
|
backup_id: UUID
|
||||||
backup: AccountBackup
|
backup: AccountBackup
|
||||||
|
remote_mail: bool = False
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_manifest(cls, data):
|
def from_manifest(cls, data):
|
||||||
@@ -32,29 +34,39 @@ class AccountBackupRequest:
|
|||||||
not isinstance(data, dict)
|
not isinstance(data, dict)
|
||||||
or data.keys() != {"version", "backup_id", "backup"}
|
or data.keys() != {"version", "backup_id", "backup"}
|
||||||
or type(data["version"]) is not int
|
or type(data["version"]) is not int
|
||||||
or data["version"] != REQUEST_VERSION
|
or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION)
|
||||||
or not isinstance(data["backup_id"], str)
|
or not isinstance(data["backup_id"], str)
|
||||||
):
|
):
|
||||||
raise ValueError("Expected a local account backup request.")
|
raise ValueError("Expected a local account backup request.")
|
||||||
backup_id = UUID(data["backup_id"])
|
backup_id = UUID(data["backup_id"])
|
||||||
if str(backup_id) != data["backup_id"]:
|
if str(backup_id) != data["backup_id"]:
|
||||||
raise ValueError("Expected a canonical backup ID.")
|
raise ValueError("Expected a canonical backup ID.")
|
||||||
return cls(backup_id, AccountBackup.from_manifest(data["backup"]))
|
backup = AccountBackup.from_manifest(data["backup"])
|
||||||
|
remote_mail = data["version"] == REMOTE_MAIL_VERSION
|
||||||
|
if remote_mail and backup.mailboxes is None:
|
||||||
|
raise ValueError(
|
||||||
|
"Expected mailboxes in the remote backup request."
|
||||||
|
)
|
||||||
|
return cls(backup_id, backup, remote_mail)
|
||||||
|
|
||||||
def manifest(self):
|
def manifest(self):
|
||||||
return {
|
return {
|
||||||
"version": REQUEST_VERSION,
|
"version": self.version,
|
||||||
"backup_id": str(self.backup_id),
|
"backup_id": str(self.backup_id),
|
||||||
"backup": self.backup.manifest(),
|
"backup": self.backup.manifest(),
|
||||||
}
|
}
|
||||||
|
|
||||||
def identity(self):
|
def identity(self):
|
||||||
return {
|
return {
|
||||||
"version": REQUEST_VERSION,
|
"version": self.version,
|
||||||
"backup_id": str(self.backup_id),
|
"backup_id": str(self.backup_id),
|
||||||
"account_id": self.backup.website.account_id,
|
"account_id": self.backup.website.account_id,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def version(self):
|
||||||
|
return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION
|
||||||
|
|
||||||
|
|
||||||
def backup_archive(account_id, backup_id):
|
def backup_archive(account_id, backup_id):
|
||||||
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
|
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
|
||||||
@@ -95,11 +107,17 @@ def serve_backup_request():
|
|||||||
def create_requested_backup(request):
|
def create_requested_backup(request):
|
||||||
if os.geteuid() != 0:
|
if os.geteuid() != 0:
|
||||||
raise ValueError("Run create-request as root on the backup node.")
|
raise ValueError("Run create-request as root on the backup node.")
|
||||||
if (
|
if request.backup.mailboxes is not None:
|
||||||
request.backup.mailboxes is not None
|
setting = (
|
||||||
and os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") != "1"
|
"COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL"
|
||||||
):
|
if request.remote_mail
|
||||||
raise ValueError("Enable mailbox backups on the local backup node.")
|
else "COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL"
|
||||||
|
)
|
||||||
|
if os.environ.get(setting) != "1":
|
||||||
|
location = "remote" if request.remote_mail else "local"
|
||||||
|
raise ValueError(
|
||||||
|
f"Enable mailbox backups on the {location} backup node."
|
||||||
|
)
|
||||||
with locked_root_directory(BACKUP_DIRECTORY):
|
with locked_root_directory(BACKUP_DIRECTORY):
|
||||||
archive = ensure_requested_archive(request)
|
archive = ensure_requested_archive(request)
|
||||||
return {"archive_bytes": archive.stat().st_size}
|
return {"archive_bytes": archive.stat().st_size}
|
||||||
@@ -112,6 +130,11 @@ def ensure_requested_archive(request):
|
|||||||
if os.path.lexists(expiration_marker(archive)):
|
if os.path.lexists(expiration_marker(archive)):
|
||||||
raise ValueError("This account backup has expired.")
|
raise ValueError("This account backup has expired.")
|
||||||
if not os.path.lexists(archive):
|
if not os.path.lexists(archive):
|
||||||
|
if request.remote_mail:
|
||||||
|
create_backup(
|
||||||
|
request.backup, archive, DEFAULT_SOCKET, remote_mail=True
|
||||||
|
)
|
||||||
|
else:
|
||||||
create_backup(request.backup, archive, DEFAULT_SOCKET)
|
create_backup(request.backup, archive, DEFAULT_SOCKET)
|
||||||
return archive
|
return archive
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from .node_requests import serve_apply_request
|
|||||||
from .web_node import WebSite
|
from .web_node import WebSite
|
||||||
|
|
||||||
REQUEST_VERSION = 1
|
REQUEST_VERSION = 1
|
||||||
|
REMOTE_MAIL_VERSION = 2
|
||||||
RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores")
|
RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores")
|
||||||
RESTORE_SOCKET = "/run/coulobre-account-restore.sock"
|
RESTORE_SOCKET = "/run/coulobre-account-restore.sock"
|
||||||
RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS
|
RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS
|
||||||
@@ -94,6 +95,7 @@ class ComponentRestoreRequest:
|
|||||||
backup_id: UUID
|
backup_id: UUID
|
||||||
account_id: int
|
account_id: int
|
||||||
resource: DatabaseSpec | MailboxSpec
|
resource: DatabaseSpec | MailboxSpec
|
||||||
|
remote_mail: bool = False
|
||||||
|
|
||||||
def __post_init__(self):
|
def __post_init__(self):
|
||||||
if (
|
if (
|
||||||
@@ -106,6 +108,8 @@ class ComponentRestoreRequest:
|
|||||||
and self.resource.account_id != self.account_id
|
and self.resource.account_id != self.account_id
|
||||||
):
|
):
|
||||||
raise ValueError("The database must belong to the backup account.")
|
raise ValueError("The database must belong to the backup account.")
|
||||||
|
if self.remote_mail and not isinstance(self.resource, MailboxSpec):
|
||||||
|
raise ValueError("Remote mail restore requires a mailbox.")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_manifest(cls, data):
|
def from_manifest(cls, data):
|
||||||
@@ -114,7 +118,7 @@ class ComponentRestoreRequest:
|
|||||||
or data.keys()
|
or data.keys()
|
||||||
!= {"version", "restore_id", "backup_id", "account_id", "resource"}
|
!= {"version", "restore_id", "backup_id", "account_id", "resource"}
|
||||||
or type(data["version"]) is not int
|
or type(data["version"]) is not int
|
||||||
or data["version"] != REQUEST_VERSION
|
or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION)
|
||||||
or not isinstance(data["resource"], dict)
|
or not isinstance(data["resource"], dict)
|
||||||
):
|
):
|
||||||
raise ValueError("Expected a local component restore request.")
|
raise ValueError("Expected a local component restore request.")
|
||||||
@@ -129,11 +133,14 @@ class ComponentRestoreRequest:
|
|||||||
parse_uuid(data["backup_id"]),
|
parse_uuid(data["backup_id"]),
|
||||||
data["account_id"],
|
data["account_id"],
|
||||||
spec,
|
spec,
|
||||||
|
data["version"] == REMOTE_MAIL_VERSION,
|
||||||
)
|
)
|
||||||
|
|
||||||
def manifest(self):
|
def manifest(self):
|
||||||
return {
|
return {
|
||||||
"version": REQUEST_VERSION,
|
"version": REMOTE_MAIL_VERSION
|
||||||
|
if self.remote_mail
|
||||||
|
else REQUEST_VERSION,
|
||||||
"restore_id": str(self.restore_id),
|
"restore_id": str(self.restore_id),
|
||||||
"backup_id": str(self.backup_id),
|
"backup_id": str(self.backup_id),
|
||||||
"account_id": self.account_id,
|
"account_id": self.account_id,
|
||||||
@@ -193,7 +200,10 @@ def restore_requested_website(request):
|
|||||||
|
|
||||||
|
|
||||||
def restore_requested_component(request):
|
def restore_requested_component(request):
|
||||||
if isinstance(request.resource, DatabaseSpec):
|
if request.remote_mail:
|
||||||
|
setting = "COULOBRE_REMOTE_MAILBOX_RESTORE"
|
||||||
|
feature = "remote mailbox"
|
||||||
|
elif isinstance(request.resource, DatabaseSpec):
|
||||||
setting = "COULOBRE_LOCAL_DATABASE_RESTORE"
|
setting = "COULOBRE_LOCAL_DATABASE_RESTORE"
|
||||||
feature = "database"
|
feature = "database"
|
||||||
else:
|
else:
|
||||||
@@ -203,14 +213,19 @@ def restore_requested_component(request):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Enable local {feature} restores on the backup node."
|
f"Enable local {feature} restores on the backup node."
|
||||||
)
|
)
|
||||||
|
if request.remote_mail:
|
||||||
|
# The destination owns the restore claim across SSH disconnects.
|
||||||
|
restore_component_from_bundle(request)
|
||||||
|
else:
|
||||||
apply_restore_once(request, restore_component_from_bundle)
|
apply_restore_once(request, restore_component_from_bundle)
|
||||||
|
|
||||||
|
|
||||||
def apply_restore_once(request, restore):
|
def apply_restore_once(request, restore, *, journal=None):
|
||||||
if os.geteuid() != 0:
|
if os.geteuid() != 0:
|
||||||
raise ValueError("Run the account restore as root on the backup node.")
|
raise ValueError("Run the account restore as root on the backup node.")
|
||||||
with locked_root_directory(RESTORE_DIRECTORY) as directory:
|
journal = RESTORE_DIRECTORY if journal is None else journal
|
||||||
claim = RESTORE_DIRECTORY / f"{request.restore_id}.json"
|
with locked_root_directory(journal) as directory:
|
||||||
|
claim = journal / f"{request.restore_id}.json"
|
||||||
result = claim.with_suffix(".result")
|
result = claim.with_suffix(".result")
|
||||||
manifest = json.dumps(request.manifest())
|
manifest = json.dumps(request.manifest())
|
||||||
try:
|
try:
|
||||||
@@ -259,6 +274,10 @@ def restore_website_from_bundle(request):
|
|||||||
|
|
||||||
def restore_component_from_bundle(request):
|
def restore_component_from_bundle(request):
|
||||||
from .database_node_backup import restore_database
|
from .database_node_backup import restore_database
|
||||||
|
from .mail_archive_transport import (
|
||||||
|
UNCONFIRMED_REMOTE_RESTORE,
|
||||||
|
upload_mailbox_restore,
|
||||||
|
)
|
||||||
from .mail_node_backup import restore_mailbox
|
from .mail_node_backup import restore_mailbox
|
||||||
|
|
||||||
resource = request.resource
|
resource = request.resource
|
||||||
@@ -270,6 +289,11 @@ def restore_component_from_bundle(request):
|
|||||||
) as staged:
|
) as staged:
|
||||||
if isinstance(resource, DatabaseSpec):
|
if isinstance(resource, DatabaseSpec):
|
||||||
restore_database(resource, DEFAULT_SOCKET, staged)
|
restore_database(resource, DEFAULT_SOCKET, staged)
|
||||||
|
elif request.remote_mail:
|
||||||
|
try:
|
||||||
|
upload_mailbox_restore(resource, staged, request.restore_id)
|
||||||
|
except OSError:
|
||||||
|
raise ValueError(UNCONFIRMED_REMOTE_RESTORE) from None
|
||||||
else:
|
else:
|
||||||
restore_mailbox(resource, staged)
|
restore_mailbox(resource, staged)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
from django.core.exceptions import PermissionDenied
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
@@ -15,6 +16,13 @@ from .models import (
|
|||||||
from .resource_requests import lock_hosting_account, require_open_account
|
from .resource_requests import lock_hosting_account, require_open_account
|
||||||
|
|
||||||
|
|
||||||
|
def mail_backups_enabled():
|
||||||
|
return (
|
||||||
|
settings.LOCAL_ACCOUNT_BACKUP_MAIL
|
||||||
|
or settings.REMOTE_ACCOUNT_BACKUP_MAIL
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def account_backup_manifest(account, *, include_mailboxes=False):
|
def account_backup_manifest(account, *, include_mailboxes=False):
|
||||||
mailboxes = None
|
mailboxes = None
|
||||||
if include_mailboxes:
|
if include_mailboxes:
|
||||||
@@ -42,6 +50,8 @@ def _enqueue_backup(account, *, include_mailboxes, scheduled_for=None):
|
|||||||
manifest=account_backup_manifest(
|
manifest=account_backup_manifest(
|
||||||
account, include_mailboxes=include_mailboxes
|
account, include_mailboxes=include_mailboxes
|
||||||
),
|
),
|
||||||
|
remote_mail=include_mailboxes
|
||||||
|
and settings.REMOTE_ACCOUNT_BACKUP_MAIL,
|
||||||
scheduled_for=scheduled_for,
|
scheduled_for=scheduled_for,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,11 @@ def enabled_component_restores():
|
|||||||
kind
|
kind
|
||||||
for kind, enabled in (
|
for kind, enabled in (
|
||||||
(RestoreKind.DATABASE, settings.LOCAL_DATABASE_RESTORE),
|
(RestoreKind.DATABASE, settings.LOCAL_DATABASE_RESTORE),
|
||||||
(RestoreKind.MAILBOX, settings.LOCAL_MAILBOX_RESTORE),
|
(
|
||||||
|
RestoreKind.MAILBOX,
|
||||||
|
settings.LOCAL_MAILBOX_RESTORE
|
||||||
|
or settings.REMOTE_MAILBOX_RESTORE,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
if enabled
|
if enabled
|
||||||
}
|
}
|
||||||
@@ -91,7 +95,12 @@ def queue_component_restore(
|
|||||||
backup,
|
backup,
|
||||||
restore_id,
|
restore_id,
|
||||||
operator_username,
|
operator_username,
|
||||||
{"kind": kind, "resource": resource},
|
{
|
||||||
|
"kind": kind,
|
||||||
|
"resource": resource,
|
||||||
|
"remote_mail": kind == RestoreKind.MAILBOX
|
||||||
|
and settings.REMOTE_MAILBOX_RESTORE,
|
||||||
|
},
|
||||||
ComponentRestoreJob.objects.filter(
|
ComponentRestoreJob.objects.filter(
|
||||||
backup__account=account,
|
backup__account=account,
|
||||||
kind=kind,
|
kind=kind,
|
||||||
@@ -102,6 +111,30 @@ def queue_component_restore(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def retry_remote_mail_restore(job, operator_username):
|
||||||
|
account = lock_hosting_account(job.backup.account_id, customer_id=None)
|
||||||
|
require_active_services(account)
|
||||||
|
job.refresh_from_db()
|
||||||
|
targets = available_restore_resources(
|
||||||
|
job.backup,
|
||||||
|
RestoreKind.MAILBOX,
|
||||||
|
current_restore_resources(account, RestoreKind.MAILBOX),
|
||||||
|
)
|
||||||
|
if not job.can_retry_remote or job.resource not in targets:
|
||||||
|
raise ValidationError("This mailbox restore can no longer be retried.")
|
||||||
|
jobs = ComponentRestoreJob.objects.filter(
|
||||||
|
backup__account=account,
|
||||||
|
kind=RestoreKind.MAILBOX,
|
||||||
|
resource=job.resource,
|
||||||
|
)
|
||||||
|
if jobs.filter(finished_at__isnull=True).exists():
|
||||||
|
raise ValidationError("Wait for the current restore of this target.")
|
||||||
|
ComponentRestoreJob.objects.requeue(
|
||||||
|
jobs.filter(pk=job.pk), operator_username=operator_username
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _queue_restore(
|
def _queue_restore(
|
||||||
jobs, backup, restore_id, operator_username, target, pending, busy
|
jobs, backup, restore_id, operator_username, target, pending, busy
|
||||||
):
|
):
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-21 21:12
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0039_mail_dns_setup"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="accountbackupjob",
|
||||||
|
name="remote_mail",
|
||||||
|
field=models.BooleanField(default=False),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="componentrestorejob",
|
||||||
|
name="remote_mail",
|
||||||
|
field=models.BooleanField(default=False),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -26,6 +26,7 @@ from coulobre.dns_node import (
|
|||||||
MxRecord,
|
MxRecord,
|
||||||
TxtRecord,
|
TxtRecord,
|
||||||
)
|
)
|
||||||
|
from coulobre.mail_archive_transport import UNCONFIRMED_REMOTE_RESTORE
|
||||||
from coulobre.mail_node import (
|
from coulobre.mail_node import (
|
||||||
LOCAL_PART_MAX_LENGTH,
|
LOCAL_PART_MAX_LENGTH,
|
||||||
MAX_MAILBOX_QUOTA_MIB,
|
MAX_MAILBOX_QUOTA_MIB,
|
||||||
@@ -829,6 +830,7 @@ class AccountBackupJob(ProvisioningJob):
|
|||||||
default=uuid.uuid4, unique=True, editable=False
|
default=uuid.uuid4, unique=True, editable=False
|
||||||
)
|
)
|
||||||
manifest = models.JSONField()
|
manifest = models.JSONField()
|
||||||
|
remote_mail = models.BooleanField(default=False)
|
||||||
scheduled_for = models.DateTimeField(null=True, blank=True)
|
scheduled_for = models.DateTimeField(null=True, blank=True)
|
||||||
archive_bytes = models.PositiveBigIntegerField(null=True, blank=True)
|
archive_bytes = models.PositiveBigIntegerField(null=True, blank=True)
|
||||||
retention_protected = models.BooleanField(default=False)
|
retention_protected = models.BooleanField(default=False)
|
||||||
@@ -900,6 +902,7 @@ class ComponentRestoreJob(ProvisioningJob):
|
|||||||
restore_id = models.UUIDField(unique=True, editable=False)
|
restore_id = models.UUIDField(unique=True, editable=False)
|
||||||
kind = models.CharField(max_length=8, choices=Kind)
|
kind = models.CharField(max_length=8, choices=Kind)
|
||||||
resource = models.CharField(max_length=254)
|
resource = models.CharField(max_length=254)
|
||||||
|
remote_mail = models.BooleanField(default=False)
|
||||||
operator_username = models.CharField(max_length=150)
|
operator_username = models.CharField(max_length=150)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
@@ -915,6 +918,16 @@ class ComponentRestoreJob(ProvisioningJob):
|
|||||||
return DatabaseSpec(self.backup.account_id, self.resource).name
|
return DatabaseSpec(self.backup.account_id, self.resource).name
|
||||||
return self.resource
|
return self.resource
|
||||||
|
|
||||||
|
@property
|
||||||
|
def can_retry_remote(self):
|
||||||
|
return (
|
||||||
|
self.kind == self.Kind.MAILBOX
|
||||||
|
and self.remote_mail
|
||||||
|
and self.state == "failed"
|
||||||
|
and self.problem == UNCONFIRMED_REMOTE_RESTORE
|
||||||
|
and self.backup.archive_is_restorable
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class AccountBackupSchedule(models.Model):
|
class AccountBackupSchedule(models.Model):
|
||||||
class Frequency(models.TextChoices):
|
class Frequency(models.TextChoices):
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ from coulobre.web_node import (
|
|||||||
RESPONSE_LIMIT = 32768
|
RESPONSE_LIMIT = 32768
|
||||||
|
|
||||||
|
|
||||||
|
class NodeReplyError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def activate_local_site(site):
|
def activate_local_site(site):
|
||||||
apply_on_local_node(
|
apply_on_local_node(
|
||||||
site, "/run/coulobre-web-apply.sock", "web node", "site"
|
site, "/run/coulobre-web-apply.sock", "web node", "site"
|
||||||
@@ -230,9 +234,9 @@ def apply_on_local_node(
|
|||||||
body = response.read(RESPONSE_LIMIT + 1)
|
body = response.read(RESPONSE_LIMIT + 1)
|
||||||
|
|
||||||
if len(body) > RESPONSE_LIMIT:
|
if len(body) > RESPONSE_LIMIT:
|
||||||
raise ValueError(f"The {node} returned an oversized response.")
|
raise NodeReplyError(f"The {node} returned an oversized response.")
|
||||||
if not body:
|
if not body:
|
||||||
raise ValueError(
|
raise NodeReplyError(
|
||||||
f"The {node} closed the connection without a response."
|
f"The {node} closed the connection without a response."
|
||||||
)
|
)
|
||||||
invalid_response = (
|
invalid_response = (
|
||||||
@@ -246,10 +250,10 @@ def apply_on_local_node(
|
|||||||
for key, value in expected.items()
|
for key, value in expected.items()
|
||||||
)
|
)
|
||||||
except (KeyError, TypeError, ValueError, RecursionError):
|
except (KeyError, TypeError, ValueError, RecursionError):
|
||||||
raise ValueError(invalid_response) from None
|
raise NodeReplyError(invalid_response) from None
|
||||||
if matches:
|
if matches:
|
||||||
if state == "configured" and problem is None:
|
if state == "configured" and problem is None:
|
||||||
return reply
|
return reply
|
||||||
if state == "failed" and isinstance(problem, str) and problem.strip():
|
if state == "failed" and isinstance(problem, str) and problem.strip():
|
||||||
raise ValueError(problem.strip()[:2000])
|
raise ValueError(problem.strip()[:2000])
|
||||||
raise ValueError(invalid_response)
|
raise NodeReplyError(invalid_response)
|
||||||
@@ -19,6 +19,7 @@ from coulobre.account_restore_request import (
|
|||||||
WebsiteRestoreRequest,
|
WebsiteRestoreRequest,
|
||||||
)
|
)
|
||||||
from coulobre.dns_node import DnsZone
|
from coulobre.dns_node import DnsZone
|
||||||
|
from coulobre.mail_archive_transport import UNCONFIRMED_REMOTE_RESTORE
|
||||||
from coulobre.php_pool_settings import PhpPoolSettings
|
from coulobre.php_pool_settings import PhpPoolSettings
|
||||||
from coulobre.sftp_keys import SFTPKeys
|
from coulobre.sftp_keys import SFTPKeys
|
||||||
from coulobre.web_node import WebAlias, WebSite
|
from coulobre.web_node import WebAlias, WebSite
|
||||||
@@ -26,6 +27,7 @@ from coulobre.web_node import WebAlias, WebSite
|
|||||||
from .account_backups import queue_due_account_backups
|
from .account_backups import queue_due_account_backups
|
||||||
from .account_retirement import apply_retirement_job, finalize_retirement
|
from .account_retirement import apply_retirement_job, finalize_retirement
|
||||||
from .backup_restores import (
|
from .backup_restores import (
|
||||||
|
RestoreKind,
|
||||||
available_restore_resources,
|
available_restore_resources,
|
||||||
current_restore_resources,
|
current_restore_resources,
|
||||||
enabled_component_restores,
|
enabled_component_restores,
|
||||||
@@ -54,6 +56,7 @@ from .models import (
|
|||||||
WebsiteRestoreJob,
|
WebsiteRestoreJob,
|
||||||
)
|
)
|
||||||
from .node_client import (
|
from .node_client import (
|
||||||
|
NodeReplyError,
|
||||||
activate_local_site,
|
activate_local_site,
|
||||||
activate_local_site_with_php,
|
activate_local_site_with_php,
|
||||||
create_local_account_backup,
|
create_local_account_backup,
|
||||||
@@ -631,7 +634,7 @@ def apply_mailbox_provisioning(provisioning):
|
|||||||
def create_account_backup(job_id):
|
def create_account_backup(job_id):
|
||||||
if settings.LOCAL_ACCOUNT_BACKUPS:
|
if settings.LOCAL_ACCOUNT_BACKUPS:
|
||||||
run_provisioning_job(
|
run_provisioning_job(
|
||||||
AccountBackupJob.objects.all(),
|
AccountBackupJob.objects.select_related("account"),
|
||||||
job_id,
|
job_id,
|
||||||
apply_account_backup,
|
apply_account_backup,
|
||||||
"Could not complete the request to the local backup node. "
|
"Could not complete the request to the local backup node. "
|
||||||
@@ -644,10 +647,29 @@ def apply_account_backup(job):
|
|||||||
backup = AccountBackup.from_manifest(job.manifest)
|
backup = AccountBackup.from_manifest(job.manifest)
|
||||||
if backup.website.account_id != job.account_id:
|
if backup.website.account_id != job.account_id:
|
||||||
raise ValueError("The backup manifest belongs to a different account.")
|
raise ValueError("The backup manifest belongs to a different account.")
|
||||||
if backup.mailboxes is not None and not settings.LOCAL_ACCOUNT_BACKUP_MAIL:
|
if backup.mailboxes is not None:
|
||||||
raise ValueError("Enable local mailbox backups before trying again.")
|
if job.remote_mail:
|
||||||
|
if not settings.REMOTE_ACCOUNT_BACKUP_MAIL:
|
||||||
|
raise ValueError(
|
||||||
|
"Enable remote mailbox backups before trying again."
|
||||||
|
)
|
||||||
|
current = current_restore_resources(
|
||||||
|
job.account, RestoreKind.MAILBOX
|
||||||
|
)
|
||||||
|
if any(
|
||||||
|
mailbox.address not in current for mailbox in backup.mailboxes
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"A mailbox no longer belongs to this account."
|
||||||
|
)
|
||||||
|
elif not settings.LOCAL_ACCOUNT_BACKUP_MAIL:
|
||||||
|
raise ValueError(
|
||||||
|
"Enable local mailbox backups before trying again."
|
||||||
|
)
|
||||||
size = create_local_account_backup(
|
size = create_local_account_backup(
|
||||||
AccountBackupRequest(job.backup_id, backup)
|
AccountBackupRequest(
|
||||||
|
job.backup_id, backup, remote_mail=job.remote_mail
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return {"archive_bytes": size}
|
return {"archive_bytes": size}
|
||||||
|
|
||||||
@@ -748,11 +770,30 @@ def apply_component_restore(job):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The backup or its restore target is no longer available."
|
"The backup or its restore target is no longer available."
|
||||||
)
|
)
|
||||||
|
if job.kind == RestoreKind.MAILBOX:
|
||||||
|
enabled = (
|
||||||
|
settings.REMOTE_MAILBOX_RESTORE
|
||||||
|
if job.remote_mail
|
||||||
|
else settings.LOCAL_MAILBOX_RESTORE
|
||||||
|
)
|
||||||
|
if not enabled:
|
||||||
|
raise ValueError(
|
||||||
|
"Re-enable the requested mailbox restore transport."
|
||||||
|
)
|
||||||
|
try:
|
||||||
restore_local_component(
|
restore_local_component(
|
||||||
ComponentRestoreRequest(
|
ComponentRestoreRequest(
|
||||||
job.restore_id, backup.backup_id, backup.account_id, target
|
job.restore_id,
|
||||||
|
backup.backup_id,
|
||||||
|
backup.account_id,
|
||||||
|
target,
|
||||||
|
remote_mail=job.remote_mail,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
except (OSError, NodeReplyError):
|
||||||
|
if job.remote_mail:
|
||||||
|
raise ValueError(UNCONFIRMED_REMOTE_RESTORE) from None
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
def run_provisioning_job(
|
def run_provisioning_job(
|
||||||
|
|||||||
@@ -30,6 +30,12 @@
|
|||||||
{{ restore.state|capfirst }}
|
{{ restore.state|capfirst }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if restore.problem %}<div>{{ restore.problem }}</div>{% endif %}
|
{% if restore.problem %}<div>{{ restore.problem }}</div>{% endif %}
|
||||||
|
{% if allow_remote_restore_retry and restore.can_retry_remote %}
|
||||||
|
<form method="post" action="{% url 'panel:mailbox_restore_retry' account.pk restore.pk %}">
|
||||||
|
{% csrf_token %}
|
||||||
|
<button class="button secondary" type="submit">Retry remote restore</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
import hashlib
|
||||||
|
from datetime import timedelta
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest.mock import patch
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.test import SimpleTestCase, TestCase, override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
|
from coulobre.account_backup_request import AccountBackupRequest
|
||||||
|
from coulobre.account_restore_request import ComponentRestoreRequest
|
||||||
|
from coulobre.mail_archive_transport import (
|
||||||
|
UNCONFIRMED_REMOTE_RESTORE,
|
||||||
|
MailArchiveConnectionError,
|
||||||
|
MailArchiveRequest,
|
||||||
|
encode_header,
|
||||||
|
node_reply,
|
||||||
|
receive_archive,
|
||||||
|
)
|
||||||
|
from coulobre.mail_node import MailboxSpec
|
||||||
|
|
||||||
|
from .account_backups import account_backup_manifest, queue_due_account_backups
|
||||||
|
from .models import (
|
||||||
|
AccountBackupJob,
|
||||||
|
AccountBackupSchedule,
|
||||||
|
ComponentRestoreJob,
|
||||||
|
HostingAccount,
|
||||||
|
HostingMailbox,
|
||||||
|
HostingMailDomain,
|
||||||
|
)
|
||||||
|
from .tasks import create_account_backup, restore_backup_component
|
||||||
|
|
||||||
|
|
||||||
|
class MailArchiveProtocolTests(SimpleTestCase):
|
||||||
|
def test_role_and_response_must_match_the_requested_mailbox(self):
|
||||||
|
mailbox = MailboxSpec("account.example", "help", 50)
|
||||||
|
payload = b"fixture"
|
||||||
|
request = MailArchiveRequest(
|
||||||
|
mailbox, uuid4(), len(payload), hashlib.sha256(payload).hexdigest()
|
||||||
|
)
|
||||||
|
manifest = request.manifest()
|
||||||
|
self.assertEqual(
|
||||||
|
MailArchiveRequest.parse(manifest, "restore"), request
|
||||||
|
)
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
MailArchiveRequest.parse(manifest, "backup")
|
||||||
|
wrong = manifest | {
|
||||||
|
"mailbox": MailboxSpec("elsewhere.example", "help", 50).manifest(),
|
||||||
|
"state": "configured",
|
||||||
|
"problem": None,
|
||||||
|
}
|
||||||
|
with self.assertRaises(MailArchiveConnectionError):
|
||||||
|
node_reply(BytesIO(encode_header(wrong)), request)
|
||||||
|
|
||||||
|
def test_truncated_corrupt_or_extra_data_is_discarded(self):
|
||||||
|
payload = b"mail archive fixture"
|
||||||
|
digest = hashlib.sha256(payload).hexdigest()
|
||||||
|
with TemporaryDirectory() as directory:
|
||||||
|
archive = Path(directory) / "mailbox.tar.gz"
|
||||||
|
for received in (
|
||||||
|
payload[:-1],
|
||||||
|
payload + b"! failure",
|
||||||
|
b"!" * len(payload),
|
||||||
|
):
|
||||||
|
with self.subTest(received=received):
|
||||||
|
with self.assertRaises(MailArchiveConnectionError):
|
||||||
|
receive_archive(
|
||||||
|
BytesIO(received),
|
||||||
|
archive,
|
||||||
|
len(payload),
|
||||||
|
digest=digest,
|
||||||
|
)
|
||||||
|
self.assertFalse(archive.exists())
|
||||||
|
receive_archive(
|
||||||
|
BytesIO(payload), archive, len(payload), digest=digest
|
||||||
|
)
|
||||||
|
with self.assertRaises(FileExistsError):
|
||||||
|
receive_archive(BytesIO(b"overwrite"), archive, 9)
|
||||||
|
self.assertEqual(archive.read_bytes(), payload)
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(
|
||||||
|
LOCAL_ACCOUNT_BACKUPS=True,
|
||||||
|
LOCAL_ACCOUNT_BACKUP_MAIL=False,
|
||||||
|
LOCAL_MAILBOX_RESTORE=False,
|
||||||
|
REMOTE_ACCOUNT_BACKUP_MAIL=True,
|
||||||
|
REMOTE_MAILBOX_RESTORE=True,
|
||||||
|
)
|
||||||
|
class RemoteMailboxArchiveTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
cls.operator = get_user_model().objects.create_superuser("operator")
|
||||||
|
cls.account = HostingAccount.objects.create(
|
||||||
|
name="Fixture", primary_domain="account.example"
|
||||||
|
)
|
||||||
|
cls.domain = HostingMailDomain.objects.create(
|
||||||
|
account=cls.account, domain="account.example"
|
||||||
|
)
|
||||||
|
cls.mailbox = HostingMailbox.objects.create(
|
||||||
|
mail_domain=cls.domain, local_part="help"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_scheduler_queues_and_dispatches_remote_mail_in_the_same_backup(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
AccountBackupSchedule.objects.create(
|
||||||
|
account=self.account,
|
||||||
|
include_mailboxes=True,
|
||||||
|
enabled=True,
|
||||||
|
next_run_at=timezone.now() - timedelta(hours=1),
|
||||||
|
time=timezone.now().time(),
|
||||||
|
)
|
||||||
|
queue_due_account_backups(timezone.now())
|
||||||
|
job = AccountBackupJob.objects.get(account=self.account)
|
||||||
|
self.assertTrue(job.remote_mail)
|
||||||
|
self.assertIsNotNone(job.scheduled_for)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.tasks.create_local_account_backup",
|
||||||
|
return_value=300,
|
||||||
|
) as run:
|
||||||
|
create_account_backup(job.pk)
|
||||||
|
request = run.call_args.args[0]
|
||||||
|
self.assertEqual(
|
||||||
|
AccountBackupRequest.from_manifest(request.manifest()), request
|
||||||
|
)
|
||||||
|
self.assertTrue(request.remote_mail)
|
||||||
|
self.assertEqual(request.backup.mailboxes, (self.mailbox.spec,))
|
||||||
|
job.refresh_from_db()
|
||||||
|
self.assertEqual(job.archive_bytes, 300)
|
||||||
|
|
||||||
|
def test_backup_fails_if_queued_address_is_no_longer_owned(self):
|
||||||
|
job = AccountBackupJob.objects.create(
|
||||||
|
account=self.account,
|
||||||
|
remote_mail=True,
|
||||||
|
manifest=account_backup_manifest(
|
||||||
|
self.account, include_mailboxes=True
|
||||||
|
),
|
||||||
|
)
|
||||||
|
new_account = HostingAccount.objects.create(
|
||||||
|
name="Other", primary_domain="other.example"
|
||||||
|
)
|
||||||
|
self.domain.account = new_account
|
||||||
|
self.domain.save(update_fields=["account"])
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.tasks.create_local_account_backup"
|
||||||
|
) as run:
|
||||||
|
create_account_backup(job.pk)
|
||||||
|
run.assert_not_called()
|
||||||
|
job.refresh_from_db()
|
||||||
|
self.assertIn("no longer belongs", job.problem)
|
||||||
|
|
||||||
|
def test_uncertain_restore_retries_the_same_request(self):
|
||||||
|
backup = AccountBackupJob.objects.create(
|
||||||
|
account=self.account,
|
||||||
|
manifest=account_backup_manifest(
|
||||||
|
self.account, include_mailboxes=True
|
||||||
|
),
|
||||||
|
finished_at=timezone.now(),
|
||||||
|
)
|
||||||
|
self.client.force_login(self.operator)
|
||||||
|
action = reverse(
|
||||||
|
"panel:mailbox_restore", args=[self.account.pk, backup.pk]
|
||||||
|
)
|
||||||
|
identifier = uuid4()
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(
|
||||||
|
action,
|
||||||
|
{"restore_id": str(identifier), "resource": str(self.mailbox)},
|
||||||
|
),
|
||||||
|
self.account.get_absolute_url(),
|
||||||
|
)
|
||||||
|
job = ComponentRestoreJob.objects.get(restore_id=identifier)
|
||||||
|
self.assertTrue(job.remote_mail)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.tasks.restore_local_component",
|
||||||
|
side_effect=(OSError("lost reply"), None),
|
||||||
|
) as restore:
|
||||||
|
restore_backup_component(job.pk)
|
||||||
|
job.refresh_from_db()
|
||||||
|
self.assertEqual(job.problem, UNCONFIRMED_REMOTE_RESTORE)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.account.get_absolute_url()),
|
||||||
|
"Retry remote restore",
|
||||||
|
)
|
||||||
|
retry = reverse(
|
||||||
|
"panel:mailbox_restore_retry", args=[self.account.pk, job.pk]
|
||||||
|
)
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(retry), self.account.get_absolute_url()
|
||||||
|
)
|
||||||
|
restore_backup_component(job.pk)
|
||||||
|
job.refresh_from_db()
|
||||||
|
self.assertEqual(job.state, "configured")
|
||||||
|
self.assertEqual(restore.call_args_list[0], restore.call_args_list[1])
|
||||||
|
request = restore.call_args.args[0]
|
||||||
|
self.assertEqual(
|
||||||
|
ComponentRestoreRequest.from_manifest(request.manifest()), request
|
||||||
|
)
|
||||||
|
self.assertEqual(request.restore_id, identifier)
|
||||||
|
self.assertEqual(ComponentRestoreJob.objects.count(), 1)
|
||||||
@@ -117,6 +117,11 @@ urlpatterns = [
|
|||||||
views.RequestComponentRestore.as_view(kind=RestoreKind.MAILBOX),
|
views.RequestComponentRestore.as_view(kind=RestoreKind.MAILBOX),
|
||||||
name="mailbox_restore",
|
name="mailbox_restore",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
"accounts/<int:pk>/restores/<int:restore_pk>/retry-mailbox/",
|
||||||
|
views.RetryRemoteMailRestore.as_view(),
|
||||||
|
name="mailbox_restore_retry",
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"accounts/<int:pk>/sftp/",
|
"accounts/<int:pk>/sftp/",
|
||||||
views.SiteSFTPKeys.as_view(),
|
views.SiteSFTPKeys.as_view(),
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ from .account_backup_forms import (
|
|||||||
)
|
)
|
||||||
from .account_backups import (
|
from .account_backups import (
|
||||||
account_backup_manifest,
|
account_backup_manifest,
|
||||||
|
mail_backups_enabled,
|
||||||
queue_account_backup,
|
queue_account_backup,
|
||||||
save_backup_schedule,
|
save_backup_schedule,
|
||||||
)
|
)
|
||||||
@@ -61,6 +62,7 @@ from .backup_restores import (
|
|||||||
enabled_component_restores,
|
enabled_component_restores,
|
||||||
queue_component_restore,
|
queue_component_restore,
|
||||||
queue_website_restore,
|
queue_website_restore,
|
||||||
|
retry_remote_mail_restore,
|
||||||
)
|
)
|
||||||
from .backup_retention import change_backup_retention, protect_backup
|
from .backup_retention import change_backup_retention, protect_backup
|
||||||
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
|
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
|
||||||
@@ -458,7 +460,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
and not can_view_mailboxes
|
and not can_view_mailboxes
|
||||||
)
|
)
|
||||||
context["account_backup_allow_mail"] = (
|
context["account_backup_allow_mail"] = (
|
||||||
settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes
|
mail_backups_enabled() and can_view_mailboxes
|
||||||
)
|
)
|
||||||
schedule = getattr(self.object, "backup_schedule", None)
|
schedule = getattr(self.object, "backup_schedule", None)
|
||||||
if (
|
if (
|
||||||
@@ -800,7 +802,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
raise Http404
|
raise Http404
|
||||||
include_mailboxes = request.POST.get("include_mail") == "1"
|
include_mailboxes = request.POST.get("include_mail") == "1"
|
||||||
if include_mailboxes:
|
if include_mailboxes:
|
||||||
if not settings.LOCAL_ACCOUNT_BACKUP_MAIL:
|
if not mail_backups_enabled():
|
||||||
raise Http404
|
raise Http404
|
||||||
if not request.user.has_perm(VIEW_MAILBOXES):
|
if not request.user.has_perm(VIEW_MAILBOXES):
|
||||||
return self.handle_no_permission()
|
return self.handle_no_permission()
|
||||||
@@ -991,6 +993,9 @@ def backup_restore_context(account, user, backups, can_view_mailboxes):
|
|||||||
context["backup_restore_jobs"] = sorted(
|
context["backup_restore_jobs"] = sorted(
|
||||||
history, key=attrgetter("requested_at"), reverse=True
|
history, key=attrgetter("requested_at"), reverse=True
|
||||||
)[:10]
|
)[:10]
|
||||||
|
context["allow_remote_restore_retry"] = (
|
||||||
|
settings.REMOTE_MAILBOX_RESTORE and RestoreKind.MAILBOX in kinds
|
||||||
|
)
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
|
||||||
@@ -1102,6 +1107,28 @@ class RequestComponentRestore(BackupRestoreView):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RetryRemoteMailRestore(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
||||||
|
permission_required = COMPONENT_RESTORE_PERMISSIONS[RestoreKind.MAILBOX]
|
||||||
|
|
||||||
|
def post(self, request, pk, restore_pk):
|
||||||
|
if not (
|
||||||
|
settings.LOCAL_ACCOUNT_BACKUPS and settings.REMOTE_MAILBOX_RESTORE
|
||||||
|
):
|
||||||
|
raise Http404
|
||||||
|
job = get_object_or_404(
|
||||||
|
ComponentRestoreJob.objects.select_related("backup"),
|
||||||
|
pk=restore_pk,
|
||||||
|
backup__account_id=pk,
|
||||||
|
kind=RestoreKind.MAILBOX,
|
||||||
|
remote_mail=True,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
retry_remote_mail_restore(job, request.user.get_username())
|
||||||
|
except ValidationError as error:
|
||||||
|
return provisioning_conflict(error)
|
||||||
|
return redirect("panel:account", pk=pk)
|
||||||
|
|
||||||
|
|
||||||
class EditAccountBackupSchedule(
|
class EditAccountBackupSchedule(
|
||||||
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
||||||
):
|
):
|
||||||
@@ -1134,7 +1161,7 @@ class EditAccountBackupSchedule(
|
|||||||
def get_form_kwargs(self):
|
def get_form_kwargs(self):
|
||||||
kwargs = super().get_form_kwargs()
|
kwargs = super().get_form_kwargs()
|
||||||
kwargs["allow_mail"] = (
|
kwargs["allow_mail"] = (
|
||||||
settings.LOCAL_ACCOUNT_BACKUP_MAIL
|
mail_backups_enabled()
|
||||||
and self.request.user.has_perm(VIEW_MAILBOXES)
|
and self.request.user.has_perm(VIEW_MAILBOXES)
|
||||||
)
|
)
|
||||||
return kwargs
|
return kwargs
|
||||||
|
|||||||
@@ -0,0 +1,262 @@
|
|||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from shutil import copyfileobj
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from .mail_node import MailboxSpec
|
||||||
|
|
||||||
|
BACKUP_RELAY = "/run/coulobre-mail-archive-backup.sock"
|
||||||
|
RESTORE_RELAY = "/run/coulobre-mail-archive-restore.sock"
|
||||||
|
WORK_DIRECTORY = Path("/var/lib/coulobre/mail-archive-work")
|
||||||
|
RESTORE_JOURNAL = Path("/var/lib/coulobre/mail-archive-restores")
|
||||||
|
TIMEOUT_SECONDS = 30 * 60
|
||||||
|
HEADER_LIMIT = 8192
|
||||||
|
CHUNK_SIZE = 1024 * 1024
|
||||||
|
DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||||
|
UNCONFIRMED_REMOTE_RESTORE = (
|
||||||
|
"Could not confirm the remote mailbox restore. Retry the same request."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MailArchiveConnectionError(OSError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MailArchiveRequest:
|
||||||
|
mailbox: MailboxSpec
|
||||||
|
restore_id: UUID | None = None
|
||||||
|
size: int | None = None
|
||||||
|
digest: str | None = None
|
||||||
|
|
||||||
|
def manifest(self):
|
||||||
|
fields = {
|
||||||
|
"version": 1,
|
||||||
|
"operation": "restore" if self.restore_id else "backup",
|
||||||
|
"mailbox": self.mailbox.manifest(),
|
||||||
|
}
|
||||||
|
if self.restore_id:
|
||||||
|
fields.update(
|
||||||
|
restore_id=str(self.restore_id),
|
||||||
|
archive_bytes=self.size,
|
||||||
|
sha256=self.digest,
|
||||||
|
)
|
||||||
|
return fields
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def parse(cls, data, operation):
|
||||||
|
fields = {"version", "operation", "mailbox"}
|
||||||
|
if operation == "restore":
|
||||||
|
fields |= {"restore_id", "archive_bytes", "sha256"}
|
||||||
|
if (
|
||||||
|
not isinstance(data, dict)
|
||||||
|
or data.keys() != fields
|
||||||
|
or type(data["version"]) is not int
|
||||||
|
or data["version"] != 1
|
||||||
|
or data["operation"] != operation
|
||||||
|
):
|
||||||
|
raise ValueError("Expected a mailbox archive request.")
|
||||||
|
mailbox = MailboxSpec.from_manifest(data["mailbox"])
|
||||||
|
if operation == "backup":
|
||||||
|
return cls(mailbox)
|
||||||
|
identifier, size, digest = (
|
||||||
|
data["restore_id"],
|
||||||
|
data["archive_bytes"],
|
||||||
|
data["sha256"],
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
not isinstance(identifier, str)
|
||||||
|
or not valid_size(size)
|
||||||
|
or not isinstance(digest, str)
|
||||||
|
or not DIGEST.fullmatch(digest)
|
||||||
|
):
|
||||||
|
raise ValueError("Expected a valid mailbox restore identity.")
|
||||||
|
restore_id = UUID(identifier)
|
||||||
|
if str(restore_id) != identifier:
|
||||||
|
raise ValueError("Expected a canonical restore ID.")
|
||||||
|
return cls(mailbox, restore_id, size, digest)
|
||||||
|
|
||||||
|
|
||||||
|
def valid_size(size):
|
||||||
|
return type(size) is int and 0 < size < 2**63
|
||||||
|
|
||||||
|
|
||||||
|
def read_header(source):
|
||||||
|
body = source.readline(HEADER_LIMIT + 1)
|
||||||
|
if not body.endswith(b"\n") or len(body) > HEADER_LIMIT:
|
||||||
|
raise MailArchiveConnectionError("Incomplete mailbox archive header.")
|
||||||
|
try:
|
||||||
|
return json.loads(body.decode("utf-8"))
|
||||||
|
except (ValueError, RecursionError):
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"Invalid mailbox archive header."
|
||||||
|
) from None
|
||||||
|
|
||||||
|
|
||||||
|
def encode_header(fields):
|
||||||
|
return json.dumps(fields, separators=(",", ":")).encode("utf-8") + b"\n"
|
||||||
|
|
||||||
|
|
||||||
|
def receive_archive(source, archive, size, *, digest=None):
|
||||||
|
calculated = hashlib.sha256() if digest else None
|
||||||
|
target = archive.open("xb")
|
||||||
|
try:
|
||||||
|
with target:
|
||||||
|
os.fchmod(target.fileno(), 0o600)
|
||||||
|
remaining = size
|
||||||
|
while remaining:
|
||||||
|
data = source.read(min(CHUNK_SIZE, remaining))
|
||||||
|
if not data:
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"The mailbox archive transfer ended early."
|
||||||
|
)
|
||||||
|
target.write(data)
|
||||||
|
if calculated is not None:
|
||||||
|
calculated.update(data)
|
||||||
|
remaining -= len(data)
|
||||||
|
if source.read(1):
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"The mailbox archive contains unexpected trailing data."
|
||||||
|
)
|
||||||
|
if calculated is not None and calculated.hexdigest() != digest:
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"The transferred mailbox archive failed its checksum."
|
||||||
|
)
|
||||||
|
except BaseException:
|
||||||
|
archive.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def connected_to_mail_node(path):
|
||||||
|
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
try:
|
||||||
|
client.settimeout(TIMEOUT_SECONDS + 5)
|
||||||
|
client.connect(path)
|
||||||
|
except OSError:
|
||||||
|
client.close()
|
||||||
|
raise
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def node_reply(source, request):
|
||||||
|
reply = read_header(source)
|
||||||
|
identity = request.manifest()
|
||||||
|
if not isinstance(reply, dict) or any(
|
||||||
|
key not in reply
|
||||||
|
or type(reply[key]) is not type(value)
|
||||||
|
or reply[key] != value
|
||||||
|
for key, value in identity.items()
|
||||||
|
):
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"The mail node returned a different mailbox archive identity."
|
||||||
|
)
|
||||||
|
if reply.get("state") == "configured" and reply.get("problem") is None:
|
||||||
|
return reply
|
||||||
|
problem = reply.get("problem")
|
||||||
|
if reply.get("state") == "failed" and isinstance(problem, str) and problem:
|
||||||
|
raise ValueError(problem[:2000])
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"The mail node returned an invalid result."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def download_mailbox_backup(mailbox, archive):
|
||||||
|
request = MailArchiveRequest(mailbox)
|
||||||
|
with connected_to_mail_node(BACKUP_RELAY) as client:
|
||||||
|
client.sendall(encode_header(request.manifest()))
|
||||||
|
client.shutdown(socket.SHUT_WR)
|
||||||
|
with client.makefile("rb") as source:
|
||||||
|
reply = node_reply(source, request)
|
||||||
|
size = reply.get("archive_bytes")
|
||||||
|
if not valid_size(size):
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"The mail node returned an invalid archive size."
|
||||||
|
)
|
||||||
|
receive_archive(source, archive, size)
|
||||||
|
|
||||||
|
|
||||||
|
def upload_mailbox_restore(mailbox, archive, restore_id):
|
||||||
|
with archive.open("rb") as data:
|
||||||
|
digest = hashlib.file_digest(data, "sha256").hexdigest()
|
||||||
|
size = os.fstat(data.fileno()).st_size
|
||||||
|
data.seek(0)
|
||||||
|
request = MailArchiveRequest(mailbox, restore_id, size, digest)
|
||||||
|
with connected_to_mail_node(RESTORE_RELAY) as client:
|
||||||
|
client.sendall(encode_header(request.manifest()))
|
||||||
|
client.sendfile(data)
|
||||||
|
client.shutdown(socket.SHUT_WR)
|
||||||
|
with client.makefile("rb") as source:
|
||||||
|
node_reply(source, request)
|
||||||
|
if source.read(1):
|
||||||
|
raise MailArchiveConnectionError(
|
||||||
|
"The mail node returned unexpected restore data."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def serve_mail_archive(operation):
|
||||||
|
from .account_restore_request import apply_restore_once
|
||||||
|
from .mail_node_backup import backup_mailbox, restore_mailbox
|
||||||
|
from .node_files import require_root_directory
|
||||||
|
|
||||||
|
source, output = sys.stdin.buffer, sys.stdout.buffer
|
||||||
|
identity = {"version": 1, "operation": operation}
|
||||||
|
try:
|
||||||
|
if os.geteuid() != 0:
|
||||||
|
raise ValueError("Run the mail archive service as root.")
|
||||||
|
request = MailArchiveRequest.parse(read_header(source), operation)
|
||||||
|
identity = request.manifest()
|
||||||
|
require_root_directory(WORK_DIRECTORY)
|
||||||
|
with TemporaryDirectory(dir=WORK_DIRECTORY) as directory:
|
||||||
|
archive = Path(directory) / "mailbox.tar.gz"
|
||||||
|
if operation == "backup":
|
||||||
|
if source.read(1):
|
||||||
|
raise ValueError("Unexpected mailbox backup request data.")
|
||||||
|
backup_mailbox(request.mailbox, archive)
|
||||||
|
with archive.open("rb") as data:
|
||||||
|
size = os.fstat(data.fileno()).st_size
|
||||||
|
output.write(
|
||||||
|
encode_header(
|
||||||
|
identity
|
||||||
|
| {
|
||||||
|
"state": "configured",
|
||||||
|
"problem": None,
|
||||||
|
"archive_bytes": size,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
copyfileobj(data, output, length=CHUNK_SIZE)
|
||||||
|
output.flush()
|
||||||
|
else:
|
||||||
|
receive_archive(
|
||||||
|
source, archive, request.size, digest=request.digest
|
||||||
|
)
|
||||||
|
apply_restore_once(
|
||||||
|
request,
|
||||||
|
lambda job: restore_mailbox(job.mailbox, archive),
|
||||||
|
journal=RESTORE_JOURNAL,
|
||||||
|
)
|
||||||
|
output.write(
|
||||||
|
encode_header(
|
||||||
|
identity | {"state": "configured", "problem": None}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
output.flush()
|
||||||
|
except (BrokenPipeError, MailArchiveConnectionError):
|
||||||
|
# The caller has no authoritative result after a transfer error.
|
||||||
|
return 1
|
||||||
|
except (OSError, ValueError) as error:
|
||||||
|
output.write(
|
||||||
|
encode_header(
|
||||||
|
identity | {"state": "failed", "problem": str(error)[:2000]}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
output.flush()
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
@@ -185,6 +185,12 @@ def main(argv=None):
|
|||||||
"apply-request",
|
"apply-request",
|
||||||
help="Apply one mailbox manifest from standard input and report JSON.",
|
help="Apply one mailbox manifest from standard input and report JSON.",
|
||||||
)
|
)
|
||||||
|
commands.add_parser(
|
||||||
|
"backup-request", help="Stream one native mailbox archive."
|
||||||
|
)
|
||||||
|
commands.add_parser(
|
||||||
|
"restore-request", help="Recover one mailbox from a streamed archive."
|
||||||
|
)
|
||||||
status = commands.add_parser(
|
status = commands.add_parser(
|
||||||
"status", help="Check an installed virtual mailbox."
|
"status", help="Check an installed virtual mailbox."
|
||||||
)
|
)
|
||||||
@@ -201,6 +207,11 @@ def main(argv=None):
|
|||||||
restore.add_argument("archive", type=Path)
|
restore.add_argument("archive", type=Path)
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
if args.command in {"backup-request", "restore-request"}:
|
||||||
|
from .mail_archive_transport import serve_mail_archive
|
||||||
|
|
||||||
|
return serve_mail_archive(args.command.removesuffix("-request"))
|
||||||
|
|
||||||
if args.command == "apply-request":
|
if args.command == "apply-request":
|
||||||
return serve_apply_request(
|
return serve_apply_request(
|
||||||
MANIFEST_VERSION,
|
MANIFEST_VERSION,
|
||||||
|
|||||||
@@ -250,6 +250,9 @@ LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1"
|
|||||||
LOCAL_ACCOUNT_BACKUP_MAIL = (
|
LOCAL_ACCOUNT_BACKUP_MAIL = (
|
||||||
os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"
|
os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"
|
||||||
)
|
)
|
||||||
|
REMOTE_ACCOUNT_BACKUP_MAIL = (
|
||||||
|
os.environ.get("COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL") == "1"
|
||||||
|
)
|
||||||
LOCAL_BACKUP_RETENTION = (
|
LOCAL_BACKUP_RETENTION = (
|
||||||
LOCAL_ACCOUNT_BACKUPS
|
LOCAL_ACCOUNT_BACKUPS
|
||||||
and os.environ.get("COULOBRE_LOCAL_BACKUP_RETENTION") == "1"
|
and os.environ.get("COULOBRE_LOCAL_BACKUP_RETENTION") == "1"
|
||||||
@@ -266,6 +269,16 @@ LOCAL_MAILBOX_RESTORE = (
|
|||||||
LOCAL_ACCOUNT_BACKUPS
|
LOCAL_ACCOUNT_BACKUPS
|
||||||
and os.environ.get("COULOBRE_LOCAL_MAILBOX_RESTORE") == "1"
|
and os.environ.get("COULOBRE_LOCAL_MAILBOX_RESTORE") == "1"
|
||||||
)
|
)
|
||||||
|
REMOTE_MAILBOX_RESTORE = (
|
||||||
|
LOCAL_ACCOUNT_BACKUPS
|
||||||
|
and os.environ.get("COULOBRE_REMOTE_MAILBOX_RESTORE") == "1"
|
||||||
|
)
|
||||||
|
if (LOCAL_ACCOUNT_BACKUP_MAIL and REMOTE_ACCOUNT_BACKUP_MAIL) or (
|
||||||
|
LOCAL_MAILBOX_RESTORE and REMOTE_MAILBOX_RESTORE
|
||||||
|
):
|
||||||
|
raise ImproperlyConfigured(
|
||||||
|
"Choose one mailbox transport for backup and one for restore."
|
||||||
|
)
|
||||||
CELERY_BEAT_SCHEDULE = {
|
CELERY_BEAT_SCHEDULE = {
|
||||||
"dispatch-account-retirements": {
|
"dispatch-account-retirements": {
|
||||||
"task": "coulobre.hosting.tasks.dispatch_account_retirements",
|
"task": "coulobre.hosting.tasks.dispatch_account_retirements",
|
||||||
|
|||||||
Reference in new issue
Block a user