From 6bc2d065e40033cc1a28a68a8426798fd62ec938 Mon Sep 17 00:00:00 2001 From: uduki Date: Wed, 16 Sep 2026 08:19:04 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20PC=E5=86=8D=E8=B5=B7=E5=8B=95=E6=99=82?= =?UTF-8?q?=E3=81=AEGoogle=20Drive=E3=83=9E=E3=82=A6=E3=83=B3=E3=83=88?= =?UTF-8?q?=E5=88=87=E6=96=AD=E3=83=BBRead-only=E5=8C=96=E5=AF=BE=E7=AD=96?= =?UTF-8?q?=E3=81=8A=E3=82=88=E3=81=B3=E8=87=AA=E5=8B=95=E5=BE=A9=E6=97=A7?= =?UTF-8?q?=E6=A9=9F=E8=83=BD=E3=81=AE=E5=AE=9F=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MusicDownloader/Class/CmnUtil.cs | 95 +++++++++++++++++++ .../Class/Downloader/YoutubeDownloader.cs | 7 +- MusicDownloader/MusicDownloader.csproj | 5 +- MusicDownloader/Program.cs | 44 ++++++++- auto-mount-gdrive.ps1 | 70 ++++++++++++++ remount-gdrive.bat | 34 +++++++ run-auto-mount-silent.vbs | 3 + setup-startup-task.ps1 | 30 ++++++ 8 files changed, 283 insertions(+), 5 deletions(-) create mode 100644 auto-mount-gdrive.ps1 create mode 100644 remount-gdrive.bat create mode 100644 run-auto-mount-silent.vbs create mode 100644 setup-startup-task.ps1 diff --git a/MusicDownloader/Class/CmnUtil.cs b/MusicDownloader/Class/CmnUtil.cs index a091a6c..fd77a07 100644 --- a/MusicDownloader/Class/CmnUtil.cs +++ b/MusicDownloader/Class/CmnUtil.cs @@ -444,5 +444,100 @@ namespace MusicDownloader.Class if (ex == null) return; LogManager.AddError($"未処理の例外が発生しました: {ex.Message}", ex); } + + /// + /// 指定されたディレクトリが存在することを確認・作成する。 + /// Google Drive や WSL2 DrvFs マウント等の一時的な切断(EINVAL / IOException等)に備え、自動リトライを行う。 + /// + /// 対象ディレクトリパス + /// 最大試行回数(既定5回) + /// 試行間隔ミリ秒(既定3000ms) + public static void EnsureDirectoryExists(string path, int maxRetries = 5, int retryDelayMs = 3000) + { + if (string.IsNullOrWhiteSpace(path)) return; + + for (int attempt = 1; attempt <= maxRetries; attempt++) + { + try + { + if (Directory.Exists(path)) + { + return; + } + + Directory.CreateDirectory(path); + return; + } + catch (Exception ex) when (attempt < maxRetries) + { + LogManager.AddWarning($"ディレクトリへのアクセス/作成に失敗しました (試行 {attempt}/{maxRetries}): {path} - {ex.Message}。{retryDelayMs / 1000}秒後に再試行します..."); + System.Threading.Thread.Sleep(retryDelayMs); + } + catch (Exception ex) + { + if (ex.Message.Contains("Read-only", StringComparison.OrdinalIgnoreCase)) + { + LogManager.AddError($"ストレージが読み取り専用 (Read-only) になっています: {path} - Google Drive (G:) のマウントが切断されている可能性があります。remount-gdrive.bat を実行してください。", ex); + } + else + { + LogManager.AddError($"ディレクトリの作成に失敗しました(ストレージ切断等の可能性があります): {path} - {ex.Message}", ex); + } + throw; + } + } + } + + /// + /// 指定されたストレージディレクトリへの書き込みが可能か(読み取り専用や切断になっていないか)を検証する。 + /// Google Drive や WSL2 DrvFs マウント切断時に発生する Read-only file system を早期検知する。 + /// + /// 検証対象ディレクトリパス + /// リトライ回数(既定3回) + /// リトライ間隔ミリ秒(既定3000ms) + /// 正常に書き込み可能であれば true + public static bool EnsureStorageWritable(string dirPath, int maxRetries = 3, int retryDelayMs = 3000) + { + if (string.IsNullOrWhiteSpace(dirPath)) return false; + + for (int attempt = 1; attempt <= maxRetries; attempt++) + { + try + { + EnsureDirectoryExists(dirPath, maxRetries: 2, retryDelayMs: 1000); + + var testFile = Path.Combine(dirPath, $".storage_probe_{Guid.NewGuid():N}.tmp"); + File.WriteAllText(testFile, "probe"); + if (File.Exists(testFile)) + { + File.Delete(testFile); + } + return true; + } + catch (Exception ex) + { + bool isReadOnly = ex.Message.Contains("Read-only", StringComparison.OrdinalIgnoreCase); + if (attempt < maxRetries) + { + LogManager.AddWarning($"[ストレージ疎通確認] ディレクトリ書き込みテストに失敗しました (試行 {attempt}/{maxRetries}): {dirPath} - {ex.Message}。{retryDelayMs / 1000}秒後に再試行します..."); + System.Threading.Thread.Sleep(retryDelayMs); + } + else + { + if (isReadOnly) + { + LogManager.AddError($"[ストレージ疎通異常] 出力先が読み取り専用 (Read-only) になっています: {dirPath} - Google Drive (G:) のマウント切断またはリンク切れの可能性があります。", ex); + } + else + { + LogManager.AddError($"[ストレージ疎通異常] 出力先ストレージへの書き込みに失敗しました: {dirPath} - {ex.Message}", ex); + } + return false; + } + } + } + + return false; + } } } diff --git a/MusicDownloader/Class/Downloader/YoutubeDownloader.cs b/MusicDownloader/Class/Downloader/YoutubeDownloader.cs index 682a107..720625e 100644 --- a/MusicDownloader/Class/Downloader/YoutubeDownloader.cs +++ b/MusicDownloader/Class/Downloader/YoutubeDownloader.cs @@ -221,9 +221,12 @@ namespace MusicDownloader.Class.Downloader // 【要件⑥】プレイリストごとのログファイル(MusicDownloader_開始時間_プレイリスト名.log)を設定 LogManager.SetPlaylistContext(DateTime.Now, sanitizedPlaylistName); - // ① 全ての曲を格納する共通フォルダ「Youtube」の準備 + // ① 全ての曲を格納する共通フォルダ「Youtube」の準備および書き込み疎通確認 var youtubeFolder = Path.Combine(outputBaseDir, CmnDefine.YoutubeFolderName); - Directory.CreateDirectory(youtubeFolder); + if (!CmnUtil.EnsureStorageWritable(youtubeFolder)) + { + throw new IOException($"出力先ディレクトリへの書き込みができません (Read-only file system またはストレージ切断): {youtubeFolder}"); + } // ④ Google Drive同期前の安全なローカル作業領域 var stagingDir = CmnDefine.GetStagingDir(); diff --git a/MusicDownloader/MusicDownloader.csproj b/MusicDownloader/MusicDownloader.csproj index f2f002b..ccc2168 100644 --- a/MusicDownloader/MusicDownloader.csproj +++ b/MusicDownloader/MusicDownloader.csproj @@ -27,8 +27,9 @@ - - + + + diff --git a/MusicDownloader/Program.cs b/MusicDownloader/Program.cs index 9397e87..32fe007 100644 --- a/MusicDownloader/Program.cs +++ b/MusicDownloader/Program.cs @@ -171,7 +171,7 @@ List ResolveTargetPlaylists(string baseDir) // 存在しない場合は初期設定のURL一覧を playlists.txt として保存(今後の追加編集用) try { - Directory.CreateDirectory(baseDir); + CmnUtil.EnsureDirectoryExists(baseDir); File.WriteAllLines(playlistsFile, defaultPlaylistUrls); LogManager.AddLog($"playlists.txt を初期生成しました: {playlistsFile}"); } @@ -207,6 +207,41 @@ LogManager.AddLog($"[起動時モード判定] 初回処理: {(isResumeOnStartup while (true) { loopCount++; + + // 各サイクルの開始前に出力先ストレージの接続健全性を確認(書き込み疎通テスト) + var commonYoutubeDir = Path.Combine(outputDir, CmnDefine.YoutubeFolderName); + bool isStorageReady = false; + int storageWaitCount = 0; + + while (!isStorageReady) + { + if (CmnUtil.EnsureStorageWritable(outputDir, maxRetries: 1, retryDelayMs: 1000) && + CmnUtil.EnsureStorageWritable(commonYoutubeDir, maxRetries: 1, retryDelayMs: 1000)) + { + isStorageReady = true; + if (storageWaitCount > 0) + { + LogManager.AddSuccess($"[ストレージ復旧] 出力先ストレージへの書き込み権限を確認しました。処理を再開します。"); + } + break; + } + + storageWaitCount++; + if (storageWaitCount == 1) + { + LogManager.AddWarning($"[ストレージ待機] 出力先ストレージ ({outputDir}) が読み取り専用または未マウントです。"); + LogManager.AddLog($"[ストレージ待機] Google Drive の起動およびマウント完了を待機しています (10秒間隔で自動確認中)..."); + } + + await Task.Delay(10000); + + // 3分以上待機しても復旧しない場合は、ログを残して待機監視を継続 + if (storageWaitCount % 18 == 0) // 18 * 10秒 = 180秒 (3分ごと) + { + LogManager.AddWarning($"[ストレージ待機継続中] Google Drive ({outputDir}) がまだ書き込み可能になっていません。ホスト側の起動を待機しています..."); + } + } + // 初回実行時: 設定ファイルが resume なら差分ダウンロード (true)、from_scratch なら全曲ダウンロード (false) // 2回目以降 (loopCount > 1): 常に差分ダウンロード (true) bool isIncremental = isFirstRun ? isResumeOnStartup : true; @@ -248,6 +283,13 @@ while (true) catch (Exception ex) { LogManager.AddError($"プレイリスト処理中にエラーが発生しました: {ex.Message}", ex); + + // ストレージ切断や読み取り専用 (Read-only) が発生した場合はループを継続せずプロセスを終了し、コンテナの自動再起動に委ねる + if (ex.ToString().Contains("Read-only", StringComparison.OrdinalIgnoreCase)) + { + LogManager.AddError($"ストレージの読み取り専用化 (Read-only) を検知しました。残りのプレイリスト処理を中止し、コンテナ自動再起動による自己復旧のためプロセスを終了します。"); + Environment.Exit(1); + } } // プレイリスト間で不要メモリを完全に返却 diff --git a/auto-mount-gdrive.ps1 b/auto-mount-gdrive.ps1 new file mode 100644 index 0000000..b48bdd6 --- /dev/null +++ b/auto-mount-gdrive.ps1 @@ -0,0 +1,70 @@ +# ============================================================================== +# Google Drive (G:) WSL2 Auto-Mount & MusicDownloader Recovery Script +# Runs automatically on Windows logon to ensure G: drive is mounted into WSL2. +# ============================================================================== + +$logDir = "C:\feeds\Log" +if (!(Test-Path $logDir)) { + New-Item -ItemType Directory -Force -Path $logDir | Out-Null +} +$logFile = Join-Path $logDir "auto-mount-gdrive.log" + +function Write-Log($msg) { + $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + $line = "[$timestamp] $msg" + Write-Output $line + 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 +} + +if (!(Test-Path "C:\MyMusic\playlists.txt")) { + Write-Log "[Warning] Google Drive target (C:\MyMusic\playlists.txt) not accessible within $maxWaitSeconds seconds." + exit 1 +} +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 +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" + + $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..." + docker restart MusicDownloader | Out-Null + Write-Log "[Success] MusicDownloader container restarted." + } else { + Write-Log "[OK] MusicDownloader container is running with healthy mount (rw)." + } + } else { + Write-Log "Container status: $containerStatus. Starting container..." + docker start MusicDownloader 2>&1 | Out-Null + } +} catch { + Write-Log "[Error] Exception occurred while inspecting container: $_" +} + +Write-Log "Auto-mount process completed successfully." diff --git a/remount-gdrive.bat b/remount-gdrive.bat new file mode 100644 index 0000000..5d29886 --- /dev/null +++ b/remount-gdrive.bat @@ -0,0 +1,34 @@ +@echo off +chcp 65001 > nul +echo ======================================================== +echo Google Drive (G:) WSL2 マウント再接続ツール +echo ======================================================== +echo. + +echo [1/3] ホスト側の Google Drive (G:) 接続確認中... +if not exist "G:\マイドライブ\MyMusic" ( + echo [エラー] ホスト側で G:\マイドライブ\MyMusic が見つかりません。 + echo Google Drive for Desktop が起動し、ログインしているか確認してください。 + pause + exit /b 1 +) +echo [成功] ホスト側 Google Drive (G:) を確認しました。 + +echo. +echo [2/3] WSL2 (docker-desktop) 上の古いマウントを解除して全マウントパスへ再接続中... +wsl -d docker-desktop sh -c "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" + +echo. +echo [3/3] コンテナマウント元 (C:\MyMusic\Youtube) のアクセス疎通確認中... +wsl -d docker-desktop sh -c "ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&1" +if %ERRORLEVEL% equ 0 ( + echo [成功] WSL2 から C:\MyMusic (G:\マイドライブ\MyMusic\Youtube) へのアクセスが正常に復旧しました! +) else ( + echo [警告] WSL2 からのアクセスに失敗しました。Docker Desktop または WSL の再起動が必要な可能性があります。 +) + +echo. +echo ======================================================== +echo 完了しました。 +echo ======================================================== +pause diff --git a/run-auto-mount-silent.vbs b/run-auto-mount-silent.vbs new file mode 100644 index 0000000..626b186 --- /dev/null +++ b/run-auto-mount-silent.vbs @@ -0,0 +1,3 @@ +Set WshShell = CreateObject("WScript.Shell") +WshShell.Run "powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File ""C:\VS2026\MusicDownloader\auto-mount-gdrive.ps1""", 0, False +Set WshShell = Nothing diff --git a/setup-startup-task.ps1 b/setup-startup-task.ps1 new file mode 100644 index 0000000..cfca0be --- /dev/null +++ b/setup-startup-task.ps1 @@ -0,0 +1,30 @@ +# ============================================================================== +# Setup Startup Task and Shortcut for MusicDownloader Auto-Mount +# ============================================================================== + +$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 +$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) +$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) + +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" +} catch { + Write-Warning "[Warning] Failed to register ScheduledTask: $_" +} + +Write-Host "Setup completed successfully."