Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend backup API with file name field #5567

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions supervisor/api/backups.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
ATTR_DATE,
ATTR_DAYS_UNTIL_STALE,
ATTR_EXTRA,
ATTR_FILENAME,
ATTR_FOLDERS,
ATTR_HOMEASSISTANT,
ATTR_HOMEASSISTANT_EXCLUDE_DATABASE,
Expand Down Expand Up @@ -98,6 +99,7 @@ def _ensure_list(item: Any) -> list:
SCHEMA_BACKUP_FULL = vol.Schema(
{
vol.Optional(ATTR_NAME): str,
vol.Optional(ATTR_FILENAME): vol.Match(RE_BACKUP_FILENAME),
vol.Optional(ATTR_PASSWORD): vol.Maybe(str),
vol.Optional(ATTR_COMPRESSED): vol.Maybe(vol.Boolean()),
vol.Optional(ATTR_LOCATION): vol.All(
Expand Down Expand Up @@ -458,10 +460,15 @@ async def download(self, request: web.Request):
raise APIError(f"Backup {backup.slug} is not in location {location}")

_LOGGER.info("Downloading backup %s", backup.slug)
response = web.FileResponse(backup.all_locations[location])
filename = backup.all_locations[location]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
filename = backup.all_locations[location]
filename = backup.all_locations[location].name

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right! Actually I use it for web.FileResponse on the next line, so the fix is somewhat more complicated.

But fixed and tested, should be fine now!

response = web.FileResponse(filename)
response.content_type = CONTENT_TYPE_TAR

download_filename = filename.name
if download_filename == f"{backup.slug}.tar":
download_filename = f"{RE_SLUGIFY_NAME.sub('_', backup.name)}.tar"
response.headers[CONTENT_DISPOSITION] = (
f"attachment; filename={RE_SLUGIFY_NAME.sub('_', backup.name)}.tar"
f"attachment; filename={download_filename}"
)
return response

Expand Down
13 changes: 10 additions & 3 deletions supervisor/backups/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ def _list_backup_files(self, path: Path) -> Iterable[Path]:
def _create_backup(
self,
name: str,
filename: str | None,
sys_type: BackupType,
password: str | None,
compressed: bool = True,
Expand All @@ -196,7 +197,11 @@ def _create_backup(
"""
date_str = utcnow().isoformat()
slug = create_slug(name, date_str)
tar_file = Path(self._get_base_path(location), f"{slug}.tar")

if filename:
tar_file = Path(self._get_base_path(location), Path(filename).name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically this Path(filename).name isn't needed anymore with the regex up front but can leave it if you want, doesn't hurt anything.

else:
tar_file = Path(self._get_base_path(location), f"{slug}.tar")

# init object
backup = Backup(self.coresys, tar_file, slug, self._get_location_name(location))
Expand Down Expand Up @@ -482,6 +487,7 @@ async def _do_backup(
async def do_backup_full(
self,
name: str = "",
filename: str | None = None,
*,
password: str | None = None,
compressed: bool = True,
Expand All @@ -500,7 +506,7 @@ async def do_backup_full(
)

backup = self._create_backup(
name, BackupType.FULL, password, compressed, location, extra
name, filename, BackupType.FULL, password, compressed, location, extra
)

_LOGGER.info("Creating new full backup with slug %s", backup.slug)
Expand All @@ -526,6 +532,7 @@ async def do_backup_full(
async def do_backup_partial(
self,
name: str = "",
filename: str | None = None,
*,
addons: list[str] | None = None,
folders: list[str] | None = None,
Expand Down Expand Up @@ -558,7 +565,7 @@ async def do_backup_partial(
_LOGGER.error("Nothing to create backup for")

backup = self._create_backup(
name, BackupType.PARTIAL, password, compressed, location, extra
name, filename, BackupType.PARTIAL, password, compressed, location, extra
)

_LOGGER.info("Creating new partial backup with slug %s", backup.slug)
Expand Down
22 changes: 22 additions & 0 deletions tests/backups/test_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,28 @@ async def test_do_backup_full(coresys: CoreSys, backup_mock, install_addon_ssh):
assert coresys.core.state == CoreState.RUNNING


@pytest.mark.parametrize(
("filename", "filename_expected"),
[("../my file.tar", "/data/backup/my file.tar"), (None, "/data/backup/{}.tar")],
)
async def test_do_backup_full_with_filename(
coresys: CoreSys, filename: str, filename_expected: str, backup_mock
):
"""Test creating Backup with a specific file name."""
coresys.core.state = CoreState.RUNNING
coresys.hardware.disk.get_disk_free_space = lambda x: 5000

manager = BackupManager(coresys)

# backup_mock fixture causes Backup() to be a MagicMock
await manager.do_backup_full(filename=filename)

slug = backup_mock.call_args[0][2]
assert str(backup_mock.call_args[0][1]) == filename_expected.format(slug)

assert coresys.core.state == CoreState.RUNNING


async def test_do_backup_full_uncompressed(
coresys: CoreSys, backup_mock, install_addon_ssh
):
Expand Down
Loading