config-central/src/Core.psm1

279 lines
18 KiB
PowerShell

Set-StrictMode -Version Latest
function New-BaseResult {
param([string]$Command)
[ordered]@{ command = $Command; succeeded = $true; exitCode = 0; revision = $null; operations = @(); warnings = @() }
}
function Get-OperationPlan {
param([string]$Machine, [string]$RepositoryRoot, $Paths, [switch]$ConfigsOnly)
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
$state = Read-JsonState -Path $Paths.State -Default ([ordered]@{ schemaVersion = 1; configs = [ordered]@{} })
if (-not $state.Contains('configs')) { $state.configs = [ordered]@{} }
$effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine
$packagePlan = @()
if (-not $ConfigsOnly) {
$wingetPackages = @($effective.packages | Where-Object { -not $_.PSObject.Properties['provider'] -or $_.provider -eq 'winget' })
$inventory = if ($wingetPackages.Count) { Get-WingetInventory } else { @{} }
$packagePlan = @(Get-PackagePlan -Packages $effective.packages -Inventory $inventory -DataRoot $Paths.Root)
}
$configPlan = @(Get-ConfigPlan -Configs $effective.configs -RepositoryRoot $RepositoryRoot -State $state -Settings $settings)
[pscustomobject]@{ effective = $effective; packages = $packagePlan; configs = $configPlan; state = $state; settings = $settings }
}
function Get-SoftwareUpdatePlan {
param([string]$Machine, [string]$RepositoryRoot, $Paths)
$state = Read-JsonState -Path $Paths.State -Default ([ordered]@{ schemaVersion = 1; configs = [ordered]@{} })
if (-not $state.Contains('configs')) { $state.configs = [ordered]@{} }
$effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine
$portablePackages = @($effective.packages | Where-Object { $_.PSObject.Properties['provider'] -and $_.provider -eq 'portable' })
$wingetPackages = @($effective.packages | Where-Object { -not $_.PSObject.Properties['provider'] -or $_.provider -eq 'winget' })
$inventory = if ($wingetPackages.Count) { Get-WingetInventory } else { @{} }
$packagePlan = [System.Collections.Generic.List[object]]::new()
foreach ($package in @($portablePackages) + @($wingetPackages)) {
try {
$selected = if ($package.PSObject.Properties['provider'] -and $package.provider -eq 'portable') {
Resolve-PackageRelease -Package $package
}
else { $package }
foreach ($operation in @(Get-PackagePlan -Packages @($selected) -Inventory $inventory -DataRoot $Paths.Root)) { $packagePlan.Add($operation) }
}
catch {
$packagePlan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'Failed'; reason = "Release lookup failed: $($_.Exception.Message)"; package = $package })
}
}
[pscustomobject]@{ effective = $effective; packages = @($packagePlan); configs = @(); state = $state }
}
function Invoke-Doctor {
param([string]$Machine, [string]$RepositoryRoot, $Paths)
$checks = [System.Collections.Generic.List[object]]::new()
function Add-Check([string]$Name, [bool]$Passed, [string]$Message, [bool]$Required = $true) {
$checks.Add([pscustomobject]@{ name = $Name; passed = $Passed; required = $Required; message = $Message })
}
Add-Check 'Windows' ($IsWindows) $(if ($IsWindows) { [Environment]::OSVersion.VersionString } else { 'Config Central applies only on Windows.' })
Add-Check 'PowerShell' ($PSVersionTable.PSVersion.Major -ge 7) "PowerShell $($PSVersionTable.PSVersion)"
Add-Check 'Git' ([bool](Get-Command git.exe -ErrorAction SilentlyContinue)) $(if (Get-Command git.exe -ErrorAction SilentlyContinue) { (& git.exe --version) -join ' ' } else { 'git.exe is missing.' })
Add-Check 'WinGet' ([bool](Get-Command winget.exe -ErrorAction SilentlyContinue)) $(if (Get-Command winget.exe -ErrorAction SilentlyContinue) { (& winget.exe --version) -join ' ' } else { 'winget.exe is missing.' })
Add-Check 'Repository' (Test-Path -LiteralPath (Join-Path $RepositoryRoot 'schemas/profile.schema.json')) $RepositoryRoot
try {
Initialize-ConfigCentralData $Paths
$probe = Join-Path $Paths.Root ".write-probe-$PID"
[System.IO.File]::WriteAllText($probe, 'ok'); Remove-Item -LiteralPath $probe -Force
Add-Check 'Data directory' $true $Paths.Root
}
catch { Add-Check 'Data directory' $false $_.Exception.Message }
if (Get-Command winget.exe -ErrorAction SilentlyContinue) {
$sourceOutput = & winget.exe source list --disable-interactivity 2>&1
Add-Check 'WinGet sources' ($LASTEXITCODE -eq 0) ($sourceOutput -join [Environment]::NewLine)
}
if (-not [string]::IsNullOrWhiteSpace($Machine)) {
try { [void](Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine); Add-Check 'Machine manifest' $true $Machine }
catch { Add-Check 'Machine manifest' $false $_.Exception.Message }
}
$failed = @($checks | Where-Object { $_.required -and -not $_.passed })
$result = New-BaseResult 'doctor'
$result.operations = @($checks)
if ($failed.Count -gt 0) { $result.succeeded = $false; $result.exitCode = 3 }
return [pscustomobject]$result
}
function Invoke-ApplyPlan {
param($Plan, [string]$Machine, [string]$RepositoryRoot, $Paths, [string]$Revision, [switch]$ForceConfigs, [string]$Command = 'apply')
$result = New-BaseResult $Command
$result.revision = $Revision
$lock = $null
try { $lock = Enter-ApplyLock -Paths $Paths }
catch { $result.succeeded = $false; $result.exitCode = 10; $result.warnings = @($_.Exception.Message); return [pscustomobject]$result }
$run = New-RunContext -Paths $Paths -Command $Command -Revision $Revision
$failedPackages = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$rebootRequired = $false
try {
$userOperations = @($Plan.packages | Where-Object { -not $_.package.PSObject.Properties['scope'] -or $_.package.scope -eq 'user' })
$machineOperations = @($Plan.packages | Where-Object { $_.package.PSObject.Properties['scope'] -and $_.package.scope -eq 'machine' })
$packageResults = [System.Collections.Generic.List[object]]::new()
foreach ($operation in $userOperations) { $packageResults.Add((Invoke-PackageOperation -Operation $operation -LogPath $run.logPath)) }
try {
foreach ($item in @(Invoke-ElevatedPackageBatch -Operations $machineOperations -RepositoryRoot $RepositoryRoot -Paths $Paths -LogPath $run.logPath)) { $packageResults.Add($item) }
}
catch {
foreach ($operation in $machineOperations) { $packageResults.Add([pscustomobject]@{ name = $operation.name; status = 'Failed'; rebootRequired = $false; message = $_.Exception.Message }) }
}
foreach ($packageResult in $packageResults) {
[void](Add-RunResult -Run $run -Kind package -Name $packageResult.name -Status $packageResult.status -Message $packageResult.message)
if ($packageResult.status -in @('Failed', 'Conflict')) { [void]$failedPackages.Add($packageResult.name) }
if ($packageResult.PSObject.Properties['rebootRequired'] -and $packageResult.rebootRequired) { $rebootRequired = $true }
}
foreach ($operation in $Plan.configs) {
if ($operation.requiresPackage -and $failedPackages.Contains($operation.requiresPackage)) {
[void](Add-RunResult -Run $run -Kind config -Name $operation.name -Status Skipped -Message "Required package '$($operation.requiresPackage)' failed")
continue
}
if ($operation.requiresAdmin -and $operation.action -notin @('None', 'Adopt')) {
if ($operation.action -eq 'Conflict' -and -not $ForceConfigs) {
$configResult = [pscustomobject]@{ name = $operation.name; status = 'Conflict'; message = "$($operation.reason); use -ForceConfigs to back up and replace it" }
}
else {
try {
$configResult = Invoke-ElevatedConfigOperation -Operation $operation -RepositoryRoot $RepositoryRoot -Paths $Paths
$Plan.state.configs[$operation.name] = [ordered]@{ target = $operation.target; deployedHash = $operation.sourceHash; sourceHash = $operation.sourceHash; mode = $operation.mode; deployedAt = [DateTimeOffset]::UtcNow.ToString('o'); lastBackup = $configResult.backup }
Write-JsonAtomic -Path $Paths.State -Value $Plan.state
}
catch { $configResult = [pscustomobject]@{ name = $operation.name; status = 'Failed'; message = $_.Exception.Message } }
}
}
else { $configResult = Invoke-ConfigOperation -Operation $operation -Paths $Paths -State $Plan.state -Force:$ForceConfigs }
[void](Add-RunResult -Run $run -Kind config -Name $configResult.name -Status $configResult.status -Message $configResult.message)
}
$result.operations = @($run.results)
$failures = @($run.results | Where-Object status -in @('Failed', 'Conflict', 'Skipped'))
$result.succeeded = $failures.Count -eq 0
$result.exitCode = if (-not $result.succeeded) { 5 } elseif ($rebootRequired) { 6 } else { 0 }
if ($Command -eq 'apply') { $Plan.state.lastAppliedRevision = $Revision }
Complete-Run -Run $run -Paths $Paths -State $Plan.state -Succeeded $result.succeeded
return [pscustomobject]$result
}
finally { Exit-ApplyLock -Lock $lock -Paths $Paths }
}
function Invoke-SnapshotCommand {
param([string]$Snapshot, [string]$Machine, $Paths, [string]$Revision, [ValidateSet('apply', 'update-software')][string]$Command, [switch]$ConfigsOnly, [switch]$ForceConfigs)
$arguments = @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $Snapshot 'cc.ps1'), $Command, '-Machine', $Machine, '-DataRoot', $Paths.Root, '-RepositoryRoot', $Snapshot, '-Revision', $Revision, '-FromSnapshot', '-Json')
if ($ConfigsOnly) { $arguments += '-ConfigsOnly' }
if ($ForceConfigs) { $arguments += '-ForceConfigs' }
$text = & pwsh.exe @arguments
$exitCode = $LASTEXITCODE
try { $child = ($text -join [Environment]::NewLine) | ConvertFrom-Json -Depth 32 }
catch { throw "Snapshot command returned invalid output (exit $exitCode): $($text -join [Environment]::NewLine)" }
return $child
}
function Invoke-ConfigCentral {
param(
[string]$Command, [string]$Machine, [string]$Config, [switch]$ConfigsOnly,
[switch]$ForceConfigs, [string]$OutputPath, $Paths, [string]$RepositoryRoot, [switch]$FromSnapshot,
[string]$Revision
)
if ($Command -eq 'doctor') { return Invoke-Doctor -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths }
if ($Command -eq 'configs') {
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
$effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine
$result = New-BaseResult 'configs'
$result.operations = @(Get-ConfigLocations -Configs $effective.configs -RepositoryRoot $RepositoryRoot -Settings $settings -Name $Config)
return [pscustomobject]$result
}
if ($Command -eq 'capture') {
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
$effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine
$capture = Export-ConfigCapture -Configs $effective.configs -RepositoryRoot $RepositoryRoot -Settings $settings -Machine $Machine -Name $Config -OutputPath $OutputPath
$result = New-BaseResult 'capture'
$result.operations = @($capture.operations)
$result | Add-Member -NotePropertyName capturePath -NotePropertyValue $capture.path
return [pscustomobject]$result
}
if ($Command -eq 'restore') {
if ([string]::IsNullOrWhiteSpace($Config)) { throw 'restore requires -Config NAME.' }
$state = Read-JsonState -Path $Paths.State -Default ([ordered]@{})
$restore = Restore-ConfigBackup -Name $Config -Paths $Paths -State $state
$result = New-BaseResult 'restore'; $result.operations = @($restore); return [pscustomobject]$result
}
if ($Command -in @('schedule', 'unschedule')) {
$operation = if ($Command -eq 'schedule') {
Register-ConfigCentralSchedule -RepositoryRoot $RepositoryRoot -Machine $Machine -Paths $Paths
}
else { Unregister-ConfigCentralSchedule }
$result = New-BaseResult $Command; $result.operations = @($operation); return [pscustomobject]$result
}
if ($Command -eq 'sync') {
if ($FromSnapshot) { throw 'Nested sync from a snapshot is not allowed.' }
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
$remoteRevision = Resolve-RemoteRevision -RepositoryRoot $RepositoryRoot -Settings $settings
$snapshot = New-RepositorySnapshot -RepositoryRoot $RepositoryRoot -Revision $remoteRevision -Paths $Paths
return Invoke-SnapshotCommand -Snapshot $snapshot -Machine $Machine -Paths $Paths -Revision $remoteRevision -Command apply -ConfigsOnly:$ConfigsOnly -ForceConfigs:$ForceConfigs
}
if ($Command -eq 'update-software') {
if ($ConfigsOnly -or $ForceConfigs) { throw 'update-software does not accept config options.' }
if (-not $FromSnapshot) {
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
$remoteRevision = Resolve-RemoteRevision -RepositoryRoot $RepositoryRoot -Settings $settings
$snapshot = New-RepositorySnapshot -RepositoryRoot $RepositoryRoot -Revision $remoteRevision -Paths $Paths
$result = Invoke-SnapshotCommand -Snapshot $snapshot -Machine $Machine -Paths $Paths -Revision $remoteRevision -Command update-software
try { $selfUpdate = Update-RepositoryCheckout -RepositoryRoot $RepositoryRoot -Revision $remoteRevision }
catch {
$selfUpdate = [pscustomobject]@{ name = 'Config Central'; status = 'Failed'; message = $_.Exception.Message }
$result.succeeded = $false
$result.exitCode = 5
}
$result.operations = @($selfUpdate) + @($result.operations)
return $result
}
if ([string]::IsNullOrWhiteSpace($Revision)) { $Revision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot }
$softwarePlan = Get-SoftwareUpdatePlan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths
return Invoke-ApplyPlan -Plan $softwarePlan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -Revision $Revision -Command 'update-software'
}
if ([string]::IsNullOrWhiteSpace($Revision)) { $Revision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot }
$plan = Get-OperationPlan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -ConfigsOnly:$ConfigsOnly
if ($Command -eq 'apply') { return Invoke-ApplyPlan -Plan $plan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -Revision $Revision -ForceConfigs:$ForceConfigs }
$result = New-BaseResult $Command
$result.revision = $Revision
$result.operations = @($plan.packages) + @($plan.configs)
if ($Command -eq 'status') {
$drift = @($result.operations | Where-Object action -notin @('None', 'Warning'))
if ($drift.Count -gt 0) { $result.succeeded = $false; $result.exitCode = 4 }
$result | Add-Member -NotePropertyName lastRun -NotePropertyValue $(if ($plan.state.Contains('lastRun')) { $plan.state.lastRun } else { $null })
}
return [pscustomobject]$result
}
function Test-ResultColor {
-not [Console]::IsOutputRedirected -and $null -eq [Environment]::GetEnvironmentVariable('NO_COLOR')
}
function Write-ConfigCentralResult {
param($Result)
$useColor = Test-ResultColor
Write-Host "Config Central: $($Result.command)"
if ($Result.revision) { Write-Host "Revision: $($Result.revision)" }
foreach ($operation in @($Result.operations)) {
$state = if ($operation.PSObject.Properties['action']) { $operation.action } elseif ($operation.PSObject.Properties['status']) { $operation.status } elseif ($operation.PSObject.Properties['passed']) { if ($operation.passed) { 'OK' } else { 'FAIL' } } else { '-' }
$message = if ($operation.PSObject.Properties['reason']) { $operation.reason } else { $operation.message }
$color = switch ($state) {
{ $_ -in @('Failed', 'FAIL') } { 'Red'; break }
{ $_ -in @('Conflict', 'Skipped', 'Warning', 'Missing') } { 'Yellow'; break }
{ $_ -in @('Succeeded', 'OK', 'Captured') } { 'Green'; break }
{ $_ -in @('Unchanged', 'None') } { 'DarkGray'; break }
default { 'Cyan' }
}
if ($useColor) {
Write-Host ("{0,-10}" -f $state) -ForegroundColor $color -NoNewline
Write-Host (" {0,-24} {1}" -f $operation.name, $message)
}
else {
Write-Host ("{0,-10} {1,-24} {2}" -f $state, $operation.name, $message)
}
}
foreach ($warning in @($Result.warnings)) {
if ($useColor) { Write-Host "Warning: $warning" -ForegroundColor Yellow }
else { Write-Host "Warning: $warning" }
}
}
function Show-ConfigCentralMenu {
param([string]$Machine, [string]$DataRoot, [string]$RepositoryRoot)
Write-Host 'Config Central'
Write-Host '1. Plan 2. Update software 3. Sync 4. Status 5. Doctor 6. Schedule 7. Config paths 8. Capture configs Q. Quit'
$choice = Read-Host 'Select'
$command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'update-software' } '3' { 'sync' } '4' { 'status' } '5' { 'doctor' } '6' { 'schedule' } '7' { 'configs' } '8' { 'capture' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } }
$arguments = @($command, '-RepositoryRoot', $RepositoryRoot)
if ($Machine) { $arguments += @('-Machine', $Machine) }
if ($DataRoot) { $arguments += @('-DataRoot', $DataRoot) }
& (Join-Path $RepositoryRoot 'cc.ps1') @arguments
}
Export-ModuleMember -Function Get-OperationPlan, Get-SoftwareUpdatePlan, Invoke-ConfigCentral, Write-ConfigCentralResult, Show-ConfigCentralMenu