Files
dyolink/infrastructure/scripts/copy-prod-backup.ps1

264 lines
9.4 KiB
PowerShell

# 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. 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'
$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 Invoke-OpenSsh([string]$Exe, [string[]]$ArgumentList) {
# 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
# 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 {}
Remove-Item -LiteralPath $outFile, $errFile -Force -ErrorAction SilentlyContinue
return [pscustomobject]@{ Code = 124; Out = ''; Err = 'timed out after 30 minutes' }
}
$null = $proc.WaitForExit()
$code = $proc.ExitCode
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) {
# 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.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();
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
Write-Log 'Script started.'
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
}
# 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
}
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'
# -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',
'-o', 'StrictHostKeyChecking=accept-new',
'-o', "UserKnownHostsFile=$KnownHosts",
'-o', 'ConnectTimeout=30'
)
Write-Log 'Starting copy from production.'
$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 -split '\r?\n') | Select-Object -Last 3) -join ' | '
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
$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
}
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 -split '\r?\n') | Select-Object -Last 3) -join ' | '
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) {
Write-Log 'Skipped cleanup: a copy failed, so no file was deleted on this PC.'
exit 1
}
# 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) (not on the server)"
}
}
}
Write-Log 'Copy finished.'
exit 0