Compare commits

...
2 Commits
5 changed files with 141 additions and 68 deletions

No files matched your search

+42 -4
View File
@@ -488,9 +488,47 @@ namespace MusicDownloader.Class
}
}
/// <summary>
/// 例外がストレージ障害(Google Drive切断、WSL2マウント切れ、読み取り専用化、I/Oエラーなど)に起因するか判定する
/// </summary>
public static bool IsStorageFailureException(Exception? ex)
{
if (ex == null) return false;
var msg = ex.ToString();
// Linux/WSL2/DrvFs/Docker でマウント先が切断・無効になった際のエラーメッセージ・条件
if (msg.Contains("Invalid argument", StringComparison.OrdinalIgnoreCase) || // errno 22: EINVAL (マウント切断・ジャンクション破損時に発生)
msg.Contains("Read-only", StringComparison.OrdinalIgnoreCase) || // EROFS
msg.Contains("Input/output error", StringComparison.OrdinalIgnoreCase) || // errno 5: EIO
msg.Contains("Transport endpoint is not connected", StringComparison.OrdinalIgnoreCase) || // errno 107: ENOTCONN
msg.Contains("Stale file handle", StringComparison.OrdinalIgnoreCase) || // errno 116: ESTALE
msg.Contains("No such device", StringComparison.OrdinalIgnoreCase) || // ENODEV
msg.Contains("Host is down", StringComparison.OrdinalIgnoreCase) || // EHOSTDOWN
msg.Contains("Network is down", StringComparison.OrdinalIgnoreCase) || // ENETDOWN
msg.Contains("Connection reset", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("Device not configured", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (ex is DriveNotFoundException || ex is DirectoryNotFoundException)
{
return true;
}
// 内部例外も再帰的に確認
if (ex.InnerException != null && IsStorageFailureException(ex.InnerException))
{
return true;
}
return false;
}
/// <summary>
/// 指定されたストレージディレクトリへの書き込みが可能か(読み取り専用や切断になっていないか)を検証する。
/// Google Drive や WSL2 DrvFs マウント切断時に発生する Read-only file system を早期検知する。
/// Google Drive や WSL2 DrvFs マウント切断時に発生する Read-only / Invalid argument などの障害を早期検知する。
/// </summary>
/// <param name="dirPath">検証対象ディレクトリパス</param>
/// <param name="maxRetries">リトライ回数(既定3回)</param>
@@ -516,7 +554,7 @@ namespace MusicDownloader.Class
}
catch (Exception ex)
{
bool isReadOnly = ex.Message.Contains("Read-only", StringComparison.OrdinalIgnoreCase);
bool isStorageFail = IsStorageFailureException(ex);
if (attempt < maxRetries)
{
LogManager.AddWarning($"[ストレージ疎通確認] ディレクトリ書き込みテストに失敗しました (試行 {attempt}/{maxRetries}): {dirPath} - {ex.Message}。{retryDelayMs / 1000}秒後に再試行します...");
@@ -524,9 +562,9 @@ namespace MusicDownloader.Class
}
else
{
if (isReadOnly)
if (isStorageFail)
{
LogManager.AddError($"[ストレージ疎通異常] 出力先が読み取り専用 (Read-only) になっています: {dirPath} - Google Drive (G:) のマウント切断またはリンク切れの可能性があります。", ex);
LogManager.AddError($"[ストレージ疎通異常] 出力先ストレージが切断・無効化または読み取り専用になっています: {dirPath} - Google Drive (G:) のマウント切断またはリンク切れの可能性があります ({ex.Message})。", ex);
}
else
{
@@ -541,12 +541,20 @@ namespace MusicDownloader.Class.Downloader
var sanitizedBaseName = CmnUtil.SanitizeFileName(rawBaseName);
var cleanFileName = $"{sanitizedBaseName}{ext}";
// 保存先へのファイル転送を安全に試行(Google Drive切断・マウント一時切れ時の自動待機&リトライ付き)
bool transferSuccess = false;
string targetFinalFileName = cleanFileName;
const int maxTransferRetries = 6; // 15秒 x 6回 = 最大90秒間待機
const int transferRetryDelayMs = 15000;
for (int attempt = 1; attempt <= maxTransferRetries; attempt++)
{
try
{
// ① 同名別動画(another vocal等)の衝突を検知し、ユニークな保存名(曲名 (2).opus等)を決定
var finalFileName = GetUniqueTargetFileName(youtubeFolder, cleanFileName, videoId, downloadedTracks);
var destOpusPath = Path.Combine(youtubeFolder, finalFileName);
try
{
File.Copy(targetOpus, destOpusPath, overwrite: true);
LogManager.AddLog($"ファイルを保存先に配置しました: {finalFileName}");
@@ -561,23 +569,54 @@ namespace MusicDownloader.Class.Downloader
// ダウンロード完了履歴 (archive.txt) に動画IDを記録
AddToArchiveFile(archiveFile, videoId);
transferSuccess = true;
targetFinalFileName = finalFileName;
break;
}
catch (Exception ex)
{
LogManager.AddError($"保存先へのファイル転送に失敗しました: {ex.Message}", ex);
}
finally
bool isStorageFail = CmnUtil.IsStorageFailureException(ex);
if (isStorageFail)
{
// 作業フォルダ内の完成ファイルを掃除
CleanupDirectory(stagingDir);
LogManager.AddWarning($"[保存先転送待機] Google Drive/ストレージ切断を検知しました (試行 {attempt}/{maxTransferRetries}): {ex.Message}。{transferRetryDelayMs / 1000}秒後に再試行します...");
if (attempt < maxTransferRetries)
{
await Task.Delay(transferRetryDelayMs);
continue;
}
else
{
LogManager.AddError($"[ストレージ切断エラー] Google Driveへのファイル転送が復旧しませんでした ({attempt}回試行): {ex.Message}", ex);
// 致命的ストレージ切断例外を上位にスローして後続曲の誤完了・破棄ループを即座に停止
throw new IOException($"Google Driveストレージ切断のため処理を安全に中断します: {ex.Message}", ex);
}
}
else
{
// 通常のエラー(権限不足や特定ファイル名不整合等)
LogManager.AddError($"保存先へのファイル転送に失敗しました: {ex.Message}", ex);
break;
}
}
}
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {finalFileName}");
// 転送が失敗した場合は、絶対に成功扱いせず作業フォルダを掃除して処理を中断
if (!transferSuccess)
{
RemoveFromArchiveFile(archiveFile, videoId);
CleanupDirectory(stagingDir);
return null;
}
// 転送成功時のみ作業フォルダを掃除し、完了ログを出力
CleanupDirectory(stagingDir);
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {targetFinalFileName}");
return new DownloadedTrackInfo
{
VideoId = videoId,
FileName = finalFileName,
FileName = targetFinalFileName,
Title = finalTitle,
Artist = finalArtist,
Duration = entryInfo?.Duration,
@@ -1072,6 +1111,11 @@ namespace MusicDownloader.Class.Downloader
catch (Exception ex)
{
LogManager.AddWarning($"downloaded_tracks.json の保存に失敗しました: {ex.Message}");
if (CmnUtil.IsStorageFailureException(ex))
{
// ストレージ切断時は上位へスローしてプロセス終了・自己復旧へ促す
throw new IOException($"downloaded_tracks.json 保存中にストレージ切断を検知しました: {ex.Message}", ex);
}
}
}
+4 -3
View File
@@ -284,10 +284,11 @@ while (true)
{
LogManager.AddError($"プレイリスト処理中にエラーが発生しました: {ex.Message}", ex);
// ストレージ切断や読み取り専用 (Read-only) が発生した場合はループを継続せずプロセスを終了し、コンテナの自動再起動に委ねる
if (ex.ToString().Contains("Read-only", StringComparison.OrdinalIgnoreCase))
// ストレージ切断(Invalid argument, Read-only, I/O error 等)が発生した場合はループを継続せずプロセスを終了し、コンテナの自動再起動に委ねる
if (CmnUtil.IsStorageFailureException(ex))
{
LogManager.AddError($"ストレージの読み取り専用化 (Read-only) を検知しました。残りのプレイリスト処理を中止し、コンテナ自動再起動による自己復旧のためプロセスを終了します。");
LogManager.AddError($"[ストレージ障害検知] 出力先ストレージ(Google Drive / WSL2マウント)の切断または障害を検知しました: {ex.Message}");
LogManager.AddError($"残りのプレイリスト処理を安全に中断し、コンテナ自動再起動による自己復旧のためプロセスを終了します。");
Environment.Exit(1);
}
}
+31 -42
View File
@@ -1,6 +1,7 @@
# ==============================================================================
# Google Drive (G:) WSL2 Auto-Mount & MusicDownloader Recovery Script
# Runs automatically on Windows logon to ensure G: drive is mounted into WSL2.
# ==============================================================================
# Google Drive (G:) WSL2 Auto-Mount & MusicDownloader Health Check Script
# Periodically monitors Google Drive mount status and automatically repairs
# broken mounts or stale containers.
# ==============================================================================
$logDir = "C:\feeds\Log"
@@ -16,55 +17,43 @@ function Write-Log($msg) {
Add-Content -Path $logFile -Value $line -Encoding UTF8
}
Write-Log "=========================================================="
Write-Log "Start Google Drive Auto-Mount and MusicDownloader Health Check"
Write-Log "=========================================================="
# 1. Wait for Google Drive (max 180s)
# C:\MyMusic is a junction pointing to G:\マイドライブ\MyMusic
$maxWaitSeconds = 180
$waited = 0
Write-Log "Waiting for Google Drive (C:\MyMusic\playlists.txt)..."
while (!(Test-Path "C:\MyMusic\playlists.txt") -and ($waited -lt $maxWaitSeconds)) {
Start-Sleep -Seconds 3
$waited += 3
# 1. ホスト側 Google Drive (G:) のアクセス健全性確認
if (!(Test-Path "G:\マイドライブ\MyMusic") -or !(Test-Path "C:\MyMusic")) {
# ホスト側で Google Drive が起動していない場合は何もしない
exit 0
}
if (!(Test-Path "C:\MyMusic\playlists.txt")) {
Write-Log "[Warning] Google Drive target (C:\MyMusic\playlists.txt) not accessible within $maxWaitSeconds seconds."
exit 1
# 2. WSL2 (docker-desktop) 上の Google Drive マウント健全性確認
$wslCheckCmd = "ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&1"
$null = wsl -d docker-desktop sh -c $wslCheckCmd 2>&1
$isWslMountBroken = ($LASTEXITCODE -ne 0)
if ($isWslMountBroken) {
Write-Log "[異常検知] WSL2 の Google Drive マウント切断 (Invalid argument 等) を検知しました。マウントを修復します..."
$remountCmd = "while umount -l /tmp/docker-desktop-root/run/desktop/mnt/host/g 2>/dev/null; do :; done; while umount -l /tmp/docker-desktop-root/mnt/host/g 2>/dev/null; do :; done; while umount -l /mnt/host/g 2>/dev/null; do :; done; mkdir -p /mnt/host/g && mount -t drvfs G: /mnt/host/g && mkdir -p /tmp/docker-desktop-root/run/desktop/mnt/host/g /tmp/docker-desktop-root/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/run/desktop/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/mnt/host/g && (ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&1 && echo 'MOUNT_OK' || echo 'MOUNT_NG')"
$remountResult = wsl -d docker-desktop sh -c $remountCmd 2>&1
Write-Log "WSL2 再マウント結果: $remountResult"
}
Write-Log "[OK] Google Drive detected and accessible via junction (waited: ${waited}s)"
# 2. Update WSL2 mounts
Write-Log "Updating WSL2 mounts for G: drive..."
$shCmd = "while umount -l /tmp/docker-desktop-root/run/desktop/mnt/host/g 2>/dev/null; do :; done; while umount -l /tmp/docker-desktop-root/mnt/host/g 2>/dev/null; do :; done; while umount -l /mnt/host/g 2>/dev/null; do :; done; mkdir -p /mnt/host/g && mount -t drvfs G: /mnt/host/g && mkdir -p /tmp/docker-desktop-root/run/desktop/mnt/host/g /tmp/docker-desktop-root/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/run/desktop/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/mnt/host/g && (ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&1 && echo 'MOUNT_OK' || echo 'MOUNT_NG')"
$mountResult = wsl -d docker-desktop sh -c $shCmd
Write-Log "WSL2 Mount Result: $mountResult"
# 3. Check and recover MusicDownloader container
# 3. MusicDownloader コンテナの健全性確認および復旧
try {
$containerStatus = docker inspect MusicDownloader --format "{{.State.Status}}" 2>&1
if ($containerStatus -eq "running") {
$mountCheck = docker exec MusicDownloader sh -c "mount | grep 'on /music'" 2>&1
Write-Log "Container mount status: $mountCheck"
# コンテナ内部からのマウントアクセス確認
$null = docker exec MusicDownloader ls -d /music/Youtube 2>&1
$isContainerMountBroken = ($LASTEXITCODE -ne 0)
$isReadOnly = ($mountCheck -match '\b(ro)\b') -or ($mountCheck -like "*overlay*") -or ($mountCheck -notlike "*G:*")
if ($isReadOnly) {
Write-Log "[Notice] Container mount is Read-only or stale. Restarting MusicDownloader..."
if ($isWslMountBroken -or $isContainerMountBroken) {
Write-Log "[コンテナ修復] コンテナ内のマウント無効化を検知しました。MusicDownloader を再起動します..."
docker restart MusicDownloader | Out-Null
Write-Log "[Success] MusicDownloader container restarted."
} else {
Write-Log "[OK] MusicDownloader container is running with healthy mount (rw)."
Write-Log "[成功] MusicDownloader コンテナを再起動しました。"
}
} else {
Write-Log "Container status: $containerStatus. Starting container..."
docker start MusicDownloader 2>&1 | Out-Null
} elseif ($containerStatus -eq "exited" -or $containerStatus -eq "created") {
Write-Log "コンテナが停止しています (Status: $containerStatus)。MusicDownloader を起動します..."
docker start MusicDownloader | Out-Null
Write-Log "[成功] MusicDownloader コンテナを起動しました。"
}
} catch {
Write-Log "[Error] Exception occurred while inspecting container: $_"
Write-Log "[エラー] コンテナ確認中に例外が発生しました: $_"
}
Write-Log "Auto-mount process completed successfully."
+11 -10
View File
@@ -1,4 +1,4 @@
# ==============================================================================
# ==============================================================================
# Setup Startup Task and Shortcut for MusicDownloader Auto-Mount
# ==============================================================================
@@ -6,23 +6,24 @@ $scriptDir = "C:\VS2026\MusicDownloader"
$vbsPath = Join-Path $scriptDir "run-auto-mount-silent.vbs"
$ps1Path = Join-Path $scriptDir "auto-mount-gdrive.ps1"
# 1. Register to Startup Folder
# 1. Register to Startup Folder (PC起動時・ログオン時の即座実行用)
$startupFolder = [Environment]::GetFolderPath([Environment+SpecialFolder]::Startup)
$startupVbs = Join-Path $startupFolder "MusicDownloader-AutoMount.vbs"
Copy-Item -Path $vbsPath -Destination $startupVbs -Force
Write-Host "[OK] Startup folder configured: $startupVbs"
# 2. Register to Windows Task Scheduler (At Logon)
# 2. Register to Windows Task Scheduler (5分ごとの定期ヘルスチェック&自動復旧用)
$taskName = "MusicDownloader-AutoMount"
$action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$vbsPath`""
$trigger = New-ScheduledTaskTrigger -AtLogOn
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
$taskCmd = "wscript.exe $vbsPath"
try {
# 既存タスクがあれば上書き登録
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description "Auto-mounts Google Drive (G:) to WSL2 and recovers MusicDownloader container on logon" | Out-Null
Write-Host "[OK] Task Scheduler configured: $taskName"
# schtasks を用いて一般ユーザー権限でも登録可能な5分毎タスクを作成
& schtasks /create /tn $taskName /tr $taskCmd /sc minute /mo 5 /f | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Host "[OK] Task Scheduler configured (every 5 mins): $taskName"
} else {
Write-Warning "[Warning] schtasks failed with exit code: $LASTEXITCODE"
}
} catch {
Write-Warning "[Warning] Failed to register ScheduledTask: $_"
}