Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: free space check when using network drives (windows) (#867)
NTFSvolumef33d3b9fc4a8
diff --git a/cyberdrop_dl/managers/download_manager.py b/cyberdrop_dl/managers/download_manager.pyindex 64e25d70a..266a584cd 100644--- a/cyberdrop_dl/managers/download_manager.py+++ b/cyberdrop_dl/managers/download_manager.py@@ -25,15 +25,15 @@ class FileLocksVault:@asynccontextmanagerasync def get_lock(self, filename: str) -> AsyncGenerator:"""Get filelock for the provided filename. Creates one if none exists"""- log_debug(f"Checking lock for {filename}", 20)+ log_debug(f"Checking lock for '{filename}'", 20)if filename not in self._locked_files:- log_debug(f"Lock for {filename} does not exists", 20)+ log_debug(f"Lock for '{filename}' does not exists", 20)self._locked_files[filename] = self._locked_files.get(filename, asyncio.Lock())async with self._locked_files[filename]:- log_debug(f"Lock for {filename} acquired", 20)+ log_debug(f"Lock for '{filename}' acquired", 20)yield- log_debug(f"Lock for {filename} released", 20)+ log_debug(f"Lock for '{filename}' released", 20)class DownloadManager:diff --git a/cyberdrop_dl/managers/storage_manager.py b/cyberdrop_dl/managers/storage_manager.pyindex 1e2ac483c..8b34d1148 100644--- a/cyberdrop_dl/managers/storage_manager.py+++ b/cyberdrop_dl/managers/storage_manager.py@@ -1,24 +1,49 @@from __future__ import annotationsimport asyncio+import itertoolsfrom collections import defaultdict+from dataclasses import asdict, dataclass, fieldfrom datetime import timedeltafrom functools import lru_cachefrom pathlib import Path-from types import MappingProxyTypefrom typing import TYPE_CHECKING, NamedTupleimport psutilfrom pydantic import ByteSizefrom cyberdrop_dl.clients.errors import InsufficientFreeSpaceError-from cyberdrop_dl.utils.logger import log_debug+from cyberdrop_dl.utils.logger import log, log_debugif TYPE_CHECKING:+ from psutil._common import sdiskpart+from cyberdrop_dl.managers.manager import Managerfrom cyberdrop_dl.utils.data_enums_classes.url_objects import MediaItem+@dataclass(frozen=True, slots=True, order=True)+class DiskPartition:+ mountpoint: Path+ device: Path = field(compare=False, hash=False)+ fstype: str = field(compare=False, hash=False)+ opts: str = field(compare=False, hash=False)++ @classmethod+ def from_psutil(cls, diskpart: sdiskpart) -> DiskPartition:+ def resolve(path: str):+ # Resolve converts any mapped drive to UNC paths (windows)+ return Path(path).resolve()++ device, mount = tuple(map(resolve, diskpart[:2]))+ return DiskPartition(mount, device, *diskpart[2:4])+++class MountStats(NamedTuple):+ partition: DiskPartition+ free_space: ByteSize++class StorageManager:"""Runs an infinite loop to keep an updated value of the available space on all storage devices."""@@ -33,27 +58,36 @@ class StorageManager:self._period: int = 2 # how often the check_free_space_loop will run (in seconds)self._log_period: int = 10 # log storage details every <x> loops, AKA log every 20 (2x10) seconds,self._timedelta_period = timedelta(seconds=self._period)+ self._partitions = [DiskPartition.from_psutil(p) for p in psutil.disk_partitions(all=True)]self._loop = asyncio.create_task(self._check_free_space_loop())+ self._unavailable_mounts: set[Path] = set()++ @property+ def mounts(self) -> tuple[Path, ...]:+ return tuple(p.mountpoint for p in self._partitions)++ @property+ def _simplified_stats(self) -> str:+ def simplify(mount_stats: MountStats) -> str:+ free_space = mount_stats.free_space.human_readable(decimal=True)+ stats_as_dict = asdict(mount_stats.partition) | {"free_space": free_space}+ return ", ".join(f"'{k}': '{v}'" for k, v in stats_as_dict.items())- def get_used_mounts_stats(self, simplified: bool = True) -> dict:- """Returns a dict with the infomartion + free space of every used mount.+ stats_as_str = "\n".join(f" {simplify(mount_stats)}" for mount_stats in self.get_used_mounts_stats())+ return f"Storage status:\n {stats_as_str}"- If simplified is `True` (the default), all the information is flatten as a single string and mounts are converted to `str` (for logging)"""- mounts = {}+ def get_used_mounts_stats(self) -> list[MountStats]:+ """Returns information of every used mount + its free space."""+ mounts_stats: list[MountStats] = []for mount in self._used_mounts:free_space = ByteSize(self._free_space[mount])- if simplified:- free_space = free_space.human_readable(decimal=True)- data = get_available_partitions()[mount]._asdict() | {"free_space": free_space}- data.pop("mountpoint", None)- mounts[mount] = data+ partition = next(p for p in self._partitions if p.mountpoint == mount)+ mounts_stats.append(MountStats(partition, free_space))- if simplified:- return {str(key): str(value) for key, value in mounts.items()}- return mounts+ return mounts_statsasync def check_free_space(self, media_item: MediaItem) -> None:- """Checks if there is enough free space on download this item"""+ """Checks if there is enough free space to download this item."""await self.manager.states.RUNNING.wait()if not await self._has_sufficient_space(media_item.download_folder):@@ -73,7 +107,7 @@ class StorageManager:raise InsufficientFreeSpaceError(origin=media_item)async def reset(self):- # This is causing lock ups+ # This is causing lockups# await self._updated.wait() # Make sure a query is not running right nowself.total_data_written = 0self._used_mounts = set()@@ -88,9 +122,38 @@ class StorageManager:passasync def _has_sufficient_space(self, folder: Path) -> bool:- """Checks if there is enough free space to download to this folder"""-- mount = get_mount_point(folder)+ """Checks if there is enough free space to download to this folder.++ `folder` must be an absolute path"""++ async def check_nt_network_drive():+ """Checks is the drive of this folder is a Windows network drive (UNC or unknown mapped drive) and exists."""+ # See: https://github.com/jbsparrow/CyberDropDownloader/issues/860+ if not psutil.WINDOWS:+ return++ # We can discard mapped drives because they would have been converted to UNC path at startup+ # calling resolve on a mapped network drive returns its UNC path+ # it would only still be a mapped drive is the network address is not available+ is_mapped_drive = ":" in folder.drive and len(folder.drive) == 2+ is_unc_path = folder.drive.startswith("\\\\")+ if is_mapped_drive or not is_unc_path:+ return++ folder_drive = drive_as_path(folder.drive)+ async with self._mount_addition_locks[folder_drive]:+ if folder_drive in itertools.chain(self._unavailable_mounts, self.mounts):+ return+ msg = f"Checking new possible network_drive: '{folder_drive}' for folder '{folder}'"+ log_debug(msg)+ if await asyncio.to_thread(folder_drive.is_dir):+ net_drive = DiskPartition(folder_drive, folder_drive, "network_drive", "")+ self._partitions.append(net_drive)+ else:+ self._unavailable_mounts.add(folder_drive)++ await check_nt_network_drive()+ mount = get_mount_point(folder, self.mounts)if not mount:return False@@ -100,6 +163,8 @@ class StorageManager:result = await asyncio.to_thread(psutil.disk_usage, str(mount))self._free_space[mount] = result.freeself._used_mounts.add(mount)+ log(f"A new mountpoint ('{mount!s}') will be used for '{folder}'")+ log(self._simplified_stats)return self._free_space[mount] > self.manager.config_manager.global_settings_data.general.required_free_space@@ -108,10 +173,6 @@ class StorageManager:last_check = -1while True:- # We could also update the values every 512MB of data written (MIN_REQUIRED_FREE_SPACE)- # if self.data_writen // MIN_REQUIRED_FREE_SPACE <= last_check:- # continue- # But every second is more accurateawait self.manager.states.RUNNING.wait()self._updated.clear()last_check += 1@@ -122,43 +183,33 @@ class StorageManager:for mount, result in zip(used_mounts, results, strict=True):self._free_space[mount] = result.freeif last_check % self._log_period == 0:- log_debug({"Storage status": self.get_used_mounts_stats()})+ log_debug(self._simplified_stats)self._updated.set()await asyncio.sleep(self._period)@lru_cache-def get_mount_point(folder: Path) -> Path | None:+def get_mount_point(folder: Path, all_mounts: tuple[Path, ...]) -> Path | None:# Cached for performance.# It's not an expensive operation nor IO blocking, but it's very common for multiple files to share the same download folder# ex: HLS downloads could have over a thousand segments. All of them will go to the same folderassert folder.is_absolute()- mounts = get_available_mountpoints()- possible_mountpoints = [mount for mount in mounts if mount in folder.parents or mount == folder]- if not possible_mountpoints:- # Mount point for this path does not exists- # This will only happend on Windows, ex: an USB drive (`D:`) that is not currently available (AKA disconnected)- # On Unix there always at least 1 mountpoint, root (`/`)- return-- # Get the closest mountpoint to the desired path- # Example:- # mount_a = /home/user/ -> points to an internal SSD- # mount_b = /home/user/USB -> points to an external USB drive- # If folder is `/home/user/USB/videos`, the correct mountpoint is mount_b- return max(possible_mountpoints, key=lambda path: len(path.parts))---@lru_cache-def get_available_partitions() -> MappingProxyType[Path, NamedTuple]:- """NOTE: This function is cached which means it always returns the partitions available at startup"""-- # all=True is required to make sure it works on most platforms. See: https://github.com/giampaolo/psutil/issues/2191- partitions = psutil.disk_partitions(all=True)- return MappingProxyType({Path(p.mountpoint): p for p in partitions})---@lru_cache-def get_available_mountpoints() -> tuple[Path, ...]:- """NOTE: This function is cached which means it always returns the mounts available at startup"""- return tuple(sorted(get_available_partitions().keys()))+ possible_mountpoints = [mount for mount in all_mounts if mount in folder.parents or mount == folder]+ if possible_mountpoints:+ # Get the closest mountpoint to `folder`+ # mount_a = /home/user/ -> points to an internal SSD+ # mount_b = /home/user/USB -> points to an external USB drive+ # If `folder`` is `/home/user/USB/videos`, the correct mountpoint is mount_b+ return max(possible_mountpoints, key=lambda path: len(path.parts))++ # Mount point for this path does not exists+ # This will only happen on Windows, ex: an USB drive (`D:`) that is not currently available (AKA disconnected)+ # On Unix there's always at least 1 mountpoint, root (`/`)+ msg = f"No available mountpoint found for '{folder}'"+ msg += f"\n -> drive = '{drive_as_path(folder.drive)}' , last_parent = '{folder.parents[-1]}'"+ log(msg, 40)+++def drive_as_path(drive: str) -> Path:+ is_mapped_drive = ":" in drive and len(drive) == 2+ return Path(f"{drive}/" if is_mapped_drive else drive)