From 9fc4ea91330f157eb1fdb232a6f192dfb917eae1 Mon Sep 17 00:00:00 2001 From: rameen Date: Fri, 16 Oct 2026 20:59:38 +0330 Subject: [PATCH 1/2] fix(backup): copy job no longer hangs in SSH and Windows mirrors the server dumps Co-authored-by: Cursor --- AGENTS.md | 2 +- infrastructure/BACKUP.md | 17 +-- .../scripts/copy-prod-backup-askpass.cmd | 2 +- infrastructure/scripts/copy-prod-backup.ps1 | 103 +++++++++++------- 4 files changed, 75 insertions(+), 49 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c78b55d..e86ac9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,7 +96,7 @@ Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpe **AdminJS:** Manual resource allowlist in `backend/src/admin/resources.ts`. **Whenever `schema.prisma` changes**, update AdminJS resources in the same task (new/renamed/removed models, hide secrets). Models with only composite `@@id` must not be registered (list 500) — including `LabCaseAttachment`. Single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock` **are** registered. `LabCase.listedAt` is trigger-maintained (list/filter/show only; never write). Rule: `.cursor/rules/adminjs.mdc`. -**Database backups:** Production dumps three times a day on the Linux server and keeps them for 3 days. The Mac copies them once at 17:00. The Windows staging PC copies each dump 30 minutes later and keeps them for 30 days (task **Nudentic copy prod backup**). Runbook: [`infrastructure/BACKUP.md`](infrastructure/BACKUP.md). +**Database backups:** Production dumps three times a day on the Linux server and keeps them for 3 days. The Mac copies them once at 17:00. The Windows staging PC copies each dump 30 minutes later and mirrors the server folder, so a dump gone from the server is removed there (task **Nudentic copy prod backup**). Runbook: [`infrastructure/BACKUP.md`](infrastructure/BACKUP.md). ## Git & commits diff --git a/infrastructure/BACKUP.md b/infrastructure/BACKUP.md index 453c8c9..0400bec 100644 --- a/infrastructure/BACKUP.md +++ b/infrastructure/BACKUP.md @@ -152,9 +152,9 @@ The staging PC pulls the same folder three times a day, 30 minutes after each pr | 11:30 | The 11:00 dump | | 16:30 | The 16:00 dump | -`nudentic_YYYYMMDD_HHMMSS.dump` files older than 30 days are deleted on the PC. `nudentic_before_restore_*.dump` is kept. This stores files only. It does not load them into the staging database, and it does not change the production server. +The folder on the PC mirrors the server folder. After a run where every copy succeeded, a `nudentic_*.dump` on the PC that is no longer on the server is deleted (about 3 days of dumps are left). If the server list is empty or any copy fails, nothing is deleted. The Mac copy is the longer archive. This stores files only. It does not load them into the staging database, and it does not change the production server. -The script is [`scripts/copy-prod-backup.ps1`](scripts/copy-prod-backup.ps1). It reads the production SSH password from `C:\dyolink\secrets\nudentic-ssh-password.txt`. A scheduled task has no person to type it. The password file is the full `dyolink` login. Do not commit it. +The script is [`scripts/copy-prod-backup.ps1`](scripts/copy-prod-backup.ps1). It reads the production SSH password from `C:\dyolink\secrets\nudentic-ssh-password.txt`. A scheduled task has no person to type it. The password file is the full `dyolink` login. Do not commit it. SSH is started with no window. A window makes SSH wait for a password that nobody can see, and `copy.log` stays on `Starting copy from production.` A deploy does not install this. On the Windows PC, from a checkout of the repo: @@ -175,20 +175,23 @@ Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz' If the offset is `+03:30`, register **02:30**, **11:30**, and **16:30**. The task runs as the current Windows user whether or not anyone is logged in. That user must be able to read `C:\dyolink\secrets`. The password it asks for is the Windows login, so the task can open the network connection. It is not the server password. +Use the full `powershell.exe` path and a quoted `-File` path. `powershell.exe` alone, or a `-File` path Windows cannot open, finishes with **4294770688** (`0xFFFD0000`) and never runs the script. The limit is 45 minutes so a stuck copy cannot block the later runs for three days. + ```powershell -$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\dyolink\scripts\copy-prod-backup.ps1' +$powershell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' +$scriptPath = 'C:\dyolink\scripts\copy-prod-backup.ps1' +$action = New-ScheduledTaskAction -Execute $powershell -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptPath`"" -WorkingDirectory 'C:\dyolink\scripts' $triggers = @( (New-ScheduledTaskTrigger -Daily -At '02:30'), (New-ScheduledTaskTrigger -Daily -At '11:30'), (New-ScheduledTaskTrigger -Daily -At '16:30') ) -$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew +$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 45) $secure = Read-Host 'Windows account password (lets the task run when nobody is logged in)' -AsSecureString $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) $windowsPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) -Unregister-ScheduledTask -TaskName 'Nudentic copy prod backup' -Confirm:$false -ErrorAction SilentlyContinue -Register-ScheduledTask -TaskName 'Nudentic copy prod backup' -Action $action -Trigger $triggers -Settings $settings -User "$env:USERDOMAIN\$env:USERNAME" -Password $windowsPassword +Register-ScheduledTask -TaskName 'Nudentic copy prod backup' -Action $action -Trigger $triggers -Settings $settings -User "$env:USERDOMAIN\$env:USERNAME" -Password $windowsPassword -Force ``` If `Get-Date` shows UTC (`+00:00`), production’s jobs are 22:30, 07:30, and 12:30 UTC. Use **23:00**, **08:00**, and **13:00** in `$triggers` instead. @@ -206,7 +209,7 @@ Get-ScheduledTask -TaskName 'Nudentic copy prod backup' | Format-List TaskName, Get-ScheduledTaskInfo -TaskName 'Nudentic copy prod backup' | Format-List LastRunTime, LastTaskResult, NextRunTime ``` -`State: Ready` means it is scheduled. `LastTaskResult` **267011** and a `LastRunTime` in 1999 mean it has never run. **0** means the last copy finished. +`State: Ready` means it is scheduled. `LastTaskResult` **267011** and a `LastRunTime` in 1999 mean it has never run. **0** means the last copy finished. **4294770688** (`0xFFFD0000`) means Windows did not open the script path. Re-register with the block above, then run the script by hand. Run it now without waiting for the next clock time: diff --git a/infrastructure/scripts/copy-prod-backup-askpass.cmd b/infrastructure/scripts/copy-prod-backup-askpass.cmd index f471848..1937232 100644 --- a/infrastructure/scripts/copy-prod-backup-askpass.cmd +++ b/infrastructure/scripts/copy-prod-backup-askpass.cmd @@ -1,4 +1,4 @@ @echo off rem OpenSSH reads the production SSH password from stdout. Nothing else is printed. chcp 65001 >nul -powershell.exe -NoLogo -NoProfile -NonInteractive -Command "$p = [IO.File]::ReadAllText('C:\dyolink\secrets\nudentic-ssh-password.txt'); if ($p.Length -gt 0 -and [int]$p[0] -eq 0xFEFF) { $p = $p.Substring(1) }; $p = $p.TrimEnd([char]13, [char]10); [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; [Console]::Out.Write($p)" +powershell.exe -NoLogo -NoProfile -NonInteractive -InputFormat None -Command "$p = [IO.File]::ReadAllText('C:\dyolink\secrets\nudentic-ssh-password.txt'); if ($p.Length -gt 0 -and [int]$p[0] -eq 0xFEFF) { $p = $p.Substring(1) }; $p = $p.TrimEnd([char]13, [char]10); [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; [Console]::Out.Write($p)" diff --git a/infrastructure/scripts/copy-prod-backup.ps1 b/infrastructure/scripts/copy-prod-backup.ps1 index 5295935..7b09920 100644 --- a/infrastructure/scripts/copy-prod-backup.ps1 +++ b/infrastructure/scripts/copy-prod-backup.ps1 @@ -1,8 +1,10 @@ # Run on the Windows staging PC. Reads the production SSH password from # C:\dyolink\secrets\nudentic-ssh-password.txt and copies every dump in the # production backup folder to C:\dyolink\nudentic-backups. Skips files already -# there. Deletes nudentic_YYYYMMDD_HHMMSS.dump older than 30 days. -# Does not delete nudentic_before_restore_*.dump. Does not save the password. +# there. Then mirrors the server: a nudentic_*.dump on this PC that is no longer +# in the server folder is deleted. Nothing is ever changed on the server. +# Cleanup is skipped unless the server list was read and every copy succeeded. +# Does not save the password. $ErrorActionPreference = 'Continue' $Remote = 'dyolink@185.243.48.140' @@ -19,39 +21,32 @@ function Write-Log([string]$Message) { Write-Host $line } -function Format-ProcessArg([string]$Value) { - if ($Value -notmatch '[\s"]') { - return $Value - } - $escaped = $Value -replace '(\\+)$', '$1$1' -replace '(\\*)"', '$1$1\"' - return '"' + $escaped + '"' -} - function Invoke-OpenSsh([string]$Exe, [string[]]$ArgumentList) { - $psi = New-Object System.Diagnostics.ProcessStartInfo - $psi.FileName = $Exe - $psi.Arguments = ($ArgumentList | ForEach-Object { Format-ProcessArg $_ }) -join ' ' - $psi.UseShellExecute = $false - $psi.RedirectStandardOutput = $true - $psi.RedirectStandardError = $true - $psi.CreateNoWindow = $true - - $proc = New-Object System.Diagnostics.Process - $proc.StartInfo = $psi - [void]$proc.Start() - $stdoutTask = $proc.StandardOutput.ReadToEndAsync() - $stderrTask = $proc.StandardError.ReadToEndAsync() + # SSH attached to a PowerShell window waits for a password and never shows + # the prompt. A hidden process writing to files is the run that finishes. + $stamp = [guid]::NewGuid().ToString('n') + $outFile = Join-Path $env:TEMP "dyolink-ssh-out-$stamp.txt" + $errFile = Join-Path $env:TEMP "dyolink-ssh-err-$stamp.txt" + $proc = Start-Process -FilePath $Exe -ArgumentList $ArgumentList -WindowStyle Hidden -RedirectStandardOutput $outFile -RedirectStandardError $errFile -PassThru $finished = $proc.WaitForExit(1800000) if (-not $finished) { - try { $proc.Kill() } catch {} - $proc.Dispose() + try { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } catch {} + Remove-Item -LiteralPath $outFile, $errFile -Force -ErrorAction SilentlyContinue return [pscustomobject]@{ Code = 124; Out = ''; Err = 'timed out after 30 minutes' } } - $stdout = $stdoutTask.Result - $stderr = $stderrTask.Result + $null = $proc.WaitForExit() $code = $proc.ExitCode - $proc.Dispose() - return [pscustomobject]@{ Code = $code; Out = $stdout; Err = $stderr.Trim() } + if ($null -eq $code) { $code = 1 } + $stdout = '' + $stderr = '' + if (Test-Path -LiteralPath $outFile) { + $stdout = [System.IO.File]::ReadAllText($outFile) + } + if (Test-Path -LiteralPath $errFile) { + $stderr = [System.IO.File]::ReadAllText($errFile).Trim() + } + Remove-Item -LiteralPath $outFile, $errFile -Force -ErrorAction SilentlyContinue + return [pscustomobject]@{ Code = $code; Out = $stdout; Err = $stderr } } function Ensure-AskpassExe([string]$CmdPath) { @@ -80,8 +75,12 @@ public class ProdBackupAskpass { psi.Arguments = "/d /c \"" + cmd + "\""; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; + psi.RedirectStandardInput = true; + psi.RedirectStandardError = true; psi.CreateNoWindow = true; var proc = Process.Start(psi); + proc.StandardInput.Close(); + proc.StandardError.ReadToEnd(); var bytes = new MemoryStream(); proc.StandardOutput.BaseStream.CopyTo(bytes); proc.WaitForExit(); @@ -99,6 +98,7 @@ public class ProdBackupAskpass { } New-Item -ItemType Directory -Force -Path $Dest | Out-Null +Write-Log 'Script started.' if (-not (Test-Path -LiteralPath $PasswordFile)) { Write-Log "Backup copy failed: password file is missing ($PasswordFile)." @@ -118,8 +118,26 @@ if (-not (Test-Path -LiteralPath $AskPass)) { exit 1 } -$ssh = (Get-Command ssh.exe -ErrorAction SilentlyContinue).Source -$scp = (Get-Command scp.exe -ErrorAction SilentlyContinue).Source +# A scheduled task has no mapped drives. Get-Command walks PATH and can sit there +# until the task is killed, which writes nothing to the log. +function Find-OpenSshTool([string]$Name) { + foreach ($path in @( + (Join-Path $env:SystemRoot "System32\OpenSSH\$Name"), + (Join-Path $env:SystemRoot "Sysnative\OpenSSH\$Name") + )) { + if (Test-Path -LiteralPath $path) { + return $path + } + } + $cmd = Get-Command $Name -ErrorAction SilentlyContinue + if ($cmd) { + return $cmd.Source + } + return $null +} + +$ssh = Find-OpenSshTool 'ssh.exe' +$scp = Find-OpenSshTool 'scp.exe' if (-not $ssh -or -not $scp) { Write-Log 'Backup copy failed: ssh.exe or scp.exe is not on PATH. Install the Windows OpenSSH Client.' exit 1 @@ -166,9 +184,11 @@ if ($remoteFiles.Count -eq 0) { } $failed = $false +$serverNames = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) foreach ($remotePath in $remoteFiles) { # Windows PowerShell 5.1 does not treat '/' as a separator in GetFileName. $name = ($remotePath -split '/')[-1] + [void]$serverNames.Add($name) if ($name -notmatch '^(nudentic_\d{8}_\d{6}|nudentic_before_restore_\d{8}_\d{6})\.dump$') { Write-Log "Skipped unexpected file: $name" continue @@ -214,19 +234,22 @@ foreach ($remotePath in $remoteFiles) { } if ($failed) { + Write-Log 'Skipped cleanup: a copy failed, so no file was deleted on this PC.' exit 1 } -$cutoff = [datetime]::UtcNow.Date.AddDays(-30) -Get-ChildItem -LiteralPath $Dest -File -Filter 'nudentic_*.dump' | ForEach-Object { - if ($_.Name -match '^nudentic_(\d{8})_\d{6}\.dump$') { - $stamp = [datetime]::SpecifyKind( - [datetime]::ParseExact($Matches[1], 'yyyyMMdd', [cultureinfo]::InvariantCulture), - [datetimekind]::Utc - ) - if ($stamp -lt $cutoff) { +# Mirror: keep only the dumps that are still in the server folder. Only the two +# dump name patterns are touched. copy.log, known_hosts and other files stay. +if ($serverNames.Count -eq 0) { + Write-Log 'Skipped cleanup: the server list was empty, so no file was deleted on this PC.' +} else { + Get-ChildItem -LiteralPath $Dest -File -Filter 'nudentic_*.dump' | ForEach-Object { + if ($_.Name -notmatch '^(nudentic_\d{8}_\d{6}|nudentic_before_restore_\d{8}_\d{6})\.dump$') { + return + } + if (-not $serverNames.Contains($_.Name)) { Remove-Item -LiteralPath $_.FullName -Force - Write-Log "Removed $($_.Name) (older than 30 days)" + Write-Log "Removed $($_.Name) (not on the server)" } } } -- 2.53.0.windows.1 From 44a321436455b23e94539d31049110fc26ca09e8 Mon Sep 17 00:00:00 2001 From: rameen Date: Fri, 16 Oct 2026 21:32:54 +0330 Subject: [PATCH 2/2] fix(backup): run SSH with -v and read the exit code so the Windows copy finishes Co-authored-by: Cursor --- infrastructure/BACKUP.md | 2 +- infrastructure/scripts/copy-prod-backup.ps1 | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/infrastructure/BACKUP.md b/infrastructure/BACKUP.md index 0400bec..4661e41 100644 --- a/infrastructure/BACKUP.md +++ b/infrastructure/BACKUP.md @@ -154,7 +154,7 @@ The staging PC pulls the same folder three times a day, 30 minutes after each pr The folder on the PC mirrors the server folder. After a run where every copy succeeded, a `nudentic_*.dump` on the PC that is no longer on the server is deleted (about 3 days of dumps are left). If the server list is empty or any copy fails, nothing is deleted. The Mac copy is the longer archive. This stores files only. It does not load them into the staging database, and it does not change the production server. -The script is [`scripts/copy-prod-backup.ps1`](scripts/copy-prod-backup.ps1). It reads the production SSH password from `C:\dyolink\secrets\nudentic-ssh-password.txt`. A scheduled task has no person to type it. The password file is the full `dyolink` login. Do not commit it. SSH is started with no window. A window makes SSH wait for a password that nobody can see, and `copy.log` stays on `Starting copy from production.` +The script is [`scripts/copy-prod-backup.ps1`](scripts/copy-prod-backup.ps1). It reads the production SSH password from `C:\dyolink\secrets\nudentic-ssh-password.txt`. A scheduled task has no person to type it. The password file is the full `dyolink` login. Do not commit it. SSH is started hidden with `-v`. On the staging PC a hidden run without `-v` waits forever and `copy.log` stays on `Starting copy from production.`; with `-v` it finishes in about 8 seconds (the password helper needs that long to start). A deploy does not install this. On the Windows PC, from a checkout of the repo: diff --git a/infrastructure/scripts/copy-prod-backup.ps1 b/infrastructure/scripts/copy-prod-backup.ps1 index 7b09920..c92744a 100644 --- a/infrastructure/scripts/copy-prod-backup.ps1 +++ b/infrastructure/scripts/copy-prod-backup.ps1 @@ -28,6 +28,8 @@ function Invoke-OpenSsh([string]$Exe, [string[]]$ArgumentList) { $outFile = Join-Path $env:TEMP "dyolink-ssh-out-$stamp.txt" $errFile = Join-Path $env:TEMP "dyolink-ssh-err-$stamp.txt" $proc = Start-Process -FilePath $Exe -ArgumentList $ArgumentList -WindowStyle Hidden -RedirectStandardOutput $outFile -RedirectStandardError $errFile -PassThru + # Windows PowerShell 5.1 returns a blank ExitCode unless the handle is read first. + $null = $proc.Handle $finished = $proc.WaitForExit(1800000) if (-not $finished) { try { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } catch {} @@ -152,7 +154,10 @@ try { $env:SSH_ASKPASS_REQUIRE = 'force' $env:DISPLAY = 'dummy' +# -v is required here: on the staging PC the hidden SSH run hangs without it and +# finishes in about 8 seconds with it. It only adds lines to stderr. $sshOpts = @( + '-v', '-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no', '-o', 'NumberOfPasswordPrompts=1', @@ -163,9 +168,9 @@ $sshOpts = @( Write-Log 'Starting copy from production.' -$list = Invoke-OpenSsh $ssh ($sshOpts + @($Remote, "ls -1 $RemoteDir/*.dump 2>/dev/null")) +$list = Invoke-OpenSsh $ssh ($sshOpts + @($Remote, "ls $RemoteDir/*.dump 2>/dev/null")) if ($list.Code -ne 0 -and [string]::IsNullOrWhiteSpace($list.Out)) { - $detail = $list.Err + $detail = (($list.Err -split '\r?\n') | Select-Object -Last 3) -join ' | ' if ([string]::IsNullOrWhiteSpace($detail)) { $detail = "ssh exit $($list.Code)" } @@ -220,7 +225,7 @@ foreach ($remotePath in $remoteFiles) { if (Test-Path -LiteralPath $partial) { Remove-Item -LiteralPath $partial -Force } - $detail = $copied.Err + $detail = (($copied.Err -split '\r?\n') | Select-Object -Last 3) -join ' | ' if ([string]::IsNullOrWhiteSpace($detail)) { $detail = "scp exit $($copied.Code)" } -- 2.53.0.windows.1