feat(khdb): KhdbBackupCount setting, default 1; move the old file aside instead of copying

A full-size khdb.txt is tens of GB, so five backups filled the disk and each copy took minutes.
The previous file is now renamed to khdb.txt.bak-<time> (instant on one volume) and only the newest
KhdbBackupCount are kept (0 = none). A non-numeric or negative value is rejected.
This commit is contained in:
2026-11-06 08:07:46 +01:00
parent a945960cef
commit e270b9ab21
5 changed files with 64 additions and 15 deletions
+1 -1
View File
@@ -55,7 +55,7 @@ Key sections:
- `StorageProvider` — `Azure` or `S3`
- Azure: `storageAccountName`, `containerName`, `sasToken`
- S3: `s3EndpointUrl`, `s3Region`, `s3BucketName`, `s3AccessKeyId`, `s3SecretAccessKey`, `s3ForcePathStyle`
- KHDB layout: `KhdbManifestPath`, `KhdbShardPrefix`, `KhdbLocalShardDir`
- KHDB layout: `KhdbManifestPath`, `KhdbShardPrefix`, `KhdbLocalShardDir`, `KhdbBackupCount`
- App: `InstallationPath`, `ReportPathBase`, `WeakPasswordsDatabase`, `CheckOnlyEnabledUsers`
- Lithnet: `LithnetStorePath`, `LithnetSyncHibp`, `LithnetHashSources`, `LithnetPlaintextSources`, `LithnetBannedWordSources`
- Telemetry (optional): `UsageBeaconUrl`, `UsageBeaconMethod`, `UsageBeaconInstanceId`, `UsageBeaconTimeoutSeconds`
+3
View File
@@ -8,6 +8,9 @@ Starting with **v2.2.0**, Elysium uses a **unified project version**. All script
## [Unreleased]
### Changed
- **KHDB backups:** the previous `khdb.txt` is now moved aside instead of copied (instant instead of minutes for a 40+ GB file), and only the newest one is kept. `KhdbBackupCount` in `ElysiumSettings.txt` sets how many (default 1, `0` = none; was a fixed 5).
### Fixed
- **`Test-WeakADPasswords` spent hours checking the KHDB before testing:** `Resolve-DSInternalsWeakHashFile` validated the whole file with a per-line PowerShell loop, the same pattern that made the KHDB rebuild take hours. It now uses the compiled checker (`Elysium.KhdbText.Inspect` / `WriteNormalized`): one pass over a clean KHDB (about 1.6 s per 5 million hashes on pwsh 7) and no temporary copy. Files with blank or whitespace-padded lines are now normalized too; before, they were passed to DSInternals unchanged.
- **KHDB rebuild took hours (or days) on Windows PowerShell 5.1:** the merged `khdb.txt` was built and validated with PowerShell code per hash line - a function call, a regex, a split and an uppercase conversion for every line, then a second regex pass to validate. Full-size KHDBs have hundreds of millions of lines. The merge and the validation now run in a small compiled class (`Elysium.KhdbMerger` / `Elysium.KhdbText`, built with `Add-Type` on 5.1 and 7, no extra install) with the same rules. 5 million hashes merge in about 4 s on pwsh 7; the 5.1 timing is still to be measured. The rebuild also prints progress per shard.
+2
View File
@@ -41,6 +41,8 @@ s3ForcePathStyle = true
KhdbManifestPath=khdb/manifest.json
KhdbShardPrefix=khdb/shards
KhdbLocalShardDir=khdb-shards
# Previous khdb.txt copies (khdb.txt.bak-*) kept after a rebuild. Each is full size (tens of GB). 0 = none.
KhdbBackupCount=1
# Application Settings
######################
+30 -14
View File
@@ -6,7 +6,8 @@ function Update-ElysiumKhdb {
.DESCRIPTION
Fetches the manifest from the configured storage (Azure Blob via SAS, or S3-compatible via
SigV4), downloads only shards whose checksum changed, removes shards no longer listed, and
atomically replaces the merged KHDB file (keeping the 5 most recent backups).
replaces the merged KHDB file. The previous file is kept as khdb.txt.bak-<time>; KhdbBackupCount (default 1,
0 = none) sets how many backups stay.
.PARAMETER MaxParallelTransfers
Shards downloaded concurrently (each in its own runspace), on Windows PowerShell 5.1 and 7 alike.
@@ -146,6 +147,12 @@ function Update-ElysiumKhdb {
Copy-Item -LiteralPath $manifestTempPath -Destination $localManifestPath -Force
Write-Host ("Manifest saved locally to {0}" -f $localManifestPath)
$backupRetentionCount = 1
$backupSetting = $settings['KhdbBackupCount']
if (-not [string]::IsNullOrWhiteSpace($backupSetting) -and -not ([int]::TryParse($backupSetting, [ref]$backupRetentionCount) -and $backupRetentionCount -ge 0)) {
throw "KhdbBackupCount must be a whole number of 0 or more (got '$backupSetting')."
}
$khdbName = if ([string]::IsNullOrWhiteSpace($settings['WeakPasswordsDatabase'])) { 'khdb.txt' } else { $settings['WeakPasswordsDatabase'] }
$combinedTarget = Join-Path -Path $installPath -ChildPath $khdbName
$combinedTemp = Join-Path -Path $tmpDir.FullName -ChildPath 'khdb-combined.txt'
@@ -165,23 +172,32 @@ function Update-ElysiumKhdb {
Merge-ShardsToFile -Manifest $manifest -ShardsRoot $localShardRoot -TargetPath $combinedTemp
Validate-KHDBFile -Path $combinedTemp
$backupPath = $null
if (Test-Path -LiteralPath $combinedTarget) {
$ts = Get-Date -Format 'yyyyMMdd-HHmmss'
$backupPath = Join-Path -Path $installPath -ChildPath ("$khdbName.bak-$ts")
Copy-Item -LiteralPath $combinedTarget -Destination $backupPath -Force
Write-Host ("Existing KHDB backed up to {0}" -f $backupPath)
# Each run adds one full-size backup; keep only the most recent few so a recurring
# scheduled job doesn't silently accumulate backups until the disk fills up.
$backupRetentionCount = 5
$staleBackups = Get-ChildItem -LiteralPath $installPath -Filter "$khdbName.bak-*" -File -ErrorAction SilentlyContinue |
Sort-Object Name -Descending | Select-Object -Skip $backupRetentionCount
foreach ($stale in $staleBackups) {
try { Remove-Item -LiteralPath $stale.FullName -Force } catch { Write-Warning "Could not remove old backup '$($stale.FullName)': $($_.Exception.Message)" }
if ($backupRetentionCount -gt 0) {
# A move is instant on the same volume; copying a full-size KHDB took minutes.
$backupPath = Join-Path -Path $installPath -ChildPath ("$khdbName.bak-" + (Get-Date -Format 'yyyyMMdd-HHmmss'))
Move-Item -LiteralPath $combinedTarget -Destination $backupPath -Force
Write-Host ("Existing KHDB backed up to {0}" -f $backupPath)
} else {
Remove-Item -LiteralPath $combinedTarget -Force
}
}
Move-Item -LiteralPath $combinedTemp -Destination $combinedTarget -Force
try {
Move-Item -LiteralPath $combinedTemp -Destination $combinedTarget -Force
} catch {
if ($backupPath) { Move-Item -LiteralPath $backupPath -Destination $combinedTarget -Force }
throw
}
# Each run adds one full-size backup; keep only the newest few so a recurring scheduled job
# doesn't silently fill the disk.
$staleBackups = Get-ChildItem -LiteralPath $installPath -Filter "$khdbName.bak-*" -File -ErrorAction SilentlyContinue |
Sort-Object Name -Descending | Select-Object -Skip $backupRetentionCount
foreach ($stale in $staleBackups) {
try { Remove-Item -LiteralPath $stale.FullName -Force } catch { Write-Warning "Could not remove old backup '$($stale.FullName)': $($_.Exception.Message)" }
}
[System.IO.File]::WriteAllText($buildMarkerPath, $manifestHash, [System.Text.UTF8Encoding]::new($false))
Write-Host ("KHDB merged file refreshed at {0}" -f $combinedTarget)
}
+28
View File
@@ -181,6 +181,34 @@ Describe 'Update-ElysiumKhdb (incremental sync against a fake S3 store)' {
'00112233445566778899AABBCCDDEEFF', '00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 'ABFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')
}
It 'keeps one backup by default, honours KhdbBackupCount, and rejects a bad value' {
$settingsFile = Join-Path $root 'ElysiumSettings.txt'
$original = Get-Content -LiteralPath $settingsFile
$backups = { @(Get-ChildItem -LiteralPath $root -Filter 'khdb.txt.bak-*') }
$ab = 'ABFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF'
try {
(& $backups).Count | Should -Be 1 # left by the previous test's rebuild
$previous = Get-Content -LiteralPath $khdb
Start-Sleep -Milliseconds 1100 # backup names have 1 s resolution
Publish-Shards @{ '00.txt' = @('00112233445566778899AABBCCDDEEFF'); 'ab.txt' = @($ab) }
Update-ElysiumKhdb -MaxParallelTransfers 1 6>$null
$found = & $backups
$found.Count | Should -Be 1
Get-Content -LiteralPath $found[0].FullName | Should -Be $previous
Add-Content -LiteralPath $settingsFile -Value 'KhdbBackupCount=0'
Publish-Shards @{ '00.txt' = @('00112233445566778899AABBCCDDEEFE'); 'ab.txt' = @($ab) }
Update-ElysiumKhdb -MaxParallelTransfers 1 6>$null
(& $backups).Count | Should -Be 0
Get-Content -LiteralPath $khdb | Should -Be @('00112233445566778899AABBCCDDEEFE', $ab)
Set-Content -LiteralPath $settingsFile -Value ($original + 'KhdbBackupCount=many')
{ Update-ElysiumKhdb -MaxParallelTransfers 1 6>$null } | Should -Throw '*KhdbBackupCount*'
} finally {
Set-Content -LiteralPath $settingsFile -Value $original
}
}
It 'fails the run and keeps the previous KHDB when a shard does not match its checksum' {
$before = Get-Content -LiteralPath $khdb
Publish-Shards @{ '00.txt' = @('00112233445566778899AABBCCDDEEFF'); 'ab.txt' = @('ABFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') }