mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 16:36:28 +08:00
Merge pull request #7637 from jxxghp/fix/issue-7634-smb-reconnect
fix(smb): 会话失效后自动重连并限制查询重试
This commit is contained in:
@@ -6,8 +6,9 @@ import errno
|
||||
import ntpath
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Optional, Union
|
||||
from typing import Any, List, Optional, TypeVar, Union
|
||||
|
||||
from app.foundation.singleton import WeakSingleton
|
||||
from app.modules.filemanager.storages import StorageBase, transfer_process
|
||||
@@ -22,7 +23,9 @@ from app.schemas.types import StorageSchema
|
||||
# SMB SDK(smbclient/smbprotocol/spnego)约 12MB,存储发现会导入全部存储实现,
|
||||
# 因此各方法内按需导入,未配置 SMB 时不加载
|
||||
|
||||
lock = threading.Lock()
|
||||
# 初始化和失效会话替换共用可重入锁,读操作重试可以再次检查连接。
|
||||
lock = threading.RLock()
|
||||
SMBResult = TypeVar("SMBResult")
|
||||
|
||||
|
||||
class SMBConnectionError(Exception):
|
||||
@@ -54,6 +57,11 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
# 文件读写块大小,默认 10 MiB
|
||||
chunk_size = 10 * 1024 * 1024
|
||||
|
||||
# 重连失败后等待 30 秒,避免整理队列对故障服务器连续认证。
|
||||
reconnect_interval = 30
|
||||
# 每次重建都推进代数,旧请求的迟到异常不能再次清除新连接。
|
||||
_connection_generation = 0
|
||||
|
||||
@property
|
||||
def snapshot_check_folder_modtime(self) -> bool:
|
||||
"""
|
||||
@@ -84,13 +92,17 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
self._host = None
|
||||
self._username = None
|
||||
self._password = None
|
||||
self._port = 445
|
||||
self._reconnect_after = 0.0
|
||||
|
||||
self._init_connection()
|
||||
with lock:
|
||||
self._init_connection()
|
||||
|
||||
def _init_connection(self) -> None:
|
||||
"""
|
||||
按当前配置建立连接,清除上次状态以免配置无效时继续使用旧共享。
|
||||
在连接锁内按当前配置建立连接,失败后延迟下一次自动重连。
|
||||
"""
|
||||
self._connection_generation += 1
|
||||
self._connected = False
|
||||
self._server_path = None
|
||||
self._shares = {}
|
||||
@@ -106,6 +118,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
self._password = conf.get("password")
|
||||
domain = conf.get("domain", "")
|
||||
port = conf.get("port", 445)
|
||||
self._port = port
|
||||
|
||||
if not self._host:
|
||||
return
|
||||
@@ -145,6 +158,10 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
except Exception as e:
|
||||
logger.error(f"【SMB】连接初始化失败:{e}")
|
||||
self._connected = False
|
||||
finally:
|
||||
self._reconnect_after = (
|
||||
0.0 if self._connected else time.monotonic() + self.reconnect_interval
|
||||
)
|
||||
|
||||
def _configure_shares(self, conf: dict[str, object]) -> None:
|
||||
"""
|
||||
@@ -178,13 +195,13 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
for share in self._shares.values():
|
||||
smbclient.listdir(f"\\\\{self._host}\\{share}")
|
||||
except SMBAuthenticationError as e:
|
||||
raise SMBConnectionError(f"SMB认证失败:{e}")
|
||||
raise SMBConnectionError(f"SMB认证失败:{e}") from e
|
||||
except SMBResponseException as e:
|
||||
raise SMBConnectionError(f"SMB响应错误:{e}")
|
||||
raise SMBConnectionError(f"SMB响应错误:{e}") from e
|
||||
except SMBException as e:
|
||||
raise SMBConnectionError(f"SMB连接错误:{e}")
|
||||
raise SMBConnectionError(f"SMB连接错误:{e}") from e
|
||||
except Exception as e:
|
||||
raise SMBConnectionError(f"连接测试失败:{e}")
|
||||
raise SMBConnectionError(f"连接测试失败:{e}") from e
|
||||
|
||||
def _is_anonymous_access(self) -> bool:
|
||||
"""
|
||||
@@ -194,10 +211,90 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
|
||||
def _check_connection(self) -> None:
|
||||
"""
|
||||
检查SMB连接状态。
|
||||
连接失效时串行替换当前主机的会话,失败后按退避时间再试。
|
||||
|
||||
:raises SMBConnectionError: 未配置共享、处于退避期或重连失败
|
||||
"""
|
||||
if not self._connected or not self._server_path:
|
||||
raise SMBConnectionError("【SMB】连接未建立或已断开,请检查配置!")
|
||||
with lock:
|
||||
if (not self._connected and self._server_path
|
||||
and time.monotonic() >= self._reconnect_after):
|
||||
from smbclient import delete_session
|
||||
|
||||
try:
|
||||
# SDK 可能仍缓存 transport.connected 为真的失效会话,直接注册会复用它。
|
||||
delete_session(self._host, port=self._port, timeout=5)
|
||||
except Exception as err:
|
||||
# SDK 先移除缓存再关闭连接;关闭失败也应继续创建新会话。
|
||||
logger.debug(f"【SMB】关闭失效会话失败:{err}")
|
||||
self._init_connection()
|
||||
if not self._connected or not self._server_path:
|
||||
raise SMBConnectionError("【SMB】连接未建立或已断开,请检查配置!")
|
||||
|
||||
@staticmethod
|
||||
def _is_connection_error(error: Exception) -> bool:
|
||||
"""
|
||||
识别网络、会话失效与 credits 耗尽,保留缺失、权限和空间错误。
|
||||
|
||||
:param error: SDK 原始异常或连接探测包装的异常
|
||||
:return: 是否需要丢弃缓存会话后重连
|
||||
"""
|
||||
from smbprotocol.exceptions import SMBConnectionClosed, SMBException
|
||||
from smbprotocol.header import NtStatus
|
||||
|
||||
if isinstance(error, SMBConnectionError) and isinstance(error.__cause__, Exception):
|
||||
return SMB._is_connection_error(error.__cause__)
|
||||
if isinstance(error, (ConnectionError, TimeoutError, SMBConnectionClosed)):
|
||||
return True
|
||||
if isinstance(error, OSError) and error.errno in (
|
||||
errno.ECONNRESET, errno.ECONNABORTED, errno.ENOTCONN, errno.EPIPE,
|
||||
errno.ETIMEDOUT, errno.EHOSTUNREACH, errno.ENETUNREACH, errno.ENETDOWN,
|
||||
):
|
||||
return True
|
||||
status = getattr(error, "ntstatus", None) or getattr(error, "status", None)
|
||||
if status in (
|
||||
NtStatus.STATUS_NETWORK_NAME_DELETED, NtStatus.STATUS_USER_SESSION_DELETED,
|
||||
NtStatus.STATUS_IO_TIMEOUT,
|
||||
):
|
||||
return True
|
||||
message = str(error)
|
||||
return isinstance(error, SMBException) and (
|
||||
("credits but only" in message and "credits are available" in message)
|
||||
or (message.startswith("Connection timeout of ")
|
||||
and "response from the server" in message)
|
||||
)
|
||||
|
||||
def _call_smb(
|
||||
self, operation: Callable[..., SMBResult], *args: Any,
|
||||
retry: bool = False, **kwargs: Any,
|
||||
) -> SMBResult:
|
||||
"""
|
||||
记录 SDK 连接故障,仅对可安全重放的查询重连并重试一次。
|
||||
|
||||
写操作及已打开句柄的读写失败只失效当前连接,由后续操作恢复,避免重复副作用。
|
||||
|
||||
:param operation: SMB SDK 操作或连接探测
|
||||
:param args: 操作的位置参数
|
||||
:param retry: 是否允许在重连后重放一次只读操作
|
||||
:param kwargs: 操作的关键字参数
|
||||
:return: SDK 操作的原始结果
|
||||
:raises Exception: 普通错误、写操作错误或重试后仍失败的原始异常
|
||||
"""
|
||||
with lock:
|
||||
generation = self._connection_generation
|
||||
try:
|
||||
return operation(*args, **kwargs)
|
||||
except Exception as err:
|
||||
if not self._is_connection_error(err):
|
||||
raise
|
||||
with lock:
|
||||
if generation == self._connection_generation:
|
||||
self._connected = False
|
||||
if not retry:
|
||||
self._reconnect_after = time.monotonic() + self.reconnect_interval
|
||||
if not retry:
|
||||
raise
|
||||
self._check_connection()
|
||||
return self._call_smb(operation, *args, **kwargs)
|
||||
|
||||
def _normalize_path(self, path: Union[str, Path], *, writable: bool = False) -> str:
|
||||
"""
|
||||
@@ -239,7 +336,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
"""
|
||||
import smbclient
|
||||
try:
|
||||
is_directory = smbclient.path.isdir(file_path)
|
||||
is_directory = self._call_smb(smbclient.path.isdir, file_path, retry=True)
|
||||
|
||||
relative_path = self._relative_path(file_path)
|
||||
if not relative_path.startswith("/"):
|
||||
@@ -291,24 +388,22 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
保存或重置配置后清理旧会话并重新连接,即使配置未变或上次连接失败。
|
||||
"""
|
||||
from smbclient import reset_connection_cache
|
||||
reset_connection_cache()
|
||||
self._init_connection()
|
||||
with lock:
|
||||
reset_connection_cache()
|
||||
self._init_connection()
|
||||
|
||||
def check(self) -> bool:
|
||||
"""
|
||||
列举各已配置共享以确认连接可用。
|
||||
|
||||
:return: 已连接且全部共享探测成功返回 True;失败时返回 False 并清除连接标记
|
||||
:return: 全部共享探测成功返回 True;连接故障自动恢复一次,仍失败时返回 False
|
||||
"""
|
||||
if not self._connected:
|
||||
return False
|
||||
|
||||
try:
|
||||
self._test_connection()
|
||||
self._check_connection()
|
||||
self._call_smb(self._test_connection, retry=True)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug(f"【SMB】连接检查失败:{e}")
|
||||
self._connected = False
|
||||
return False
|
||||
|
||||
def list_strict(self, fileitem: _SchemaFileItem) -> List[_SchemaFileItem]:
|
||||
@@ -359,7 +454,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
smb_path = self._normalize_path(file_path.rstrip("/"))
|
||||
|
||||
try:
|
||||
entries = smbclient.listdir(smb_path)
|
||||
entries = self._call_smb(smbclient.listdir, smb_path, retry=True)
|
||||
except (SMBResponseException, SMBException) as e:
|
||||
logger.error(f"【SMB】列出目录失败: {smb_path} - {e}")
|
||||
if strict:
|
||||
@@ -373,7 +468,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
|
||||
entry_path = f"{smb_path}\\{entry}"
|
||||
try:
|
||||
stat_result = smbclient.stat(entry_path)
|
||||
stat_result = self._call_smb(smbclient.stat, entry_path, retry=True)
|
||||
item = self._create_fileitem(stat_result, entry_path, entry, strict=strict)
|
||||
items.append(item)
|
||||
except Exception as e:
|
||||
@@ -408,7 +503,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
|
||||
new_path = self._normalize_path(Path(file_path) / name, writable=True)
|
||||
|
||||
smbclient.mkdir(new_path)
|
||||
self._call_smb(smbclient.mkdir, new_path)
|
||||
|
||||
return _SchemaFileItem(
|
||||
storage=self.schema.value,
|
||||
@@ -473,10 +568,10 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
|
||||
smb_path = self._normalize_path(str(path).rstrip("/"))
|
||||
|
||||
if not smbclient.path.exists(smb_path):
|
||||
if not self._call_smb(smbclient.path.exists, smb_path, retry=True):
|
||||
return None
|
||||
|
||||
stat_result = smbclient.stat(smb_path)
|
||||
stat_result = self._call_smb(smbclient.stat, smb_path, retry=True)
|
||||
file_name = Path(path).name
|
||||
|
||||
return self._create_fileitem(stat_result, smb_path, file_name)
|
||||
@@ -509,7 +604,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
|
||||
smb_path = self._normalize_path(str(path).rstrip("/"))
|
||||
try:
|
||||
stat_result = smbclient.stat(smb_path)
|
||||
stat_result = self._call_smb(smbclient.stat, smb_path, retry=True)
|
||||
except OSError as err:
|
||||
if err.errno in (errno.ENOENT, errno.ENOTDIR):
|
||||
return None
|
||||
@@ -547,7 +642,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
smb_path = self._normalize_path(file_path.rstrip("/"), writable=True)
|
||||
logger.info(f"【SMB】开始删除: {file_path} (类型: {fileitem.type})")
|
||||
|
||||
if not smbclient.path.exists(smb_path):
|
||||
if not self._call_smb(smbclient.path.exists, smb_path, retry=True):
|
||||
logger.warn(f"【SMB】路径不存在,跳过删除: {file_path}")
|
||||
return True
|
||||
|
||||
@@ -556,7 +651,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
self._recursive_delete(smb_path)
|
||||
else:
|
||||
logger.debug(f"【SMB】删除文件: {smb_path}")
|
||||
smbclient.remove(smb_path)
|
||||
self._call_smb(smbclient.remove, smb_path)
|
||||
|
||||
logger.info(f"【SMB】删除成功: {fileitem.path}")
|
||||
return True
|
||||
@@ -580,19 +675,19 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
import smbclient
|
||||
from smbprotocol.exceptions import SMBException, SMBResponseException
|
||||
try:
|
||||
if not smbclient.path.exists(smb_path):
|
||||
if not self._call_smb(smbclient.path.exists, smb_path, retry=True):
|
||||
logger.debug(f"【SMB】路径不存在,跳过删除: {smb_path}")
|
||||
return
|
||||
|
||||
if smbclient.path.isfile(smb_path):
|
||||
if self._call_smb(smbclient.path.isfile, smb_path, retry=True):
|
||||
logger.debug(f"【SMB】删除文件: {smb_path}")
|
||||
smbclient.remove(smb_path)
|
||||
self._call_smb(smbclient.remove, smb_path)
|
||||
return
|
||||
|
||||
if smbclient.path.isdir(smb_path):
|
||||
if self._call_smb(smbclient.path.isdir, smb_path, retry=True):
|
||||
logger.debug(f"【SMB】开始删除目录内容: {smb_path}")
|
||||
try:
|
||||
entries = smbclient.listdir(smb_path)
|
||||
entries = self._call_smb(smbclient.listdir, smb_path, retry=True)
|
||||
logger.debug(f"【SMB】目录 {smb_path} 包含 {len(entries)} 个项目")
|
||||
|
||||
for entry in entries:
|
||||
@@ -603,15 +698,17 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
self._recursive_delete(entry_path)
|
||||
|
||||
logger.debug(f"【SMB】删除空目录: {smb_path}")
|
||||
smbclient.rmdir(smb_path)
|
||||
self._call_smb(smbclient.rmdir, smb_path)
|
||||
logger.debug(f"【SMB】目录删除成功: {smb_path}")
|
||||
|
||||
except SMBResponseException as e:
|
||||
if self._is_connection_error(e):
|
||||
raise
|
||||
# 如果目录不为空,尝试强制删除
|
||||
logger.warn(f"【SMB】目录不为空,尝试强制删除: {smb_path} - {e}")
|
||||
# 使用remove方法尝试删除(某些SMB服务器支持)
|
||||
try:
|
||||
smbclient.remove(smb_path)
|
||||
self._call_smb(smbclient.remove, smb_path)
|
||||
logger.info(f"【SMB】强制删除目录成功: {smb_path}")
|
||||
except Exception as remove_error:
|
||||
logger.error(
|
||||
@@ -649,7 +746,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
parent_path = Path(file_path).parent
|
||||
new_path = self._normalize_path(parent_path / name, writable=True)
|
||||
|
||||
smbclient.rename(old_path, new_path)
|
||||
self._call_smb(smbclient.rename, old_path, new_path)
|
||||
|
||||
logger.info(f"【SMB】重命名成功: {file_path} -> {name}")
|
||||
return True
|
||||
@@ -660,18 +757,21 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
def open_file_stream(self, fileitem: _SchemaFileItem) -> Optional[tuple[Any, int]]:
|
||||
"""
|
||||
以可随机定位的二进制只读句柄打开 SMB 共享文件,供流媒体端点按 HTTP Range 边加载边播放。
|
||||
|
||||
:param fileitem: 待打开的共享内文件
|
||||
:return: 只读句柄与字节长度;连接或打开失败返回 None
|
||||
"""
|
||||
import smbclient
|
||||
|
||||
file_path = fileitem.path
|
||||
if not file_path:
|
||||
return None
|
||||
smb_path = self._normalize_path(file_path)
|
||||
try:
|
||||
self._check_connection()
|
||||
stat_info = smbclient.stat(smb_path)
|
||||
smb_path = self._normalize_path(file_path)
|
||||
stat_info = self._call_smb(smbclient.stat, smb_path, retry=True)
|
||||
size = int(stat_info.st_size)
|
||||
stream = smbclient.open_file(smb_path, mode="rb")
|
||||
stream = self._call_smb(smbclient.open_file, smb_path, mode="rb", retry=True)
|
||||
return stream, size
|
||||
except Exception as e:
|
||||
logger.error(f"【SMB】打开流式读取失败: {fileitem.name} - {e}")
|
||||
@@ -697,9 +797,9 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
local_path = self._build_download_path(fileitem, temp_path)
|
||||
if not local_path:
|
||||
return None
|
||||
smb_path = self._normalize_path(file_path)
|
||||
try:
|
||||
self._check_connection()
|
||||
smb_path = self._normalize_path(file_path)
|
||||
|
||||
local_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -708,14 +808,14 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
logger.info(f"【SMB】开始下载: {fileitem.name} -> {local_path}")
|
||||
progress_callback = transfer_process(Path(file_path).as_posix())
|
||||
|
||||
with smbclient.open_file(smb_path, mode="rb") as src_file:
|
||||
with self._call_smb(smbclient.open_file, smb_path, mode="rb", retry=True) as src_file:
|
||||
with open(local_path, "wb") as dst_file:
|
||||
downloaded_size = 0
|
||||
while True:
|
||||
if runtime_stop_state.consume_transfer_stop(file_path):
|
||||
logger.info(f"【SMB】{file_path} 下载已取消!")
|
||||
return None
|
||||
chunk = src_file.read(self.chunk_size)
|
||||
chunk = self._call_smb(src_file.read, self.chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
dst_file.write(chunk)
|
||||
@@ -761,7 +861,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
progress_callback = transfer_process(path.as_posix())
|
||||
|
||||
with open(path, "rb") as src_file:
|
||||
with smbclient.open_file(smb_path, mode="wb") as dst_file:
|
||||
with self._call_smb(smbclient.open_file, smb_path, mode="wb") as dst_file:
|
||||
uploaded_size = 0
|
||||
while True:
|
||||
if runtime_stop_state.consume_transfer_stop(path.as_posix()):
|
||||
@@ -770,7 +870,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
chunk = src_file.read(self.chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
dst_file.write(chunk)
|
||||
self._call_smb(dst_file.write, chunk)
|
||||
uploaded_size += len(chunk)
|
||||
if file_size:
|
||||
progress = (uploaded_size * 100) / file_size
|
||||
@@ -804,12 +904,12 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
src_path = self._normalize_path(fileitem.path, writable=True)
|
||||
dst_path = self._normalize_path(path / new_name, writable=True)
|
||||
try:
|
||||
if smbclient.path.samefile(src_path, dst_path):
|
||||
if self._call_smb(smbclient.path.samefile, src_path, dst_path, retry=True):
|
||||
raise ValueError("源文件和目标是同一文件,不能执行服务端复制")
|
||||
except OSError as err:
|
||||
if err.errno != errno.ENOENT:
|
||||
raise
|
||||
smbclient.copyfile(src_path, dst_path)
|
||||
self._call_smb(smbclient.copyfile, src_path, dst_path)
|
||||
logger.info(f"【SMB】服务端复制成功: {src_path} -> {dst_path}")
|
||||
return True
|
||||
except Exception as e:
|
||||
@@ -837,7 +937,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
if ntpath.splitdrive(src_path)[0].casefold() != ntpath.splitdrive(dst_path)[0].casefold():
|
||||
self._move_between_shares(fileitem, path, new_name, src_path, dst_path)
|
||||
else:
|
||||
smbclient.rename(src_path, dst_path)
|
||||
self._call_smb(smbclient.rename, src_path, dst_path)
|
||||
logger.info(f"【SMB】服务端移动成功: {src_path} -> {dst_path}")
|
||||
return True
|
||||
except Exception as e:
|
||||
@@ -852,7 +952,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
"""
|
||||
import smbclient
|
||||
try:
|
||||
smbclient.stat(dst_path)
|
||||
self._call_smb(smbclient.stat, dst_path, retry=True)
|
||||
except OSError as err:
|
||||
if err.errno != errno.ENOENT:
|
||||
raise
|
||||
@@ -860,7 +960,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
raise FileExistsError("跨共享移动的目标已存在,请先由整理覆盖策略处理")
|
||||
if not self.copy(fileitem, path, new_name):
|
||||
raise OSError("跨共享服务端复制失败,保留源文件")
|
||||
smbclient.remove(src_path)
|
||||
self._call_smb(smbclient.remove, src_path)
|
||||
|
||||
def link(self, fileitem: _SchemaFileItem, target_file: Path) -> bool:
|
||||
"""
|
||||
@@ -882,15 +982,15 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
if ntpath.splitdrive(src_path)[0].casefold() != ntpath.splitdrive(dst_path)[0].casefold():
|
||||
raise ValueError("SMB 不支持跨共享硬链接,请改用复制或移动,或使用包含两者的共同共享")
|
||||
|
||||
if not smbclient.path.exists(src_path):
|
||||
if not self._call_smb(smbclient.path.exists, src_path, retry=True):
|
||||
raise FileNotFoundError(f"源文件不存在: {src_path}")
|
||||
|
||||
dst_parent = "\\".join(dst_path.rsplit("\\", 1)[:-1])
|
||||
if dst_parent and not smbclient.path.exists(dst_parent):
|
||||
if dst_parent and not self._call_smb(smbclient.path.exists, dst_parent, retry=True):
|
||||
logger.info(f"【SMB】创建目标目录: {dst_parent}")
|
||||
smbclient.makedirs(dst_parent, exist_ok=True)
|
||||
self._call_smb(smbclient.makedirs, dst_parent, exist_ok=True)
|
||||
|
||||
smbclient.link(src_path, dst_path)
|
||||
self._call_smb(smbclient.link, src_path, dst_path)
|
||||
logger.info(f"【SMB】硬链接创建成功: {src_path} -> {dst_path}")
|
||||
return True
|
||||
|
||||
@@ -924,7 +1024,7 @@ class SMB(StorageBase, metaclass=WeakSingleton):
|
||||
# 多个共享可能共用存储池;SMB 的卷序列号也可能按共享生成,不能据此累加。
|
||||
# 沿用单卷用量合同,以配置首项作为容量查询入口,保持卡片和仪表板可用。
|
||||
share = next(iter(self._shares.values()))
|
||||
volume_stat = smbclient.stat_volume(f"\\\\{self._host}\\{share}")
|
||||
volume_stat = self._call_smb(smbclient.stat_volume, f"\\\\{self._host}\\{share}", retry=True)
|
||||
return _SchemaStorageUsage(
|
||||
total=volume_stat.total_size,
|
||||
available=volume_stat.caller_available_size,
|
||||
|
||||
@@ -228,9 +228,13 @@ CloudDrive 的移动后改名失败,验证重新取得租约后仅补改名、
|
||||
- 连接失效保留旧基线;恢复后发现新文件,再次轮询不重复派发。
|
||||
- 真正清空的目录和确认不存在的根路径可以提交空快照。
|
||||
- 完整遍历仍遵守递归深度上限,不因本次修复增加扫描频率。
|
||||
- 断线、会话丢失、SDK 超时和 credits 耗尽时,查询清理当前主机的缓存会话并重试一次;
|
||||
重连失败后退避 30 秒,并发查询共用一次重连,旧代请求的迟到异常不清除新会话。
|
||||
- 移动、复制和删除请求中途失败不自动重放;严格查询仍区分缺失、权限和连接错误。
|
||||
- 真实 `smbclient` 缓存注册与删除逻辑确认旧连接确实被替换,关闭失效连接报错也能恢复。
|
||||
|
||||
这些场景只承诺已验证的 SMB 查询语义;为其他存储接入严格快照时,应在其 SDK/API
|
||||
边界复现同样的状态转换,并评估目录时间语义、分页和请求成本。
|
||||
这些场景使用离线 SDK 边界,不代表真实 SMB 服务器断线验收。为其他存储接入严格快照时,
|
||||
应在其 SDK/API 边界复现同样的状态转换,并评估目录时间语义、分页和请求成本。
|
||||
|
||||
`tests/modules/filemanager/test_u115_storage.py` 在 115 API 边界验证目录时间不推进时的深层新增、修改、
|
||||
保留旧时间的文件移入和删除,兼容空基线,并覆盖千条分页、递归深度和重复派发。
|
||||
|
||||
@@ -127,8 +127,10 @@ FROZEN_EGRESS_FINGERPRINT_BY_EDGE = {
|
||||
("app.modules.discord.discord", "discord"): "2761ef9a9e5a805bfb20ea832c5d34edea12db21ca3eb27c3db7ce512a5ee7f5",
|
||||
("app.modules.emby.emby", "requests"): "6c4c17fe170226ea1272f5859bc119c2775442cabe8ce2a9edcabaf9c37bec31",
|
||||
("app.adapters.network.feishu", "websocket"): "95aca65eed288e0c7654ab49aad6c535d9313d5e38c44b1cb1768dcdfc772453",
|
||||
("app.modules.filemanager.storages.smb", "smbclient"): "bfc6993d05d5d33dfcb8044fda6c89a3cc3c599fecb0fe327cefd9e1f9145092",
|
||||
("app.modules.filemanager.storages.smb", "smbprotocol"): "f02686afd99c59820dffa7b4c2627a0be1ad62980c98a9cd33b7564697842b22",
|
||||
# SMB 原有读写经同一 owner 的故障包装器调用;新增 delete_session 仅移除失效主机缓存。
|
||||
# smbprotocol 新绑定只识别断线异常和状态码,没有新增外连调用方或传输库。
|
||||
("app.modules.filemanager.storages.smb", "smbclient"): "9b4df1be8c63c2c8ece658f5c5ebe65f3f7e28fc1c1e926abd790cb81ea95d42",
|
||||
("app.modules.filemanager.storages.smb", "smbprotocol"): "f1c9ba18714734a3287d273ecacc9777fdd1d8f5918e95b5003e3a84a518ed6f",
|
||||
("app.modules.filemanager.storages.u115", "oss2"): "f7b89c8ae6dad2603f0a9e0caaa159769aef5b3581d7e728f62445b979366eae",
|
||||
("app.modules.jellyfin.jellyfin", "requests"): "5c46d09ca9a4bcc0bae21ca5d554ef09baa3f901c562b27c5f5ee1439c7746b5",
|
||||
# 补充现有 SDK 返回类型导入;未增加客户端或请求路径。
|
||||
|
||||
@@ -559,62 +559,33 @@
|
||||
{
|
||||
"bindings": [
|
||||
"from:smbclient.ClientConfig as ClientConfig",
|
||||
"from:smbclient.delete_session as delete_session",
|
||||
"from:smbclient.register_session as register_session",
|
||||
"from:smbclient.reset_connection_cache as reset_connection_cache",
|
||||
"import:smbclient as smbclient"
|
||||
],
|
||||
"fingerprint": "bfc6993d05d5d33dfcb8044fda6c89a3cc3c599fecb0fe327cefd9e1f9145092",
|
||||
"fingerprint": "9b4df1be8c63c2c8ece658f5c5ebe65f3f7e28fc1c1e926abd790cb81ea95d42",
|
||||
"kind": "network_sdk",
|
||||
"source": "app.modules.filemanager.storages.smb",
|
||||
"target": "smbclient",
|
||||
"uses": [
|
||||
"SMB.__del__|call:reset_connection_cache",
|
||||
"SMB._create_fileitem|call:path.isdir",
|
||||
"SMB._check_connection|call:delete_session",
|
||||
"SMB._init_connection|call:ClientConfig",
|
||||
"SMB._init_connection|call:register_session",
|
||||
"SMB._move_between_shares|call:remove",
|
||||
"SMB._move_between_shares|call:stat",
|
||||
"SMB._recursive_delete|call:listdir",
|
||||
"SMB._recursive_delete|call:path.exists",
|
||||
"SMB._recursive_delete|call:path.isdir",
|
||||
"SMB._recursive_delete|call:path.isfile",
|
||||
"SMB._recursive_delete|call:remove",
|
||||
"SMB._recursive_delete|call:remove",
|
||||
"SMB._recursive_delete|call:rmdir",
|
||||
"SMB._test_connection|call:listdir",
|
||||
"SMB.copy|call:copyfile",
|
||||
"SMB.copy|call:path.samefile",
|
||||
"SMB.create_folder|call:mkdir",
|
||||
"SMB.delete|call:path.exists",
|
||||
"SMB.delete|call:remove",
|
||||
"SMB.download|call:open_file",
|
||||
"SMB.download|call:read",
|
||||
"SMB.get_item_strict|call:stat",
|
||||
"SMB.get_item|call:path.exists",
|
||||
"SMB.get_item|call:stat",
|
||||
"SMB.init_storage|call:reset_connection_cache",
|
||||
"SMB.link|call:link",
|
||||
"SMB.link|call:makedirs",
|
||||
"SMB.link|call:path.exists",
|
||||
"SMB.link|call:path.exists",
|
||||
"SMB.list|call:listdir",
|
||||
"SMB.list|call:stat",
|
||||
"SMB.move|call:rename",
|
||||
"SMB.open_file_stream|call:open_file",
|
||||
"SMB.open_file_stream|call:stat",
|
||||
"SMB.rename|call:rename",
|
||||
"SMB.upload|call:open_file",
|
||||
"SMB.upload|call:write",
|
||||
"SMB.usage|call:stat_volume"
|
||||
"SMB.init_storage|call:reset_connection_cache"
|
||||
]
|
||||
},
|
||||
{
|
||||
"bindings": [
|
||||
"from:smbprotocol.exceptions.SMBAuthenticationError as SMBAuthenticationError",
|
||||
"from:smbprotocol.exceptions.SMBConnectionClosed as SMBConnectionClosed",
|
||||
"from:smbprotocol.exceptions.SMBException as SMBException",
|
||||
"from:smbprotocol.exceptions.SMBResponseException as SMBResponseException"
|
||||
"from:smbprotocol.exceptions.SMBResponseException as SMBResponseException",
|
||||
"from:smbprotocol.header.NtStatus as NtStatus"
|
||||
],
|
||||
"fingerprint": "f02686afd99c59820dffa7b4c2627a0be1ad62980c98a9cd33b7564697842b22",
|
||||
"fingerprint": "f1c9ba18714734a3287d273ecacc9777fdd1d8f5918e95b5003e3a84a518ed6f",
|
||||
"kind": "network_sdk",
|
||||
"source": "app.modules.filemanager.storages.smb",
|
||||
"target": "smbprotocol",
|
||||
|
||||
@@ -139,7 +139,7 @@
|
||||
{"source": "app.agent.llm.discovery", "target": "openai", "kind": "network_sdk", "fingerprint": "fff154461ff3fdfdf1daea0530dcb68589d6ad7a67f3966e3b86338b483e6dfd"},
|
||||
{"source": "app.agent.tools.impl.search_web", "target": "ddgs", "kind": "network_sdk", "fingerprint": "377e73bb3be804b825d60ad6e792344ca633de107f8c4dbb45d50a34a4dfa04b"},
|
||||
{"source": "app.modules.discord.discord", "target": "discord", "kind": "network_sdk", "fingerprint": "2761ef9a9e5a805bfb20ea832c5d34edea12db21ca3eb27c3db7ce512a5ee7f5"},
|
||||
{"source": "app.modules.filemanager.storages.smb", "target": "smbclient", "kind": "network_sdk", "fingerprint": "bfc6993d05d5d33dfcb8044fda6c89a3cc3c599fecb0fe327cefd9e1f9145092"},
|
||||
{"source": "app.modules.filemanager.storages.smb", "target": "smbclient", "kind": "network_sdk", "fingerprint": "9b4df1be8c63c2c8ece658f5c5ebe65f3f7e28fc1c1e926abd790cb81ea95d42"},
|
||||
{"source": "app.modules.filemanager.storages.u115", "target": "oss2", "kind": "network_sdk", "fingerprint": "f7b89c8ae6dad2603f0a9e0caaa159769aef5b3581d7e728f62445b979366eae"},
|
||||
{"source": "app.modules.plex.plex", "target": "plexapi", "kind": "network_sdk", "fingerprint": "27343fdd0761e0be7090b4dbf3b2f39cab07116f5c9435d2e2454e5f4af7a976"},
|
||||
{"source": "app.modules.qbittorrent.qbittorrent", "target": "qbittorrentapi", "kind": "network_sdk", "fingerprint": "b2f5a27f0c54cf95ed42fe99848fd6c9c0641caca8bc4ff8006a411cb427066d"},
|
||||
@@ -202,7 +202,7 @@
|
||||
{"source": "app.adapters.external.plugin.client", "target": "httpx2", "kind": "raw_transport", "fingerprint": "2d249b0906bc7f8fa29f569d6bcc5667d4290a551b1a06bcdf85e09ec50a793d"},
|
||||
{"source": "app.adapters.external.plugin.client", "target": "requests", "kind": "raw_transport", "fingerprint": "b5239e7eee9c23569b7fec66791e56bcc226db86a8d09ee7fc58d3ba8bc14f09"},
|
||||
{"source": "app.modules.emby.emby", "target": "requests", "kind": "raw_transport", "fingerprint": "6c4c17fe170226ea1272f5859bc119c2775442cabe8ce2a9edcabaf9c37bec31"},
|
||||
{"source": "app.modules.filemanager.storages.smb", "target": "smbprotocol", "kind": "network_sdk", "fingerprint": "f02686afd99c59820dffa7b4c2627a0be1ad62980c98a9cd33b7564697842b22"},
|
||||
{"source": "app.modules.filemanager.storages.smb", "target": "smbprotocol", "kind": "network_sdk", "fingerprint": "f1c9ba18714734a3287d273ecacc9777fdd1d8f5918e95b5003e3a84a518ed6f"},
|
||||
{"source": "app.modules.jellyfin.jellyfin", "target": "requests", "kind": "raw_transport", "fingerprint": "5c46d09ca9a4bcc0bae21ca5d554ef09baa3f901c562b27c5f5ee1439c7746b5"},
|
||||
{"source": "app.modules.plex.plex", "target": "requests", "kind": "raw_transport", "fingerprint": "e49c0856fd6c99a3409850898aac7e6e3fa611d4e91546634c178fbfd244e8da"},
|
||||
{"source": "app.modules.rtorrent.rtorrent", "target": "http.client", "kind": "raw_transport", "fingerprint": "6adc93b3bc479dfe81197554c7977930a60abc51714f14ef29298eb40730aaf7"},
|
||||
|
||||
@@ -3,12 +3,16 @@ SMB 保存重连、服务端整理与远程快照恢复的回归测试。
|
||||
"""
|
||||
|
||||
import errno
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
import smbclient
|
||||
from smbclient import _pool as smb_pool
|
||||
from smbprotocol.exceptions import SMBConnectionClosed, SMBException, SMBOSError
|
||||
from smbprotocol.header import NtStatus
|
||||
|
||||
from app.application.storage import StorageHelper
|
||||
from app.modules.filemanager.module import FileManagerModule
|
||||
@@ -27,7 +31,7 @@ def smb_storage(monkeypatch):
|
||||
state = {"conf": {}}
|
||||
client = Mock()
|
||||
client.listdir.return_value = []
|
||||
for name in ("ClientConfig", "register_session", "listdir", "reset_connection_cache"):
|
||||
for name in ("ClientConfig", "register_session", "listdir", "reset_connection_cache", "delete_session"):
|
||||
monkeypatch.setattr(smbclient, name, getattr(client, name))
|
||||
|
||||
def get_conf(_self):
|
||||
@@ -104,6 +108,230 @@ def test_save_incomplete_config_clears_previous_connection(smb_storage, conf):
|
||||
smb_storage.storage._check_connection()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def connected_smb(smb_storage, monkeypatch):
|
||||
"""
|
||||
建立可用共享并提供确定性的退避时钟,所有 SMB 请求均被拦截。
|
||||
"""
|
||||
smb_storage.state["conf"] = {"host": "smb.example", "share": "video", "port": 1445}
|
||||
smb_storage.storage.init_storage()
|
||||
smb_storage.client.reset_mock()
|
||||
monkeypatch.setattr(smbclient.path, "isdir", Mock(return_value=False))
|
||||
clock = Mock(return_value=100.0)
|
||||
monkeypatch.setattr(smb_module.time, "monotonic", clock)
|
||||
smb_storage.clock = clock
|
||||
return smb_storage
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", [
|
||||
SMBException("Request requires 1 credits but only 0 credits are available"),
|
||||
SMBConnectionClosed("socket closed"),
|
||||
ConnectionResetError(errno.ECONNRESET, "reset"),
|
||||
TimeoutError("timed out"),
|
||||
SMBException("Connection timeout of 60 seconds exceeded while waiting for a message id 1 response from the server"),
|
||||
OSError(errno.EHOSTUNREACH, "unreachable"),
|
||||
SMBOSError(NtStatus.STATUS_USER_SESSION_DELETED, "file"),
|
||||
SMBOSError(NtStatus.STATUS_NETWORK_NAME_DELETED, "file"),
|
||||
SMBOSError(NtStatus.STATUS_IO_TIMEOUT, "file"),
|
||||
])
|
||||
def test_strict_query_replaces_stale_session_and_retries_once(connected_smb, monkeypatch, failure):
|
||||
"""
|
||||
真实查询入口遇到断线、会话丢失或 credits 耗尽后自动恢复,无需保存配置。
|
||||
"""
|
||||
state = connected_smb
|
||||
stat = Mock(side_effect=[failure, SimpleNamespace(st_size=1024, st_mtime=1)])
|
||||
monkeypatch.setattr(smbclient, "stat", stat)
|
||||
|
||||
item = state.storage.get_item_strict(Path("/movie.mkv"))
|
||||
|
||||
assert item.path == "/movie.mkv"
|
||||
assert item.size == 1024
|
||||
assert stat.call_count == 2
|
||||
state.client.delete_session.assert_called_once_with("smb.example", port=1445, timeout=5)
|
||||
state.client.register_session.assert_called_once()
|
||||
state.client.reset_connection_cache.assert_not_called()
|
||||
assert state.storage._connected is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error_number", [errno.EACCES, errno.ENOENT, errno.ENOTDIR, errno.ENOSPC])
|
||||
def test_query_business_errors_do_not_reset_session(connected_smb, monkeypatch, error_number):
|
||||
"""
|
||||
路径缺失、权限与空间错误保留原有语义,不通过重连掩盖。
|
||||
"""
|
||||
stat = Mock(side_effect=OSError(error_number, "query failed"))
|
||||
monkeypatch.setattr(smbclient, "stat", stat)
|
||||
if error_number in (errno.ENOENT, errno.ENOTDIR):
|
||||
assert connected_smb.storage.get_item_strict(Path("/movie.mkv")) is None
|
||||
else:
|
||||
with pytest.raises(smb_module.StorageQueryError):
|
||||
connected_smb.storage.get_item_strict(Path("/movie.mkv"))
|
||||
stat.assert_called_once()
|
||||
connected_smb.client.delete_session.assert_not_called()
|
||||
connected_smb.client.register_session.assert_not_called()
|
||||
assert connected_smb.storage._connected is True
|
||||
|
||||
|
||||
def test_health_check_recovers_after_session_expires(connected_smb):
|
||||
"""
|
||||
连通性巡检也能丢弃失效会话并恢复,不会永久锁在未连接状态。
|
||||
"""
|
||||
state = connected_smb
|
||||
state.client.listdir.side_effect = [SMBConnectionClosed("closed"), [], []]
|
||||
|
||||
assert state.storage.check() is True
|
||||
state.client.delete_session.assert_called_once()
|
||||
state.client.register_session.assert_called_once()
|
||||
|
||||
|
||||
def test_failed_reconnect_is_bounded_and_recovers_after_cooldown(connected_smb, monkeypatch):
|
||||
"""
|
||||
服务未恢复时每个退避窗口只重连一次,后续查询仍严格失败且下一窗口可恢复。
|
||||
"""
|
||||
state = connected_smb
|
||||
stat = Mock(side_effect=SMBConnectionClosed("closed"))
|
||||
monkeypatch.setattr(smbclient, "stat", stat)
|
||||
state.client.register_session.side_effect = OSError(errno.ECONNREFUSED, "offline")
|
||||
|
||||
for _ in range(5):
|
||||
with pytest.raises(smb_module.StorageQueryError):
|
||||
state.storage.get_item_strict(Path("/movie.mkv"))
|
||||
state.client.register_session.assert_called_once()
|
||||
stat.assert_called_once()
|
||||
assert state.storage.list(FileItem(storage="smb", type="dir", path="/")) == []
|
||||
|
||||
state.clock.return_value += state.storage.reconnect_interval
|
||||
state.client.register_session.side_effect = None
|
||||
stat.side_effect = None
|
||||
stat.return_value = SimpleNamespace(st_size=1024, st_mtime=1)
|
||||
assert state.storage.get_item_strict(Path("/movie.mkv")).size == 1024
|
||||
assert state.client.register_session.call_count == 2
|
||||
|
||||
|
||||
def test_repeated_query_fault_stops_after_one_retry(connected_smb, monkeypatch):
|
||||
"""
|
||||
新会话查询仍失败时最多请求两次,并对后续文件启用退避。
|
||||
"""
|
||||
state = connected_smb
|
||||
stat = Mock(side_effect=SMBException("Request requires 1 credits but only 0 credits are available"))
|
||||
monkeypatch.setattr(smbclient, "stat", stat)
|
||||
for _ in range(3):
|
||||
with pytest.raises(smb_module.StorageQueryError):
|
||||
state.storage.get_item_strict(Path("/movie.mkv"))
|
||||
assert stat.call_count == 2
|
||||
state.client.register_session.assert_called_once()
|
||||
assert state.storage._connected is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode, command", [("move", "rename"), ("copy", "copyfile"), ("delete", "remove")])
|
||||
def test_write_failure_is_not_replayed_and_later_operation_recovers(connected_smb, monkeypatch, mode, command):
|
||||
"""
|
||||
写请求中途失效只报告失败,退避后后续操作恢复,不重放结果不明的副作用。
|
||||
"""
|
||||
state = connected_smb
|
||||
operation = Mock(side_effect=SMBConnectionClosed("response lost"))
|
||||
monkeypatch.setattr(smbclient, command, operation)
|
||||
monkeypatch.setattr(smbclient.path, "exists", Mock(return_value=True))
|
||||
monkeypatch.setattr(smbclient.path, "samefile", Mock(return_value=False))
|
||||
source = FileItem(storage="smb", type="file", path="/source.mkv")
|
||||
arguments = (source,) if mode == "delete" else (source, Path("/media"), "target.mkv")
|
||||
|
||||
assert getattr(state.storage, mode)(*arguments) is False
|
||||
operation.assert_called_once()
|
||||
state.client.register_session.assert_not_called()
|
||||
|
||||
state.clock.return_value += state.storage.reconnect_interval
|
||||
operation.side_effect = None
|
||||
assert getattr(state.storage, mode)(*arguments) is True
|
||||
assert operation.call_count == 2
|
||||
state.client.register_session.assert_called_once()
|
||||
|
||||
|
||||
def test_parallel_queries_share_one_reconnect(connected_smb, monkeypatch):
|
||||
"""
|
||||
多个真实查询同时看到未连接状态时只建立一个新会话。
|
||||
"""
|
||||
state = connected_smb
|
||||
state.storage._connected = False
|
||||
start = threading.Barrier(5)
|
||||
monkeypatch.setattr(smbclient, "stat", Mock(return_value=SimpleNamespace(st_size=1, st_mtime=1)))
|
||||
results = []
|
||||
|
||||
def query():
|
||||
"""
|
||||
在屏障释放后进入真实存储查询,收集成功或失败结果。
|
||||
"""
|
||||
start.wait(timeout=10)
|
||||
results.append(state.storage.get_item_strict(Path("/movie.mkv")))
|
||||
|
||||
threads = [threading.Thread(target=query) for _ in range(4)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
try:
|
||||
start.wait(timeout=10)
|
||||
finally:
|
||||
for thread in threads:
|
||||
thread.join(timeout=10)
|
||||
assert all(not thread.is_alive() for thread in threads)
|
||||
assert len(results) == 4
|
||||
assert all(item.size == 1 for item in results)
|
||||
state.client.delete_session.assert_called_once()
|
||||
state.client.register_session.assert_called_once()
|
||||
|
||||
|
||||
def test_old_request_error_cannot_invalidate_replacement_session(connected_smb, monkeypatch):
|
||||
"""
|
||||
旧代查询迟到报错时复用已恢复的新会话,不额外断开它。
|
||||
"""
|
||||
state = connected_smb
|
||||
|
||||
def query(_path):
|
||||
"""
|
||||
在旧请求返回前模拟另一个调用已经替换会话。
|
||||
"""
|
||||
if stat.call_count == 1:
|
||||
state.storage._connected = False
|
||||
state.storage._check_connection()
|
||||
raise SMBConnectionClosed("old connection closed")
|
||||
return SimpleNamespace(st_size=1, st_mtime=1)
|
||||
|
||||
stat = Mock(side_effect=query)
|
||||
monkeypatch.setattr(smbclient, "stat", stat)
|
||||
assert state.storage.get_item_strict(Path("/movie.mkv")).size == 1
|
||||
assert state.storage._connected is True
|
||||
state.client.register_session.assert_called_once()
|
||||
|
||||
|
||||
def test_sdk_cache_replaces_broken_transport_even_when_close_fails(connected_smb, monkeypatch):
|
||||
"""
|
||||
使用真实 SDK 缓存注册与删除逻辑,确认仍标记连接的旧会话确实被替换。
|
||||
"""
|
||||
state = connected_smb
|
||||
old_session = SimpleNamespace(username=None, encrypt_data=False)
|
||||
new_session = SimpleNamespace(username=None, encrypt_data=False)
|
||||
old_connection = Mock(session_table={1: old_session})
|
||||
new_connection = Mock(session_table={2: new_session})
|
||||
old_connection.transport.connected = new_connection.transport.connected = True
|
||||
old_connection.disconnect.side_effect = SMBException(
|
||||
"Request requires 1 credits but only 0 credits are available"
|
||||
)
|
||||
cache = {"smb.example:1445": old_connection}
|
||||
monkeypatch.setattr(smb_pool, "_SMB_CONNECTIONS", cache)
|
||||
monkeypatch.setattr(smb_pool, "Connection", Mock(return_value=new_connection))
|
||||
monkeypatch.setattr(smbclient, "register_session", smb_pool.register_session)
|
||||
monkeypatch.setattr(smbclient, "delete_session", smb_pool.delete_session)
|
||||
monkeypatch.setattr(smbclient, "stat_volume", Mock(side_effect=[
|
||||
SMBConnectionClosed("expired"),
|
||||
SimpleNamespace(total_size=4096, caller_available_size=1024),
|
||||
]))
|
||||
|
||||
assert smb_pool.register_session("smb.example", port=1445) is old_session
|
||||
assert state.storage.usage().available == 1024
|
||||
assert cache["smb.example:1445"] is new_connection
|
||||
old_connection.disconnect.assert_called_once_with(close=True, timeout=5)
|
||||
new_connection.connect.assert_called_once_with(timeout=60)
|
||||
state.client.reset_connection_cache.assert_not_called()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server_transfer(smb_storage, monkeypatch):
|
||||
"""
|
||||
@@ -485,9 +713,15 @@ def snapshot_server(smb_storage, monkeypatch):
|
||||
fault = {"operation": None, "path": None}
|
||||
|
||||
def relative(path):
|
||||
"""
|
||||
将 SDK 的 UNC 路径转换为测试树的存储内键。
|
||||
"""
|
||||
return storage._relative_path(path).rstrip("/")
|
||||
|
||||
def read_node(operation, path):
|
||||
"""
|
||||
按操作和路径注入查询故障,其余节点保持真实缺失语义。
|
||||
"""
|
||||
key = relative(path)
|
||||
if fault == {"operation": operation, "path": key}:
|
||||
raise OSError(errno.EIO, "temporary SMB read failure")
|
||||
@@ -496,14 +730,23 @@ def snapshot_server(smb_storage, monkeypatch):
|
||||
return key, tree[key]
|
||||
|
||||
def list_directory(path):
|
||||
"""
|
||||
列出测试树中的直接子项,不递归展开后代。
|
||||
"""
|
||||
key, _node = read_node("list", path)
|
||||
return [Path(item).name for item in tree if Path(item).parent.as_posix() == key]
|
||||
|
||||
def stat_item(path):
|
||||
"""
|
||||
将节点大小和修改时间投影为 SDK 元数据。
|
||||
"""
|
||||
_key, node = read_node("stat", path)
|
||||
return SimpleNamespace(st_mtime=node["mtime"], st_size=node.get("size", 0))
|
||||
|
||||
def is_directory(path):
|
||||
"""
|
||||
返回节点类型,保留独立类型查询的故障注入。
|
||||
"""
|
||||
_key, node = read_node("type", path)
|
||||
return node["directory"]
|
||||
|
||||
@@ -586,6 +829,7 @@ def test_disconnected_snapshot_preserves_failure_semantics(snapshot_server):
|
||||
"""
|
||||
state = snapshot_server
|
||||
state.storage._connected = False
|
||||
state.client.listdir.side_effect = SMBConnectionClosed("server remains offline")
|
||||
|
||||
assert state.module.snapshot_storage("smb", state.root) is None
|
||||
assert state.storage.list(FileItem(storage="smb", type="dir", path="/downloads")) == []
|
||||
|
||||
Reference in New Issue
Block a user