From 873b25e881ebb8a26e7226f7615496dc8b8cd6a3 Mon Sep 17 00:00:00 2001 From: rameen Date: Fri, 9 Oct 2026 17:34:23 +0330 Subject: [PATCH] backup script that run on gitea server. --- .gitattributes | 3 + .gitignore | 1 + infrastructure/BACKUP.md | 68 ++++- .../scripts/copy-prod-backup-askpass.cmd | 4 + infrastructure/scripts/copy-prod-backup.ps1 | 235 ++++++++++++++++++ 5 files changed, 308 insertions(+), 3 deletions(-) create mode 100644 infrastructure/scripts/copy-prod-backup-askpass.cmd create mode 100644 infrastructure/scripts/copy-prod-backup.ps1 diff --git a/.gitattributes b/.gitattributes index 6673000..d501c5f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ # Shell scripts must use LF — CRLF breaks Alpine entrypoints ("No such file or directory"). *.sh text eol=lf +# Windows OpenSSH askpass is a cmd script. LF-only cmd files fail on the staging PC. +*.cmd text eol=crlf +*.ps1 text eol=crlf diff --git a/.gitignore b/.gitignore index 6cd048a..0785bc4 100644 --- a/.gitignore +++ b/.gitignore @@ -76,6 +76,7 @@ Desktop.ini *.crt .secrets/ secrets/ +infrastructure/scripts/copy-prod-backup-askpass.exe # === Database files === *.sqlite diff --git a/infrastructure/BACKUP.md b/infrastructure/BACKUP.md index dc5f651..38f8134 100644 --- a/infrastructure/BACKUP.md +++ b/infrastructure/BACKUP.md @@ -1,6 +1,6 @@ # Manual database backup (nudentic.ir) -Copy-paste runbook for the production Postgres database. Use it when you need a dump in a hurry, a copy of production data on your Mac, or a restore after something has gone wrong. +Copy-paste runbook for the production Postgres database. Use it when you need a dump in a hurry, a copy of production data on your Mac or the Windows staging PC, or a restore after something has gone wrong. A **dump** is one file that contains the `dyolink_db` tables: users, patients, appointments, treatments, lab cases, billing, and so on. Taking a dump does **not** stop the site. Postgres reads a consistent snapshot while the app keeps running. @@ -17,11 +17,12 @@ The dump does **not** contain photo or case-file bytes. Those files live on disk | Dump folder on the server | `/opt/dyolink/infrastructure/database/backups` | | Same folder inside the container | `/backups` | | Copy on the Mac | `~/Documents/dental/nudentic-backups/` | +| Copy on the Windows staging PC | `C:\dyolink\nudentic-backups` | | Local Postgres container | `dyolink-postgres-dev` | The container already has `POSTGRES_USER` and `POSTGRES_DB`. Do not type the password, and do not print `database.env`. -Keep dump files private. They contain patient and account data. Do not commit them, and do not put them inside the git repo. `~/Documents/dental/nudentic-backups/` is outside the repo. +Keep dump files private. They contain patient and account data. Do not commit them, and do not put them inside the git repo. `~/Documents/dental/nudentic-backups/` and `C:\dyolink\nudentic-backups` are outside the repo. ## Do not @@ -41,7 +42,7 @@ The server keeps a new dump at three Iran times (`Asia/Tehran`, UTC+3:30). Each | 11:00 | Morning work | | 16:00 | Most of the afternoon | -The longest gap is overnight, from 16:00 to 02:00. Rows saved in that gap are only in the live database until the next file. These files sit on the same disk as the database. Copy them to the Mac with section 2 when you want copies that survive a dead server. Filenames use UTC, the same clock as the first manual dump. +The longest gap is overnight, from 16:00 to 02:00. Rows saved in that gap are only in the live database until the next file. These files sit on the same disk as the database. The Windows staging PC copies each dump off that disk 30 minutes later. The Mac copy in section 2 is the other off-site copy. Filenames use UTC, the same clock as the first manual dump. The script is [`scripts/backup-prod-db.sh`](scripts/backup-prod-db.sh). A git tag deploy does not copy it, so put it on the server once from the Mac: @@ -141,6 +142,67 @@ Output goes to `~/Documents/dental/nudentic-backups/copy.log`. --- +## Copy the dumps to the Windows staging PC + +The staging PC pulls the same folder three times a day, 30 minutes after each production dump. One run copies every `.dump` still on the server and skips a file that is already in `C:\dyolink\nudentic-backups`. If the PC is off at 11:30, that run starts when the PC is next on, and the 16:30 run still copies the 11:00 file while production is up. + +| Iran time | What it copies | +|-----------|----------------| +| 02:30 | The 02:00 dump | +| 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 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. + +A deploy does not install this. On the Windows PC, from a checkout of the repo: + +```powershell +New-Item -ItemType Directory -Force -Path C:\dyolink\scripts, C:\dyolink\nudentic-backups +Copy-Item infrastructure\scripts\copy-prod-backup.ps1, infrastructure\scripts\copy-prod-backup-askpass.cmd C:\dyolink\scripts\ +``` + +Put the production SSH password in `C:\dyolink\secrets\nudentic-ssh-password.txt` on one line. No quotes. + +The first run writes `C:\dyolink\scripts\copy-prod-backup-askpass.exe` next to the cmd file. Windows OpenSSH cannot start a `.cmd` as the password prompt, so that exe runs the cmd and passes the password through. It is created on the PC. It is not in git. + +Check the PC clock: + +```powershell +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. + +```powershell +$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\dyolink\scripts\copy-prod-backup.ps1' +$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 +$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 +``` + +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. + +Try it once before relying on the schedule: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\dyolink\scripts\copy-prod-backup.ps1 +``` + +A good run writes a `.dump` larger than a few kilobytes into `C:\dyolink\nudentic-backups` and a line in `C:\dyolink\nudentic-backups\copy.log`. The first run also stores the production host key in `known_hosts` in that folder. Run it again. The log should say each file is already there. + +--- + ## 3. Load the dump into the local database This **deletes** the current local `dyolink_db` and replaces it with the dump. Production is not touched. diff --git a/infrastructure/scripts/copy-prod-backup-askpass.cmd b/infrastructure/scripts/copy-prod-backup-askpass.cmd new file mode 100644 index 0000000..f471848 --- /dev/null +++ b/infrastructure/scripts/copy-prod-backup-askpass.cmd @@ -0,0 +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)" diff --git a/infrastructure/scripts/copy-prod-backup.ps1 b/infrastructure/scripts/copy-prod-backup.ps1 new file mode 100644 index 0000000..5295935 --- /dev/null +++ b/infrastructure/scripts/copy-prod-backup.ps1 @@ -0,0 +1,235 @@ +# 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. +$ErrorActionPreference = 'Continue' + +$Remote = 'dyolink@185.243.48.140' +$RemoteDir = '/opt/dyolink/infrastructure/database/backups' +$Dest = 'C:\dyolink\nudentic-backups' +$PasswordFile = 'C:\dyolink\secrets\nudentic-ssh-password.txt' +$LogPath = Join-Path $Dest 'copy.log' +$AskPass = Join-Path $PSScriptRoot 'copy-prod-backup-askpass.cmd' +$KnownHosts = 'C:/dyolink/nudentic-backups/known_hosts' + +function Write-Log([string]$Message) { + $line = '[{0}] {1}' -f ([datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')), $Message + [System.IO.File]::AppendAllText($LogPath, $line + [Environment]::NewLine) + 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() + $finished = $proc.WaitForExit(1800000) + if (-not $finished) { + try { $proc.Kill() } catch {} + $proc.Dispose() + return [pscustomobject]@{ Code = 124; Out = ''; Err = 'timed out after 30 minutes' } + } + $stdout = $stdoutTask.Result + $stderr = $stderrTask.Result + $code = $proc.ExitCode + $proc.Dispose() + return [pscustomobject]@{ Code = $code; Out = $stdout; Err = $stderr.Trim() } +} + +function Ensure-AskpassExe([string]$CmdPath) { + # Windows OpenSSH starts SSH_ASKPASS with CreateProcess, which cannot run a .cmd. + # This exe runs the cmd and forwards its stdout unchanged. + $exePath = [System.IO.Path]::ChangeExtension($CmdPath, '.exe') + $cmdTime = (Get-Item -LiteralPath $CmdPath).LastWriteTimeUtc + if ((Test-Path -LiteralPath $exePath) -and (Get-Item -LiteralPath $exePath).LastWriteTimeUtc -ge $cmdTime) { + return $exePath + } + if (Test-Path -LiteralPath $exePath) { + Remove-Item -LiteralPath $exePath -Force + } + $source = @' +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +public class ProdBackupAskpass { + public static int Main() { + string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string cmd = Path.Combine(dir, "copy-prod-backup-askpass.cmd"); + var psi = new ProcessStartInfo(); + psi.FileName = "cmd.exe"; + psi.Arguments = "/d /c \"" + cmd + "\""; + psi.UseShellExecute = false; + psi.RedirectStandardOutput = true; + psi.CreateNoWindow = true; + var proc = Process.Start(psi); + var bytes = new MemoryStream(); + proc.StandardOutput.BaseStream.CopyTo(bytes); + proc.WaitForExit(); + if (proc.ExitCode != 0) return proc.ExitCode; + var data = bytes.ToArray(); + using (var stdout = Console.OpenStandardOutput()) { + stdout.Write(data, 0, data.Length); + } + return 0; + } +} +'@ + Add-Type -TypeDefinition $source -OutputAssembly $exePath -OutputType ConsoleApplication -Language CSharp + return $exePath +} + +New-Item -ItemType Directory -Force -Path $Dest | Out-Null + +if (-not (Test-Path -LiteralPath $PasswordFile)) { + Write-Log "Backup copy failed: password file is missing ($PasswordFile)." + exit 1 +} +$passwordText = [System.IO.File]::ReadAllText($PasswordFile).TrimEnd([char]13, [char]10) +if ($passwordText.Length -gt 0 -and [int]$passwordText[0] -eq 0xFEFF) { + $passwordText = $passwordText.Substring(1) +} +if ([string]::IsNullOrWhiteSpace($passwordText)) { + Write-Log "Backup copy failed: password file is empty ($PasswordFile)." + exit 1 +} + +if (-not (Test-Path -LiteralPath $AskPass)) { + Write-Log "Backup copy failed: askpass helper is missing ($AskPass)." + exit 1 +} + +$ssh = (Get-Command ssh.exe -ErrorAction SilentlyContinue).Source +$scp = (Get-Command scp.exe -ErrorAction SilentlyContinue).Source +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 +} + +try { + $env:SSH_ASKPASS = Ensure-AskpassExe $AskPass +} catch { + Write-Log "Backup copy failed: could not prepare the password helper. $($_.Exception.Message)" + exit 1 +} +$env:SSH_ASKPASS_REQUIRE = 'force' +$env:DISPLAY = 'dummy' + +$sshOpts = @( + '-o', 'PreferredAuthentications=password', + '-o', 'PubkeyAuthentication=no', + '-o', 'NumberOfPasswordPrompts=1', + '-o', 'StrictHostKeyChecking=accept-new', + '-o', "UserKnownHostsFile=$KnownHosts", + '-o', 'ConnectTimeout=30' +) + +Write-Log 'Starting copy from production.' + +$list = Invoke-OpenSsh $ssh ($sshOpts + @($Remote, "ls -1 $RemoteDir/*.dump 2>/dev/null")) +if ($list.Code -ne 0 -and [string]::IsNullOrWhiteSpace($list.Out)) { + $detail = $list.Err + if ([string]::IsNullOrWhiteSpace($detail)) { + $detail = "ssh exit $($list.Code)" + } + if ($list.Code -eq 2) { + Write-Log "No dump found in $RemoteDir." + } else { + Write-Log "Backup copy failed: $detail" + } + exit 1 +} + +$remoteFiles = @($list.Out -split '\r?\n' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) +if ($remoteFiles.Count -eq 0) { + Write-Log "No dump found in $RemoteDir." + exit 1 +} + +$failed = $false +foreach ($remotePath in $remoteFiles) { + # Windows PowerShell 5.1 does not treat '/' as a separator in GetFileName. + $name = ($remotePath -split '/')[-1] + if ($name -notmatch '^(nudentic_\d{8}_\d{6}|nudentic_before_restore_\d{8}_\d{6})\.dump$') { + Write-Log "Skipped unexpected file: $name" + continue + } + if ($remotePath -ne "$RemoteDir/$name") { + Write-Log "Skipped unexpected path: $remotePath" + continue + } + + $localPath = Join-Path $Dest $name + if ((Test-Path -LiteralPath $localPath) -and (Get-Item -LiteralPath $localPath).Length -gt 0) { + Write-Log "Already present: $name" + continue + } + + $partial = "$localPath.partial" + if (Test-Path -LiteralPath $partial) { + Remove-Item -LiteralPath $partial -Force + } + + # A drive-letter path must use forward slashes so scp does not read "C:" as a host name. + $partialScp = $partial -replace '\\', '/' + $copied = Invoke-OpenSsh $scp ($sshOpts + @("${Remote}:${remotePath}", $partialScp)) + $partialLength = 0 + if (Test-Path -LiteralPath $partial) { + $partialLength = (Get-Item -LiteralPath $partial).Length + } + if ($copied.Code -ne 0 -or $partialLength -le 0) { + if (Test-Path -LiteralPath $partial) { + Remove-Item -LiteralPath $partial -Force + } + $detail = $copied.Err + if ([string]::IsNullOrWhiteSpace($detail)) { + $detail = "scp exit $($copied.Code)" + } + Write-Log "Backup copy failed for ${name}: $detail" + $failed = $true + continue + } + + Move-Item -LiteralPath $partial -Destination $localPath -Force + Write-Log "Copied $name ($partialLength bytes)" +} + +if ($failed) { + 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) { + Remove-Item -LiteralPath $_.FullName -Force + Write-Log "Removed $($_.Name) (older than 30 days)" + } + } +} + +Write-Log 'Copy finished.' +exit 0