2023-08-09 13:47:18 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-02-03 20:28:55 +00:00
|
|
|
import subprocess
|
2023-02-08 16:28:05 +00:00
|
|
|
import json
|
2023-04-03 16:29:06 +00:00
|
|
|
import datetime
|
2023-07-03 20:41:52 +00:00
|
|
|
import tempfile
|
2023-02-03 20:28:55 +00:00
|
|
|
|
2023-08-09 13:47:18 +00:00
|
|
|
from typing import List, TypeVar, Callable
|
2023-04-14 11:58:39 +00:00
|
|
|
from collections.abc import Iterable
|
2023-06-07 15:55:38 +00:00
|
|
|
from json.decoder import JSONDecodeError
|
2023-07-03 20:41:52 +00:00
|
|
|
from os.path import exists, join
|
2023-08-23 11:51:01 +00:00
|
|
|
from os import mkdir
|
2023-08-14 12:43:44 +00:00
|
|
|
from shutil import rmtree
|
2023-02-13 11:16:35 +00:00
|
|
|
|
2023-07-03 20:41:52 +00:00
|
|
|
from selfprivacy_api.backup.util import output_yielder, sync
|
2023-06-23 12:04:33 +00:00
|
|
|
from selfprivacy_api.backup.backuppers import AbstractBackupper
|
2023-02-13 11:16:35 +00:00
|
|
|
from selfprivacy_api.models.backup.snapshot import Snapshot
|
2023-05-17 20:09:29 +00:00
|
|
|
from selfprivacy_api.backup.jobs import get_backup_job
|
|
|
|
from selfprivacy_api.services import get_service_by_id
|
|
|
|
from selfprivacy_api.jobs import Jobs, JobStatus
|
2023-01-23 13:43:18 +00:00
|
|
|
|
2023-02-17 15:55:19 +00:00
|
|
|
from selfprivacy_api.backup.local_secret import LocalBackupSecret
|
|
|
|
|
2023-07-21 11:11:24 +00:00
|
|
|
SHORT_ID_LEN = 8
|
|
|
|
|
2023-08-09 13:47:18 +00:00
|
|
|
T = TypeVar("T", bound=Callable)
|
|
|
|
|
|
|
|
|
|
|
|
def unlocked_repo(func: T) -> T:
|
|
|
|
"""unlock repo and retry if it appears to be locked"""
|
|
|
|
|
|
|
|
def inner(self: ResticBackupper, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
return func(self, *args, **kwargs)
|
2023-08-23 11:51:01 +00:00
|
|
|
except Exception as error:
|
|
|
|
if "unable to create lock" in str(error):
|
2023-08-09 13:47:18 +00:00
|
|
|
self.unlock()
|
|
|
|
return func(self, *args, **kwargs)
|
|
|
|
else:
|
2023-08-23 11:51:01 +00:00
|
|
|
raise error
|
2023-08-09 13:47:18 +00:00
|
|
|
|
|
|
|
# Above, we manually guarantee that the type returned is compatible.
|
|
|
|
return inner # type: ignore
|
|
|
|
|
2023-01-23 13:43:18 +00:00
|
|
|
|
2023-06-23 12:04:33 +00:00
|
|
|
class ResticBackupper(AbstractBackupper):
|
2023-07-20 15:24:26 +00:00
|
|
|
def __init__(self, login_flag: str, key_flag: str, storage_type: str) -> None:
|
2023-01-23 14:21:43 +00:00
|
|
|
self.login_flag = login_flag
|
|
|
|
self.key_flag = key_flag
|
2023-07-20 15:24:26 +00:00
|
|
|
self.storage_type = storage_type
|
2023-02-03 20:28:55 +00:00
|
|
|
self.account = ""
|
|
|
|
self.key = ""
|
2023-05-17 17:48:06 +00:00
|
|
|
self.repo = ""
|
2023-07-20 15:24:26 +00:00
|
|
|
super().__init__()
|
2023-02-03 20:28:55 +00:00
|
|
|
|
2023-07-19 12:59:51 +00:00
|
|
|
def set_creds(self, account: str, key: str, repo: str) -> None:
|
2023-02-03 20:28:55 +00:00
|
|
|
self.account = account
|
|
|
|
self.key = key
|
2023-05-17 17:48:06 +00:00
|
|
|
self.repo = repo
|
2023-01-23 14:21:43 +00:00
|
|
|
|
2023-05-17 17:48:06 +00:00
|
|
|
def restic_repo(self) -> str:
|
2023-01-23 14:21:43 +00:00
|
|
|
# https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#other-services-via-rclone
|
|
|
|
# https://forum.rclone.org/t/can-rclone-be-run-solely-with-command-line-options-no-config-no-env-vars/6314/5
|
2023-07-26 16:45:08 +00:00
|
|
|
return f"rclone:{self.rclone_repo()}"
|
|
|
|
|
|
|
|
def rclone_repo(self) -> str:
|
|
|
|
return f"{self.storage_type}{self.repo}"
|
2023-01-23 14:21:43 +00:00
|
|
|
|
|
|
|
def rclone_args(self):
|
2023-07-26 16:45:08 +00:00
|
|
|
return "rclone.args=serve restic --stdio " + " ".join(
|
|
|
|
self.backend_rclone_args()
|
|
|
|
)
|
2023-01-23 14:21:43 +00:00
|
|
|
|
2023-07-26 16:45:08 +00:00
|
|
|
def backend_rclone_args(self) -> list[str]:
|
|
|
|
args = []
|
2023-02-08 14:05:25 +00:00
|
|
|
if self.account != "":
|
2023-07-26 16:45:08 +00:00
|
|
|
acc_args = [self.login_flag, self.account]
|
|
|
|
args.extend(acc_args)
|
2023-02-08 14:05:25 +00:00
|
|
|
if self.key != "":
|
2023-07-26 16:45:08 +00:00
|
|
|
key_args = [self.key_flag, self.key]
|
|
|
|
args.extend(key_args)
|
|
|
|
return args
|
2023-01-23 14:21:43 +00:00
|
|
|
|
2023-02-17 15:55:19 +00:00
|
|
|
def _password_command(self):
|
|
|
|
return f"echo {LocalBackupSecret.get()}"
|
|
|
|
|
2023-07-03 15:28:12 +00:00
|
|
|
def restic_command(self, *args, tag: str = "") -> List[str]:
|
2023-02-08 14:05:25 +00:00
|
|
|
command = [
|
2023-01-23 14:21:43 +00:00
|
|
|
"restic",
|
|
|
|
"-o",
|
|
|
|
self.rclone_args(),
|
|
|
|
"-r",
|
2023-05-17 17:48:06 +00:00
|
|
|
self.restic_repo(),
|
2023-02-17 15:55:19 +00:00
|
|
|
"--password-command",
|
|
|
|
self._password_command(),
|
2023-02-08 14:05:25 +00:00
|
|
|
]
|
2023-06-23 09:40:10 +00:00
|
|
|
if tag != "":
|
2023-05-17 17:48:06 +00:00
|
|
|
command.extend(
|
|
|
|
[
|
|
|
|
"--tag",
|
2023-06-23 09:40:10 +00:00
|
|
|
tag,
|
2023-05-17 17:48:06 +00:00
|
|
|
]
|
|
|
|
)
|
2023-07-20 15:24:26 +00:00
|
|
|
if args:
|
2023-06-23 12:04:33 +00:00
|
|
|
command.extend(ResticBackupper.__flatten_list(args))
|
2023-02-08 14:05:25 +00:00
|
|
|
return command
|
2023-02-03 20:28:55 +00:00
|
|
|
|
2023-07-26 16:45:08 +00:00
|
|
|
def erase_repo(self) -> None:
|
|
|
|
"""Fully erases repo on remote, can be reinitted again"""
|
|
|
|
command = [
|
|
|
|
"rclone",
|
|
|
|
"purge",
|
|
|
|
self.rclone_repo(),
|
|
|
|
]
|
|
|
|
backend_args = self.backend_rclone_args()
|
|
|
|
if backend_args:
|
|
|
|
command.extend(backend_args)
|
|
|
|
|
|
|
|
with subprocess.Popen(command, stdout=subprocess.PIPE, shell=False) as handle:
|
|
|
|
output = handle.communicate()[0].decode("utf-8")
|
|
|
|
if handle.returncode != 0:
|
|
|
|
raise ValueError(
|
|
|
|
"purge exited with errorcode",
|
|
|
|
handle.returncode,
|
|
|
|
":",
|
|
|
|
output,
|
|
|
|
)
|
|
|
|
|
2023-04-14 11:58:39 +00:00
|
|
|
@staticmethod
|
2023-07-20 15:24:26 +00:00
|
|
|
def __flatten_list(list_to_flatten):
|
2023-04-14 11:58:39 +00:00
|
|
|
"""string-aware list flattener"""
|
|
|
|
result = []
|
2023-07-20 15:24:26 +00:00
|
|
|
for item in list_to_flatten:
|
2023-04-14 11:58:39 +00:00
|
|
|
if isinstance(item, Iterable) and not isinstance(item, str):
|
2023-06-23 12:04:33 +00:00
|
|
|
result.extend(ResticBackupper.__flatten_list(item))
|
2023-04-14 11:58:39 +00:00
|
|
|
continue
|
|
|
|
result.append(item)
|
|
|
|
return result
|
|
|
|
|
2023-08-09 13:47:18 +00:00
|
|
|
@unlocked_repo
|
2023-07-19 12:59:51 +00:00
|
|
|
def start_backup(self, folders: List[str], tag: str) -> Snapshot:
|
2023-02-03 20:28:55 +00:00
|
|
|
"""
|
|
|
|
Start backup with restic
|
|
|
|
"""
|
2023-04-14 11:20:03 +00:00
|
|
|
|
2023-07-19 12:59:51 +00:00
|
|
|
# but maybe it is ok to accept a union
|
|
|
|
# of a string and an array of strings
|
2023-04-14 11:20:03 +00:00
|
|
|
assert not isinstance(folders, str)
|
|
|
|
|
2023-02-03 20:28:55 +00:00
|
|
|
backup_command = self.restic_command(
|
|
|
|
"backup",
|
2023-04-03 16:29:06 +00:00
|
|
|
"--json",
|
2023-04-14 11:58:39 +00:00
|
|
|
folders,
|
2023-06-23 09:40:10 +00:00
|
|
|
tag=tag,
|
2023-02-03 20:28:55 +00:00
|
|
|
)
|
2023-05-17 20:09:29 +00:00
|
|
|
|
|
|
|
messages = []
|
2023-07-19 12:59:51 +00:00
|
|
|
|
|
|
|
service = get_service_by_id(tag)
|
|
|
|
if service is None:
|
|
|
|
raise ValueError("No service with id ", tag)
|
|
|
|
|
|
|
|
job = get_backup_job(service)
|
2023-08-09 13:47:18 +00:00
|
|
|
output = []
|
2023-05-17 20:09:29 +00:00
|
|
|
try:
|
2023-07-03 13:06:54 +00:00
|
|
|
for raw_message in output_yielder(backup_command):
|
2023-08-09 13:47:18 +00:00
|
|
|
output.append(raw_message)
|
2023-07-19 12:59:51 +00:00
|
|
|
message = self.parse_message(
|
|
|
|
raw_message,
|
|
|
|
job,
|
|
|
|
)
|
2023-05-17 20:09:29 +00:00
|
|
|
messages.append(message)
|
2023-07-19 12:59:51 +00:00
|
|
|
return ResticBackupper._snapshot_from_backup_messages(
|
|
|
|
messages,
|
|
|
|
tag,
|
|
|
|
)
|
2023-07-20 15:24:26 +00:00
|
|
|
except ValueError as error:
|
2023-08-09 13:47:18 +00:00
|
|
|
raise ValueError(
|
|
|
|
"Could not create a snapshot: ",
|
|
|
|
str(error),
|
|
|
|
output,
|
|
|
|
"parsed messages:",
|
|
|
|
messages,
|
|
|
|
) from error
|
2023-04-03 16:29:06 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _snapshot_from_backup_messages(messages, repo_name) -> Snapshot:
|
|
|
|
for message in messages:
|
|
|
|
if message["message_type"] == "summary":
|
2023-07-19 12:59:51 +00:00
|
|
|
return ResticBackupper._snapshot_from_fresh_summary(
|
|
|
|
message,
|
|
|
|
repo_name,
|
|
|
|
)
|
2023-04-03 17:23:16 +00:00
|
|
|
raise ValueError("no summary message in restic json output")
|
2023-04-03 16:29:06 +00:00
|
|
|
|
2023-06-28 11:45:07 +00:00
|
|
|
def parse_message(self, raw_message_line: str, job=None) -> dict:
|
|
|
|
message = ResticBackupper.parse_json_output(raw_message_line)
|
|
|
|
if not isinstance(message, dict):
|
|
|
|
raise ValueError("we have too many messages on one line?")
|
2023-05-17 20:21:37 +00:00
|
|
|
if message["message_type"] == "status":
|
|
|
|
if job is not None: # only update status if we run under some job
|
|
|
|
Jobs.update(
|
|
|
|
job,
|
|
|
|
JobStatus.RUNNING,
|
2023-06-28 11:45:07 +00:00
|
|
|
progress=int(message["percent_done"] * 100),
|
2023-05-17 20:21:37 +00:00
|
|
|
)
|
|
|
|
return message
|
2023-05-17 20:09:29 +00:00
|
|
|
|
2023-04-03 16:29:06 +00:00
|
|
|
@staticmethod
|
2023-06-28 11:45:07 +00:00
|
|
|
def _snapshot_from_fresh_summary(message: dict, repo_name) -> Snapshot:
|
2023-04-03 16:29:06 +00:00
|
|
|
return Snapshot(
|
2023-07-21 11:11:24 +00:00
|
|
|
# There is a discrepancy between versions of restic/rclone
|
|
|
|
# Some report short_id in this field and some full
|
|
|
|
id=message["snapshot_id"][0:SHORT_ID_LEN],
|
2023-04-03 16:29:06 +00:00
|
|
|
created_at=datetime.datetime.now(datetime.timezone.utc),
|
|
|
|
service_name=repo_name,
|
|
|
|
)
|
2023-02-08 15:40:45 +00:00
|
|
|
|
2023-07-19 12:59:51 +00:00
|
|
|
def init(self) -> None:
|
2023-02-17 15:59:27 +00:00
|
|
|
init_command = self.restic_command(
|
|
|
|
"init",
|
|
|
|
)
|
2023-02-20 13:04:39 +00:00
|
|
|
with subprocess.Popen(
|
2023-02-17 15:59:27 +00:00
|
|
|
init_command,
|
|
|
|
shell=False,
|
2023-02-20 13:04:39 +00:00
|
|
|
stdout=subprocess.PIPE,
|
2023-02-17 15:59:27 +00:00
|
|
|
stderr=subprocess.STDOUT,
|
2023-02-20 13:04:39 +00:00
|
|
|
) as process_handle:
|
|
|
|
output = process_handle.communicate()[0].decode("utf-8")
|
2023-07-19 12:59:51 +00:00
|
|
|
if "created restic repository" not in output:
|
2023-02-20 13:04:39 +00:00
|
|
|
raise ValueError("cannot init a repo: " + output)
|
2023-02-17 15:59:27 +00:00
|
|
|
|
2023-08-09 13:58:53 +00:00
|
|
|
@unlocked_repo
|
2023-05-29 16:50:14 +00:00
|
|
|
def is_initted(self) -> bool:
|
2023-03-14 00:39:15 +00:00
|
|
|
command = self.restic_command(
|
2023-08-07 13:33:10 +00:00
|
|
|
"check",
|
2023-03-14 00:39:15 +00:00
|
|
|
)
|
|
|
|
|
2023-07-19 12:59:51 +00:00
|
|
|
with subprocess.Popen(
|
|
|
|
command,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
shell=False,
|
2023-08-07 13:33:10 +00:00
|
|
|
stderr=subprocess.STDOUT,
|
2023-07-19 12:59:51 +00:00
|
|
|
) as handle:
|
2023-08-07 13:33:10 +00:00
|
|
|
output = handle.communicate()[0].decode("utf-8")
|
2023-08-04 11:08:23 +00:00
|
|
|
if handle.returncode != 0:
|
2023-08-09 13:58:53 +00:00
|
|
|
if "unable to create lock" in output:
|
|
|
|
raise ValueError("Stale lock detected: ", output)
|
2023-03-14 00:39:15 +00:00
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2023-08-07 13:33:10 +00:00
|
|
|
def unlock(self) -> None:
|
|
|
|
"""Remove stale locks."""
|
|
|
|
command = self.restic_command(
|
|
|
|
"unlock",
|
|
|
|
)
|
|
|
|
|
|
|
|
with subprocess.Popen(
|
|
|
|
command,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
shell=False,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
) as handle:
|
|
|
|
# communication forces to complete and for returncode to get defined
|
|
|
|
output = handle.communicate()[0].decode("utf-8")
|
|
|
|
if handle.returncode != 0:
|
|
|
|
raise ValueError("cannot unlock the backup repository: ", output)
|
|
|
|
|
|
|
|
def lock(self) -> None:
|
|
|
|
"""
|
|
|
|
Introduce a stale lock.
|
|
|
|
Mainly for testing purposes.
|
|
|
|
Double lock is supposed to fail
|
|
|
|
"""
|
|
|
|
command = self.restic_command(
|
|
|
|
"check",
|
|
|
|
)
|
|
|
|
|
|
|
|
# using temporary cache in /run/user/1000/restic-check-cache-817079729
|
|
|
|
# repository 9639c714 opened (repository version 2) successfully, password is correct
|
|
|
|
# created new cache in /run/user/1000/restic-check-cache-817079729
|
|
|
|
# create exclusive lock for repository
|
|
|
|
# load indexes
|
|
|
|
# check all packs
|
|
|
|
# check snapshots, trees and blobs
|
|
|
|
# [0:00] 100.00% 1 / 1 snapshots
|
|
|
|
# no errors were found
|
|
|
|
|
|
|
|
try:
|
|
|
|
for line in output_yielder(command):
|
|
|
|
if "indexes" in line:
|
|
|
|
break
|
|
|
|
if "unable" in line:
|
|
|
|
raise ValueError(line)
|
2023-08-23 11:51:01 +00:00
|
|
|
except Exception as error:
|
|
|
|
raise ValueError("could not lock repository") from error
|
2023-08-07 13:33:10 +00:00
|
|
|
|
2023-08-09 13:58:53 +00:00
|
|
|
@unlocked_repo
|
2023-06-23 09:40:10 +00:00
|
|
|
def restored_size(self, snapshot_id: str) -> int:
|
2023-02-22 18:48:08 +00:00
|
|
|
"""
|
|
|
|
Size of a snapshot
|
|
|
|
"""
|
|
|
|
command = self.restic_command(
|
|
|
|
"stats",
|
|
|
|
snapshot_id,
|
|
|
|
"--json",
|
|
|
|
)
|
|
|
|
|
2023-06-23 09:40:10 +00:00
|
|
|
with subprocess.Popen(
|
|
|
|
command,
|
|
|
|
stdout=subprocess.PIPE,
|
2023-08-09 14:46:27 +00:00
|
|
|
stderr=subprocess.STDOUT,
|
2023-06-23 09:40:10 +00:00
|
|
|
shell=False,
|
|
|
|
) as handle:
|
2023-02-22 18:48:08 +00:00
|
|
|
output = handle.communicate()[0].decode("utf-8")
|
|
|
|
try:
|
2023-06-23 12:04:33 +00:00
|
|
|
parsed_output = ResticBackupper.parse_json_output(output)
|
2023-02-22 18:48:08 +00:00
|
|
|
return parsed_output["total_size"]
|
2023-07-20 15:24:26 +00:00
|
|
|
except ValueError as error:
|
|
|
|
raise ValueError("cannot restore a snapshot: " + output) from error
|
2023-02-22 18:48:08 +00:00
|
|
|
|
2023-08-09 15:18:20 +00:00
|
|
|
@unlocked_repo
|
2023-07-18 17:15:22 +00:00
|
|
|
def restore_from_backup(
|
|
|
|
self,
|
|
|
|
snapshot_id,
|
|
|
|
folders: List[str],
|
|
|
|
verify=True,
|
2023-07-19 12:59:51 +00:00
|
|
|
) -> None:
|
2023-02-08 15:40:45 +00:00
|
|
|
"""
|
|
|
|
Restore from backup with restic
|
|
|
|
"""
|
2023-07-03 20:41:52 +00:00
|
|
|
if folders is None or folders == []:
|
|
|
|
raise ValueError("cannot restore without knowing where to!")
|
|
|
|
|
2023-07-20 15:24:26 +00:00
|
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
2023-07-07 13:14:30 +00:00
|
|
|
if verify:
|
2023-07-20 15:24:26 +00:00
|
|
|
self._raw_verified_restore(snapshot_id, target=temp_dir)
|
|
|
|
snapshot_root = temp_dir
|
2023-08-14 12:43:44 +00:00
|
|
|
for folder in folders:
|
|
|
|
src = join(snapshot_root, folder.strip("/"))
|
|
|
|
if not exists(src):
|
|
|
|
raise ValueError(
|
|
|
|
f"No such path: {src}. We tried to find {folder}"
|
|
|
|
)
|
|
|
|
dst = folder
|
|
|
|
sync(src, dst)
|
|
|
|
|
|
|
|
else: # attempting inplace restore
|
|
|
|
for folder in folders:
|
|
|
|
rmtree(folder)
|
|
|
|
mkdir(folder)
|
|
|
|
self._raw_verified_restore(snapshot_id, target="/")
|
|
|
|
return
|
2023-07-18 17:15:22 +00:00
|
|
|
|
2023-07-19 10:51:36 +00:00
|
|
|
def _raw_verified_restore(self, snapshot_id, target="/"):
|
2023-07-03 20:41:52 +00:00
|
|
|
"""barebones restic restore"""
|
2023-02-08 15:40:45 +00:00
|
|
|
restore_command = self.restic_command(
|
2023-07-19 10:51:36 +00:00
|
|
|
"restore", snapshot_id, "--target", target, "--verify"
|
2023-02-08 15:40:45 +00:00
|
|
|
)
|
|
|
|
|
2023-02-22 14:45:11 +00:00
|
|
|
with subprocess.Popen(
|
2023-08-09 14:46:27 +00:00
|
|
|
restore_command,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
shell=False,
|
2023-02-22 14:45:11 +00:00
|
|
|
) as handle:
|
|
|
|
|
2023-07-19 12:59:51 +00:00
|
|
|
# for some reason restore does not support
|
|
|
|
# nice reporting of progress via json
|
2023-02-22 14:45:11 +00:00
|
|
|
output = handle.communicate()[0].decode("utf-8")
|
2023-02-22 15:58:36 +00:00
|
|
|
if "restoring" not in output:
|
2023-02-22 14:45:11 +00:00
|
|
|
raise ValueError("cannot restore a snapshot: " + output)
|
2023-02-08 16:28:05 +00:00
|
|
|
|
2023-07-03 20:53:21 +00:00
|
|
|
assert (
|
|
|
|
handle.returncode is not None
|
|
|
|
) # none should be impossible after communicate
|
|
|
|
if handle.returncode != 0:
|
|
|
|
raise ValueError(
|
2023-07-19 12:59:51 +00:00
|
|
|
"restore exited with errorcode",
|
|
|
|
handle.returncode,
|
|
|
|
":",
|
|
|
|
output,
|
2023-07-03 20:53:21 +00:00
|
|
|
)
|
|
|
|
|
2023-08-09 15:18:20 +00:00
|
|
|
@unlocked_repo
|
2023-07-19 12:59:51 +00:00
|
|
|
def forget_snapshot(self, snapshot_id) -> None:
|
|
|
|
"""
|
|
|
|
Either removes snapshot or marks it for deletion later,
|
|
|
|
depending on server settings
|
|
|
|
"""
|
2023-07-05 13:13:30 +00:00
|
|
|
forget_command = self.restic_command(
|
|
|
|
"forget",
|
|
|
|
snapshot_id,
|
|
|
|
)
|
|
|
|
|
|
|
|
with subprocess.Popen(
|
2023-07-19 12:59:51 +00:00
|
|
|
forget_command,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
shell=False,
|
2023-07-05 13:13:30 +00:00
|
|
|
) as handle:
|
2023-07-19 12:59:51 +00:00
|
|
|
# for some reason restore does not support
|
|
|
|
# nice reporting of progress via json
|
|
|
|
output, err = [
|
|
|
|
string.decode(
|
|
|
|
"utf-8",
|
|
|
|
)
|
|
|
|
for string in handle.communicate()
|
|
|
|
]
|
2023-07-05 13:13:30 +00:00
|
|
|
|
|
|
|
if "no matching ID found" in err:
|
|
|
|
raise ValueError(
|
|
|
|
"trying to delete, but no such snapshot: ", snapshot_id
|
|
|
|
)
|
|
|
|
|
|
|
|
assert (
|
|
|
|
handle.returncode is not None
|
|
|
|
) # none should be impossible after communicate
|
|
|
|
if handle.returncode != 0:
|
|
|
|
raise ValueError(
|
2023-08-09 15:18:20 +00:00
|
|
|
"forget exited with errorcode", handle.returncode, ":", output, err
|
2023-07-05 13:13:30 +00:00
|
|
|
)
|
|
|
|
|
2023-05-31 13:16:08 +00:00
|
|
|
def _load_snapshots(self) -> object:
|
2023-02-08 16:28:05 +00:00
|
|
|
"""
|
|
|
|
Load list of snapshots from repository
|
2023-02-17 15:55:19 +00:00
|
|
|
raises Value Error if repo does not exist
|
2023-02-08 16:28:05 +00:00
|
|
|
"""
|
|
|
|
listing_command = self.restic_command(
|
|
|
|
"snapshots",
|
|
|
|
"--json",
|
|
|
|
)
|
|
|
|
|
|
|
|
with subprocess.Popen(
|
|
|
|
listing_command,
|
|
|
|
shell=False,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
) as backup_listing_process_descriptor:
|
|
|
|
output = backup_listing_process_descriptor.communicate()[0].decode("utf-8")
|
|
|
|
|
2023-02-17 15:55:19 +00:00
|
|
|
if "Is there a repository at the following location?" in output:
|
|
|
|
raise ValueError("No repository! : " + output)
|
2023-02-08 16:28:05 +00:00
|
|
|
try:
|
2023-06-23 12:04:33 +00:00
|
|
|
return ResticBackupper.parse_json_output(output)
|
2023-07-20 15:24:26 +00:00
|
|
|
except ValueError as error:
|
2023-08-09 15:18:20 +00:00
|
|
|
raise ValueError("Cannot load snapshots: ", output) from error
|
2023-02-08 16:28:05 +00:00
|
|
|
|
2023-08-09 15:18:20 +00:00
|
|
|
@unlocked_repo
|
2023-05-31 13:16:08 +00:00
|
|
|
def get_snapshots(self) -> List[Snapshot]:
|
2023-02-13 11:16:35 +00:00
|
|
|
"""Get all snapshots from the repo"""
|
2023-02-08 16:28:05 +00:00
|
|
|
snapshots = []
|
2023-05-31 13:16:08 +00:00
|
|
|
for restic_snapshot in self._load_snapshots():
|
2023-02-22 13:35:55 +00:00
|
|
|
snapshot = Snapshot(
|
|
|
|
id=restic_snapshot["short_id"],
|
|
|
|
created_at=restic_snapshot["time"],
|
2023-05-17 17:48:06 +00:00
|
|
|
service_name=restic_snapshot["tags"][0],
|
2023-02-22 13:35:55 +00:00
|
|
|
)
|
|
|
|
|
2023-02-08 16:28:05 +00:00
|
|
|
snapshots.append(snapshot)
|
|
|
|
return snapshots
|
|
|
|
|
2023-06-23 09:40:10 +00:00
|
|
|
@staticmethod
|
|
|
|
def parse_json_output(output: str) -> object:
|
2023-06-23 12:04:33 +00:00
|
|
|
starting_index = ResticBackupper.json_start(output)
|
2023-03-14 00:39:15 +00:00
|
|
|
|
|
|
|
if starting_index == -1:
|
2023-07-19 12:59:51 +00:00
|
|
|
raise ValueError("There is no json in the restic output: " + output)
|
2023-04-03 16:29:06 +00:00
|
|
|
|
|
|
|
truncated_output = output[starting_index:]
|
|
|
|
json_messages = truncated_output.splitlines()
|
|
|
|
if len(json_messages) == 1:
|
2023-06-07 15:55:38 +00:00
|
|
|
try:
|
|
|
|
return json.loads(truncated_output)
|
2023-07-20 15:24:26 +00:00
|
|
|
except JSONDecodeError as error:
|
2023-06-07 15:55:38 +00:00
|
|
|
raise ValueError(
|
|
|
|
"There is no json in the restic output : " + output
|
2023-07-20 15:24:26 +00:00
|
|
|
) from error
|
2023-03-14 00:39:15 +00:00
|
|
|
|
2023-04-03 16:29:06 +00:00
|
|
|
result_array = []
|
|
|
|
for message in json_messages:
|
|
|
|
result_array.append(json.loads(message))
|
|
|
|
return result_array
|
2023-03-14 00:39:15 +00:00
|
|
|
|
2023-06-23 09:40:10 +00:00
|
|
|
@staticmethod
|
|
|
|
def json_start(output: str) -> int:
|
2023-02-22 18:48:08 +00:00
|
|
|
indices = [
|
|
|
|
output.find("["),
|
|
|
|
output.find("{"),
|
|
|
|
]
|
|
|
|
indices = [x for x in indices if x != -1]
|
|
|
|
|
|
|
|
if indices == []:
|
2023-03-14 00:39:15 +00:00
|
|
|
return -1
|
|
|
|
return min(indices)
|
2023-02-22 18:48:08 +00:00
|
|
|
|
2023-06-23 09:40:10 +00:00
|
|
|
@staticmethod
|
|
|
|
def has_json(output: str) -> bool:
|
2023-06-23 12:04:33 +00:00
|
|
|
if ResticBackupper.json_start(output) == -1:
|
2023-03-14 00:39:15 +00:00
|
|
|
return False
|
|
|
|
return True
|