Files
cbb-refresh-verify-795/CBBRefresh.Core.psm1
T

270 lines
9.8 KiB
PowerShell

Set-StrictMode -Version Latest
$script:RequiredStates = @(
'library_item_present',
'verify_result',
'cbb_status_flag',
'error_state'
)
function Get-CbbRefreshRequiredStates {
return @($script:RequiredStates)
}
function Read-CbbRefreshStatus {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
throw "Status file does not exist: $Path"
}
try {
$status = Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json -ErrorAction Stop
}
catch {
throw "Status file is not valid UTF-8 JSON: $Path"
}
if ($null -eq $status -or $status.schemaVersion -ne 1 -or $null -eq $status.states) {
throw 'Status must contain schemaVersion=1 and states.'
}
foreach ($name in $script:RequiredStates) {
$property = $status.states.PSObject.Properties[$name]
if ($null -eq $property) {
throw "Status is missing state: $name"
}
if ([string]$property.Value -notin @('red', 'yellow', 'green', 'unknown')) {
throw "Unsupported state color for ${name}: $($property.Value)"
}
}
return $status
}
function Get-CbbRefreshNextAction {
[CmdletBinding()]
param([Parameter(Mandatory)]$Status)
foreach ($name in $script:RequiredStates) {
$color = [string]$Status.states.PSObject.Properties[$name].Value
if ($color -in @('red', 'yellow')) {
return [pscustomobject]@{
State = $name
Color = $color
Action = switch ($name) {
'library_item_present' { 'locate_uploaded_cbb' }
'verify_result' { 'run_cbb_verify' }
'cbb_status_flag' { 'confirm_cbb_green_flag' }
'error_state' { 'resolve_cbb_verify_error' }
}
}
}
if ($color -eq 'unknown') {
return [pscustomobject]@{
State = $name
Color = $color
Action = 'blocked_unknown_state'
}
}
}
return $null
}
function Test-CbbRefreshAllGreen {
[CmdletBinding()]
param([Parameter(Mandatory)]$Status)
foreach ($name in $script:RequiredStates) {
if ([string]$Status.states.PSObject.Properties[$name].Value -ne 'green') {
return $false
}
}
return $true
}
function New-CbbRefreshVerification {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Status,
[Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Observations
)
$next = Get-CbbRefreshNextAction -Status $Status
$allGreen = Test-CbbRefreshAllGreen -Status $Status
$issues = New-Object 'System.Collections.Generic.List[string]'
if ($null -ne $next) {
[void]$issues.Add("pending_action:$($next.Action)")
}
foreach ($observation in @($Observations)) {
if ($null -eq $observation -or [string]::IsNullOrWhiteSpace([string]$observation.timestampUtc)) {
[void]$issues.Add('observation_missing_timestamp')
}
if ([string]$observation.result -in @('error', 'timeout', 'unknown')) {
[void]$issues.Add("observation_$($observation.result)")
}
}
[pscustomobject]@{
schemaVersion = 1
generatedAtUtc = [datetime]::UtcNow.ToString('o')
result = if ($allGreen -and $issues.Count -eq 0) { 'PASS' } else { 'BLOCKED' }
allGreen = $allGreen
nextAction = if ($null -eq $next) { $null } else { $next.Action }
issues = @($issues)
observationCount = @($Observations).Count
}
}
function Write-CbbRefreshVerification {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Verification,
[Parameter(Mandatory)][string]$Path
)
$parent = Split-Path -Parent ([IO.Path]::GetFullPath($Path))
if ($parent -and -not (Test-Path -LiteralPath $parent -PathType Container)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
$temporary = "$Path.tmp-$([guid]::NewGuid().ToString('N'))"
try {
$Verification | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $temporary -Encoding UTF8
Move-Item -LiteralPath $temporary -Destination $Path -Force
}
finally {
if (Test-Path -LiteralPath $temporary -PathType Leaf) {
Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue
}
}
}
function Get-CbbReuseBlockImporterPath {
[CmdletBinding()]
param([string]$MentorBin = $env:SDD_LM_BIN)
if ([string]::IsNullOrWhiteSpace($MentorBin)) {
throw 'Mentor bin is not configured. Set SDD_LM_BIN or pass -MentorBin.'
}
$path = Join-Path ([IO.Path]::GetFullPath($MentorBin)) 'ReuseBlockImporter.exe'
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
throw "ReuseBlockImporter.exe was not found: $path"
}
return [IO.Path]::GetFullPath($path)
}
function Invoke-CbbReuseBlockContentCheck {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$LmcFile,
[Parameter(Mandatory)][string]$BlockName,
[Parameter(Mandatory)][string]$LibSpec,
[Parameter(Mandatory)][string]$DmsLoginConfig,
[string]$MentorBin = $env:SDD_LM_BIN,
[string]$ReportPath,
[int]$TimeoutSeconds = 120
)
$lmc = [IO.Path]::GetFullPath($LmcFile)
if (-not (Test-Path -LiteralPath $lmc -PathType Leaf)) {
throw "Library file was not found: $lmc"
}
if ([string]::IsNullOrWhiteSpace($BlockName)) { throw 'BlockName cannot be empty.' }
if ([string]::IsNullOrWhiteSpace($LibSpec)) { throw 'LibSpec cannot be empty.' }
if ([string]::IsNullOrWhiteSpace($DmsLoginConfig)) { throw 'DmsLoginConfig cannot be empty.' }
if ($TimeoutSeconds -lt 1) { throw 'TimeoutSeconds must be at least 1.' }
$exe = Get-CbbReuseBlockImporterPath -MentorBin $MentorBin
if ([string]::IsNullOrWhiteSpace($ReportPath)) {
$logDir = Join-Path ([IO.Path]::GetDirectoryName($lmc)) 'LogFiles'
# Match Mentor's safeName procedure: Windows-invalid key characters become '_'.
$safeBlockName = ($BlockName -replace '[\\/:*?"<>|]', '_')
$ReportPath = Join-Path $logDir ("restorerb_RULP_{0}_contents.log" -f $safeBlockName)
}
$report = [IO.Path]::GetFullPath($ReportPath)
$reportDir = Split-Path -Parent $report
if ($reportDir -and -not (Test-Path -LiteralPath $reportDir -PathType Container)) {
New-Item -ItemType Directory -Path $reportDir -Force | Out-Null
}
$arguments = @('-lmcFile', $lmc, '-blockName', $BlockName, '-logicalType', 'LP',
'-chkContents', '-libSpec', $LibSpec, '-dmsLoginConfig', $DmsLoginConfig)
$quote = {
param([string]$value)
if ($value -notmatch '[\s"]') { return $value }
return '"' + ($value -replace '(\\*)"', '$1$1\"' -replace '(\\+)$', '$1$1') + '"'
}
$psi = [Diagnostics.ProcessStartInfo]::new()
$psi.FileName = $exe
$psi.Arguments = (($arguments | ForEach-Object { & $quote ([string]$_) }) -join ' ')
$psi.WorkingDirectory = [IO.Path]::GetDirectoryName($lmc)
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$startedUtc = [datetime]::UtcNow
$process = [Diagnostics.Process]::new()
$process.StartInfo = $psi
try {
if (-not $process.Start()) { throw 'ReuseBlockImporter process did not start.' }
# Drain both pipes while the child runs. Reading after WaitForExit can
# deadlock once the child fills the pipe buffer, which would be
# misreported as a timeout.
$stdoutTask = $process.StandardOutput.ReadToEndAsync()
$stderrTask = $process.StandardError.ReadToEndAsync()
if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
try { $process.Kill() } catch { }
$result = 'timeout'
$exitCode = $null
}
else {
$result = 'unknown'
$exitCode = $process.ExitCode
}
$stdout = ''
$stderr = ''
# Bounded drain: a grandchild holding the pipe open must not hang the
# check. Partial output is dropped rather than blocking forever.
try { if ($stdoutTask.Wait(5000)) { $stdout = [string]$stdoutTask.Result } } catch { }
try { if ($stderrTask.Wait(5000)) { $stderr = [string]$stderrTask.Result } } catch { }
}
catch {
$result = 'error'
$exitCode = $null
$stdout = ''
$stderr = $_.Exception.ToString()
}
finally {
$process.Dispose()
}
$combined = @($stdout, $stderr) -join "`r`n"
[IO.File]::WriteAllText($report, $combined, [Text.UTF8Encoding]::new($false))
if ($result -eq 'unknown') {
if ($exitCode -eq 0 -and $combined -match '(?i)completed successfully' -and $combined -notmatch '(?i)failed|error') {
$result = 'pass'
}
elseif ($combined -match '(?i)failed|error|cannot connect|bad data') {
$result = 'fail'
}
elseif ($exitCode -eq 0) {
$result = 'unknown'
}
else {
$result = 'fail'
}
}
[pscustomobject]@{
operation = 'reuse_block_content_check'
lmcFile = $lmc
blockName = $BlockName
logicalType = 'LP'
libSpec = $LibSpec
reportPath = $report
executable = $exe
startedAtUtc = $startedUtc.ToString('o')
completedAtUtc = [datetime]::UtcNow.ToString('o')
exitCode = $exitCode
result = $result
output = $combined
}
}
Export-ModuleMember -Function Get-CbbRefreshRequiredStates, Read-CbbRefreshStatus, Get-CbbRefreshNextAction, Test-CbbRefreshAllGreen, New-CbbRefreshVerification, Write-CbbRefreshVerification, Get-CbbReuseBlockImporterPath, Invoke-CbbReuseBlockContentCheck