Files
MusicDownloader/auto-mount-gdrive.ps1

60 lines
3.3 KiB
PowerShell

# ==============================================================================
# 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"
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
}
# 1. ホスト側 Google Drive (G:) のアクセス健全性確認
if (!(Test-Path "G:\マイドライブ\MyMusic") -or !(Test-Path "C:\MyMusic")) {
# ホスト側で Google Drive が起動していない場合は何もしない
exit 0
}
# 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"
}
# 3. MusicDownloader コンテナの健全性確認および復旧
try {
$containerStatus = docker inspect MusicDownloader --format "{{.State.Status}}" 2>&1
if ($containerStatus -eq "running") {
# コンテナ内部からのマウントアクセス確認
$null = docker exec MusicDownloader ls -d /music/Youtube 2>&1
$isContainerMountBroken = ($LASTEXITCODE -ne 0)
if ($isWslMountBroken -or $isContainerMountBroken) {
Write-Log "[コンテナ修復] コンテナ内のマウント無効化を検知しました。MusicDownloader を再起動します..."
docker restart MusicDownloader | Out-Null
Write-Log "[成功] MusicDownloader コンテナを再起動しました。"
}
} elseif ($containerStatus -eq "exited" -or $containerStatus -eq "created") {
Write-Log "コンテナが停止しています (Status: $containerStatus)。MusicDownloader を起動します..."
docker start MusicDownloader | Out-Null
Write-Log "[成功] MusicDownloader コンテナを起動しました。"
}
} catch {
Write-Log "[エラー] コンテナ確認中に例外が発生しました: $_"
}