Modules/businessdev.ALbuild.Apps/Public/Publish-BcContainerApp.ps1
|
function Publish-BcContainerApp { <# .SYNOPSIS Publishes an AL app (.app) to a Business Central container, optionally syncing/installing. .DESCRIPTION Copies the .app into the container and publishes it with the BC server management cmdlets, then optionally synchronises and installs it. Requires Windows + Docker. .PARAMETER Name Container name. .PARAMETER AppFile Path to the .app file on the host. .PARAMETER SkipVerification Publish without signature verification (for unsigned development apps). .PARAMETER Sync Synchronise the app after publishing. .PARAMETER Install Install the app after synchronising. .PARAMETER SyncMode Schema sync mode: Add (default), Clean, Development or ForceSync. Clean never syncs the NEW version with Clean (that removes its schema and leaves it NotSynced): it clean-syncs the versions -IfExists removes, dropping their data, and syncs the new version with Add. .PARAMETER IfExists What to do when a version of this app is already published: fail - stop with VERSION_ALREADY_PUBLISHED when the same version is published. unpublish - uninstall and unpublish every published version first. force-sync - uninstall and unpublish the same version (its data stays), then sync with ForceSync. upgrade - publish as is; a data upgrade runs when the tenant holds data of an older version. none - no check (default). Apps that depend on a removed app are removed first when -ReplaceableAppId lists them; any other dependent stops the publish with DEPENDENT_BLOCKS_UNPUBLISH. .PARAMETER ReplaceableAppId App ids that -IfExists may uninstall and unpublish because they depend on this app. Pass the ids of every app in the same deployment (e.g. the test app), which is published again next. .PARAMETER Scope Global (default) or Tenant. .PARAMETER ServerInstance BC server instance. Default 'BC'. .PARAMETER Tenant Tenant. Default 'default'. .PARAMETER DockerExecutable The Docker executable to use (default 'docker'). .PARAMETER OperationTimeoutSeconds Maximum seconds to allow the publish/sync/install before abandoning it and throwing. Prevents a hung operation (e.g. a deadlocked schema sync) from freezing the build. Default 600. .PARAMETER Development Publish through the container's development endpoint (like VS Code) as a replaceable development extension, re-publishable without a version bump. -SyncMode maps to the endpoint's schema update mode. Requires -Credential. .PARAMETER Credential BC user that authenticates to the development endpoint. Required with -Development. .EXAMPLE Publish-BcContainerApp -Name bld -AppFile .\output\MyApp.app -SkipVerification -Sync -Install .EXAMPLE Publish-BcContainerApp -Name bld -AppFile .\output\MyApp.app -Development -Credential $cred -SyncMode ForceSync #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseUsingScopeModifierInNewRunspaces', '', Justification = 'The Start-Job scriptblock declares a param() block bound positionally via -ArgumentList; $using: is intentionally not used.')] [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [Alias('ContainerName')] [string] $Name, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $AppFile, [switch] $SkipVerification, [switch] $Sync, [switch] $Install, [ValidateSet('Add', 'Clean', 'Development', 'ForceSync')] [string] $SyncMode = 'Add', [ValidateSet('none', 'fail', 'unpublish', 'force-sync', 'upgrade')] [string] $IfExists = 'none', [string[]] $ReplaceableAppId = @(), [ValidateSet('Global', 'Tenant')] [string] $Scope = 'Global', [string] $ServerInstance = 'BC', [string] $Tenant = 'default', [int] $OperationTimeoutSeconds = 600, [string] $DockerExecutable = 'docker', # Publish via the container's development endpoint (like VS Code / BcContainerHelper -useDevEndpoint): # the app is published as a replaceable development extension - re-publishable without a version bump, # which is what test environments need. Requires -Credential (a BC user for the dev endpoint). [switch] $Development, [pscredential] $Credential ) if (-not (Test-Path -LiteralPath $AppFile)) { throw "App file not found: '$AppFile'." } if (-not $PSCmdlet.ShouldProcess($Name, "Publish $(Split-Path $AppFile -Leaf)")) { return } # force-sync is the policy's name for the ForceSync schema mode. if ($IfExists -eq 'force-sync') { $SyncMode = 'ForceSync' } if ($Development) { # Development (dev-endpoint) publish - the app is published as a replaceable ModernDev extension # (re-publishable without a version bump), so we do NOT run the Publish/Sync/Install-NAVApp flow. # The POST is made from the HOST to the container's IP: the in-container loopback to the SSL dev # endpoint is rejected at the TLS layer, whereas host->container-IP works (BcContainerHelper does # the same with -useDevEndpoint). if (-not $Credential) { throw 'A development (dev-endpoint) publish requires -Credential (the BC user to authenticate to the dev endpoint).' } # The dev endpoint's schema-update modes are synchronize|recreate|forcesync; map from -SyncMode. $schemaUpdateMode = switch ($SyncMode) { 'ForceSync' { 'forcesync' } 'Clean' { 'recreate' } default { 'synchronize' } } # Resolve the developer-services port + SSL from the container's own CustomSettings.config # (authoritative regardless of which tool created the container). $cfgRaw = Invoke-BcContainerCommand -ContainerName $Name -DockerExecutable $DockerExecutable -ScriptBlock { $c = Get-ChildItem -Path 'C:\Program Files\Microsoft Dynamics*\*\Service\CustomSettings.config' -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $c) { '|' } else { [xml]$x = Get-Content -LiteralPath $c.FullName $g = { param($k) $n = $x.SelectSingleNode("//appSettings/add[@key='$k']"); if ($n) { $n.value } } "$(& $g 'DeveloperServicesPort')|$(& $g 'DeveloperServicesSSLEnabled')" } } $cfgLine = @("$cfgRaw" -split "`r?`n" | Where-Object { $_ -match '\|' } | Select-Object -Last 1) $parts = "$cfgLine".Trim() -split '\|', 2 $port = if ($parts[0].Trim()) { $parts[0].Trim() } else { '7049' } $useSsl = ($parts.Count -gt 1) -and ($parts[1].Trim() -eq 'true') # The dev endpoint is reachable at the container's IP (host->container NAT); fall back to the name. $ipResult = Invoke-BcDocker -DockerExecutable $DockerExecutable -PassThru -Quiet -Arguments @('inspect', '-f', '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}', $Name) $ip = if ($ipResult.Success) { "$($ipResult.StdOut)".Trim() } else { '' } $hostForUrl = if ($ip) { $ip } else { $Name } $proto = if ($useSsl) { 'https' } else { 'http' } $devUrl = "$proto`://$hostForUrl`:$port/$ServerInstance/dev/apps?SchemaUpdateMode=$schemaUpdateMode" Write-ALbuildLog "Dev-publishing '$(Split-Path -Path $AppFile -Leaf)' to $devUrl ..." Publish-BcAppToDevEndpoint -Url $devUrl -AppFile $AppFile -Credential $Credential -IgnoreSslErrors:$useSsl Write-ALbuildLog -Level Success "Dev-published '$(Split-Path -Path $AppFile -Leaf)' to the development endpoint of '$Name'." return } $containerPath = Copy-BcFileToContainer -Name $Name -Source $AppFile -DockerExecutable $DockerExecutable $script = { $info = Get-NAVAppInfo -Path $Path # Each timeout-bounded child job is a fresh runspace that does not inherit the imported NAV cmdlets, # so it re-imports the exact assembly the session already loaded (resolved centrally, per BC version # and PowerShell edition, in ConvertTo-BcEncodedCommand). Reusing that loaded path keeps the version # logic in one place and works whether the session runs under Windows PowerShell or pwsh. $navMgmtPath = (Get-Command Publish-NAVApp -ErrorAction SilentlyContinue).Module.Path # The newest error the NAV server logged since $Since. A server-side failure (sync conflict, # recompile) often lands only in this log while the cmdlet reports nothing useful. Best effort. function Get-BcNavServerError { param([datetime] $Since) try { $evt = Get-WinEvent -FilterHashtable @{ LogName = 'Application'; ProviderName = "MicrosoftDynamicsNavServer`$$ServerInstance"; Level = 2; StartTime = $Since } -MaxEvents 1 -ErrorAction SilentlyContinue if (-not $evt) { return '' } $msg = if ($evt.Message -match '(?s)\bMessage\b\s*(.+)$') { $matches[1] } else { $evt.Message } return ($msg -replace '\x1b\[[0-9;]*m', '' -replace '\s+', ' ').Trim() } catch { return '' } } # Show a single operation's job as a growing-dots line, then 'OK' / 'FAILED <complete error>' # / 'TIMED OUT', so EACH step is shown separately and it is obvious which one hangs. The # caller builds the job with explicit scalar arguments (a robust Start-Job pattern). function Wait-BcStepJob { param([System.Management.Automation.Job] $Job, [string] $Label) $stepStart = Get-Date [System.Console]::Out.Write("$Label "); [System.Console]::Out.Flush() $elapsed = 0 while (-not (Wait-Job $Job -Timeout $PollSeconds)) { $elapsed += $PollSeconds if ($elapsed -ge $OperationTimeoutSeconds) { Stop-Job $Job -ErrorAction SilentlyContinue Remove-Job $Job -Force -ErrorAction SilentlyContinue [System.Console]::Out.WriteLine("TIMED OUT after $OperationTimeoutSeconds s"); [System.Console]::Out.Flush() # A stalled publish/sync is usually a *server-side* operation that failed (e.g. an # extension recompile) whose real error only lands in the NAV server event log - # the cmdlet just never returns. Surface that log entry so the reason is visible. $serverErr = Get-BcNavServerError -Since $stepStart if ($serverErr) { [System.Console]::Out.WriteLine("NAV server log: $serverErr"); [System.Console]::Out.Flush() return [PSCustomObject]@{ Ok = $false; Error = "$Label timed out after $OperationTimeoutSeconds s. NAV server log: $serverErr" } } return [PSCustomObject]@{ Ok = $false; Error = "$Label timed out after $OperationTimeoutSeconds s (operation hung)" } } [System.Console]::Out.Write('. '); [System.Console]::Out.Flush() } try { # The job emits warnings as 'ALBUILD-WARN:' data lines (a child job's warnings are # written straight to the host, so they cannot be redirected from the parent). Print # 'OK' on the step line, then each warning on its own line; the rest is real output. $results = Receive-Job $Job -ErrorAction Stop $jobWarn = @($results | Where-Object { "$_" -like 'ALBUILD-WARN:*' } | ForEach-Object { "$_" -replace '^ALBUILD-WARN:', '' }) $out = @($results | Where-Object { "$_" -notlike 'ALBUILD-WARN:*' }) [System.Console]::Out.WriteLine('OK'); [System.Console]::Out.Flush() foreach ($w in $jobWarn) { [System.Console]::Out.WriteLine(" WARNING: $(($w -replace '\s+', ' ').Trim())"); [System.Console]::Out.Flush() } $txt = if ($out) { ($out | Out-String).Trim() } else { '' } if ($txt) { [System.Console]::Out.WriteLine($txt); [System.Console]::Out.Flush() } return [PSCustomObject]@{ Ok = $true; Error = '' } } catch { [System.Console]::Out.WriteLine('FAILED'); [System.Console]::Out.Flush() # Show the COMPLETE error (full compiler/server output), only ANSI-stripped. $full = ("$($_.Exception.Message)" -replace '\x1b\[[0-9;]*m', '').TrimEnd() [System.Console]::Out.WriteLine($full); [System.Console]::Out.Flush() $first = @(($full -split "`r?`n") | Where-Object { $_.Trim() }) $first = if ($first.Count -gt 0) { $first[0].Trim() } else { 'failed' } return [PSCustomObject]@{ Ok = $false; Error = "$Label failed: $first" } } finally { Remove-Job $Job -Force -ErrorAction SilentlyContinue } } $app = "'$($info.Name) $($info.Version)'" # Run one NAV cmdlet call as a timeout-bounded step; a failure ends the script with ALBUILD-ERROR. function Invoke-BcNavStep { param([string] $Label, [string] $Command, [hashtable] $Arguments) $job = Start-Job -ScriptBlock { param($module, $cmd, $argsJson) if ($module) { Import-Module $module -DisableNameChecking -ErrorAction Stop } $a = @{} foreach ($p in ($argsJson | ConvertFrom-Json).PSObject.Properties) { $a[$p.Name] = $p.Value } $wv = @() & $cmd @a -ErrorAction Stop -WarningVariable +wv -WarningAction SilentlyContinue foreach ($x in $wv) { "ALBUILD-WARN:$x" } } -ArgumentList $navMgmtPath, $Command, ($Arguments | ConvertTo-Json -Compress) $r = Wait-BcStepJob -Job $job -Label $Label if (-not $r.Ok) { [System.Console]::Out.WriteLine("ALBUILD-ERROR:$($r.Error)"); [System.Console]::Out.Flush(); exit 1 } } # -IfExists: clear what is already published BEFORE publishing, so a rebuilt package with an # unchanged version replaces the old one instead of failing "same App ID and Version". if ($IfExists -in @('fail', 'unpublish', 'force-sync')) { $published = @(Get-NAVAppInfo -ServerInstance $ServerInstance) $sameVersion = @($published | Where-Object { "$($_.AppId)" -eq "$($info.AppId)" -and "$($_.Version)" -eq "$($info.Version)" }) if ($IfExists -eq 'fail') { if ($sameVersion.Count -gt 0) { [System.Console]::Out.WriteLine("ALBUILD-ERROR:VERSION_ALREADY_PUBLISHED: $app is already published. Use -IfExists unpublish (CLI: --if-exists unpublish) to replace it.") [System.Console]::Out.Flush(); exit 1 } } else { # unpublish removes every version; force-sync only the colliding one (keeping its data). # @() around the whole 'if': an if-expression unrolls a one-element array into a scalar. $targets = @(if ($IfExists -eq 'unpublish') { $published | Where-Object { "$($_.AppId)" -eq "$($info.AppId)" } } else { $sameVersion }) if ($targets.Count -gt 0) { # Dependency ids per published app. The listing carries no Dependencies when the NAV # assembly is loaded directly (BC 29), only the per-version detail does. Microsoft apps # cannot depend on a partner app, so only the others are looked up. $depIds = @{} foreach ($p in $published) { $key = "$($p.AppId)|$($p.Version)" $depIds[$key] = @() if ("$($p.Publisher)" -eq 'Microsoft') { continue } $deps = @(if ($p.PSObject.Properties.Name -contains 'Dependencies') { $p.Dependencies }) if ($deps.Count -eq 0) { try { $deps = @((Get-NAVAppInfo -ServerInstance $ServerInstance -Name "$($p.Name)" -Publisher "$($p.Publisher)" -Version "$($p.Version)").Dependencies) } catch { $deps = @() } } $depIds[$key] = @($deps | Where-Object { $_ } | ForEach-Object { "$($_.AppId)".ToLowerInvariant() }) } $dependsOn = { param($p, $ids) @($depIds["$($p.AppId)|$($p.Version)"] | Where-Object { $ids -contains $_ }).Count -gt 0 } # Everything that depends on a target, transitively: it must go first, or BC refuses # to uninstall/unpublish the target. $removeIds = @("$($info.AppId)".ToLowerInvariant()) do { $added = $false foreach ($p in $published) { $id = "$($p.AppId)".ToLowerInvariant() if ($removeIds -contains $id) { continue } if (& $dependsOn $p $removeIds) { $removeIds += $id; $added = $true } } } while ($added) $allowed = @($ReplaceableAppIds -split ';' | Where-Object { $_ } | ForEach-Object { $_.Trim().ToLowerInvariant() }) + "$($info.AppId)".ToLowerInvariant() $dependents = @($published | Where-Object { $removeIds -contains "$($_.AppId)".ToLowerInvariant() -and "$($_.AppId)" -ne "$($info.AppId)" }) $foreign = @($dependents | Where-Object { $allowed -notcontains "$($_.AppId)".ToLowerInvariant() }) if ($foreign.Count -gt 0) { $names = (@($foreign | ForEach-Object { "'$($_.Name)' $($_.Version)" }) -join ', ') [System.Console]::Out.WriteLine("ALBUILD-ERROR:DEPENDENT_BLOCKS_UNPUBLISH: $app cannot be replaced because $names depend(s) on it and are not part of this deployment. Uninstall and unpublish them first, or deploy them together with this app.") [System.Console]::Out.Flush(); exit 1 } # Removal order: dependents before the apps they depend on. $pending = @(@($targets) + @($dependents)) $ordered = @() while ($pending.Count -gt 0) { $next = @($pending | Where-Object { $cand = $_ $candId = @("$($cand.AppId)".ToLowerInvariant()) @($pending | Where-Object { $_ -ne $cand -and (& $dependsOn $_ $candId) }).Count -eq 0 }) if ($next.Count -eq 0) { $next = @($pending[0]) } # dependency cycle: should not happen; do not loop forever $ordered += $next $pending = @($pending | Where-Object { $next -notcontains $_ }) } $installed = @{} try { foreach ($t in @(Get-NAVAppInfo -ServerInstance $ServerInstance -Tenant $Tenant -TenantSpecificProperties)) { if ($t.PSObject.Properties.Name -contains 'IsInstalled' -and $t.IsInstalled) { $installed["$($t.AppId)|$($t.Version)".ToLowerInvariant()] = $true } } } catch { } $clean = ($Mode -eq 'Clean') [System.Console]::Out.WriteLine("Replacing $app (if-exists $IfExists$(if ($clean) { ', clean' })): removing " + (@($ordered | ForEach-Object { "'$($_.Name)' $($_.Version)" }) -join ', ') + '.') foreach ($o in $ordered) { if ($installed.ContainsKey("$($o.AppId)|$($o.Version)".ToLowerInvariant())) { Invoke-BcNavStep -Label "Uninstalling '$($o.Name) $($o.Version)'" -Command 'Uninstall-NAVApp' -Arguments @{ ServerInstance = $ServerInstance; Name = "$($o.Name)"; Publisher = "$($o.Publisher)"; Version = "$($o.Version)"; Tenant = $Tenant; Force = $true } } } foreach ($o in $ordered) { # Clean drops the old version's tables; without it the data stays for the new version. if ($clean) { Invoke-BcNavStep -Label "Clean-syncing '$($o.Name) $($o.Version)'" -Command 'Sync-NAVApp' -Arguments @{ ServerInstance = $ServerInstance; Name = "$($o.Name)"; Publisher = "$($o.Publisher)"; Version = "$($o.Version)"; Tenant = $Tenant; Mode = 'Clean'; Force = $true } } Invoke-BcNavStep -Label "Unpublishing '$($o.Name) $($o.Version)'" -Command 'Unpublish-NAVApp' -Arguments @{ ServerInstance = $ServerInstance; Name = "$($o.Name)"; Publisher = "$($o.Publisher)"; Version = "$($o.Version)" } } } } } # The new version is never synced with Clean: Clean removes its schema (NotSynced). $newMode = if ($Mode -eq 'Clean') { 'Add' } else { $Mode } $job = Start-Job -ScriptBlock { param($module, $si, $path, $scope, $skip) if ($module) { Import-Module $module -DisableNameChecking -ErrorAction Stop } $wv = @() Publish-NAVApp -ServerInstance $si -Path $path -Scope $scope -SkipVerification:$skip -ErrorAction Stop -WarningVariable +wv -WarningAction SilentlyContinue foreach ($x in $wv) { "ALBUILD-WARN:$x" } } -ArgumentList $navMgmtPath, $ServerInstance, $Path, $Scope, ([bool]$SkipVerification) $r = Wait-BcStepJob -Job $job -Label "Publishing $app" if (-not $r.Ok) { [System.Console]::Out.WriteLine("ALBUILD-ERROR:$($r.Error)"); [System.Console]::Out.Flush(); exit 1 } $syncStart = Get-Date if ($DoSync) { $job = Start-Job -ScriptBlock { param($module, $si, $name, $ver, $mode, $tenant) if ($module) { Import-Module $module -DisableNameChecking -ErrorAction Stop } $wv = @() Sync-NAVApp -ServerInstance $si -Name $name -Version $ver -Mode $mode -Tenant $tenant -Force -ErrorAction Stop -WarningVariable +wv -WarningAction SilentlyContinue foreach ($x in $wv) { "ALBUILD-WARN:$x" } } -ArgumentList $navMgmtPath, $ServerInstance, $info.Name, $info.Version, $newMode, $Tenant $r = Wait-BcStepJob -Job $job -Label "Syncing $app (mode $newMode)" if (-not $r.Ok) { [System.Console]::Out.WriteLine("ALBUILD-ERROR:$($r.Error)"); [System.Console]::Out.Flush(); exit 1 } } if ($DoInstall) { # Read the tenant's view of this app ONCE: the just-published version's SyncState (for the # fail-fast below), whether it is already installed, and the version the tenant DATA is at # (ExtensionDataVersion) - which, not "is another version published", is what actually decides # install vs data-upgrade. $tenantInfo = @() try { $tenantInfo = @(Get-NAVAppInfo -ServerInstance $ServerInstance -Name $info.Name -Publisher $info.Publisher -Tenant $Tenant -TenantSpecificProperties | Where-Object { "$($_.AppId)" -eq "$($info.AppId)" }) } catch { } # Property access is StrictMode-safe: Get-NAVAppInfo -TenantSpecificProperties carries SyncState / # ExtensionDataVersion / IsInstalled, but a mock (or an odd BC version) may not, and StrictMode # throws on a missing property. Read via PSObject.Properties so an absent field is just $null. $prop = { param($o, $n) if ($o -and ($o.PSObject.Properties.Name -contains $n)) { $o.$n } else { $null } } $thisVer = @($tenantInfo | Where-Object { "$($_.Version)" -eq "$($info.Version)" }) | Select-Object -First 1 $syncState = "$(& $prop $thisVer 'SyncState')" # §2 FAIL FAST: Sync-NAVApp above can report success while the NST leaves the app NotSynced (a # schema conflict silently blocked 'Add' mode). A plain install then fails with "not # synchronized". Stop here with an actionable code + remedy instead of proceeding to a doomed # install. Callers pass -SyncMode ForceSync (CLI: --if-exists force-sync) to push the change. if ($DoSync -and $syncState -and $syncState -notin @('Synced', 'Unknown')) { # Name the mode that ran and the server's own reason, not only a generic remedy. $serverErr = Get-BcNavServerError -Since $syncStart $reason = if ($serverErr) { " NAV server log: $serverErr" } else { ' The NAV server logged no error for it.' } $remedy = if ($newMode -eq 'ForceSync') { '' } else { ' To push a schema change through, re-publish with -SyncMode ForceSync (CLI: --if-exists force-sync).' } [System.Console]::Out.WriteLine("ALBUILD-ERROR:NOT_SYNCHRONIZED: '$($info.Name)' $($info.Version) is '$syncState' after a sync in mode $newMode.$reason$remedy") [System.Console]::Out.Flush(); exit 1 } # The version the tenant's DATA is at (highest ExtensionDataVersion across versions). $tenantDataList = @($tenantInfo | ForEach-Object { "$(& $prop $_ 'ExtensionDataVersion')" } | Where-Object { $_ }) $tenantData = if ($tenantDataList.Count -gt 0) { @($tenantDataList | Sort-Object { [version]$_ } -Descending)[0] } else { '' } # OLDER published versions only. A data upgrade goes forward, so only a strictly-older present # version (or older tenant data) makes this an upgrade - NOT merely "a different version". A # NEWER version lingering (e.g. a stale build not cleared by a force-sync republish) must not be # treated as something to "upgrade to", which fails with "no previous version was found". $prior = @($tenantInfo | Where-Object { try { [version]"$($_.Version)" -lt [version]"$($info.Version)" } catch { $false } }) # Upgrade when a strictly-OLDER version is still published, OR the tenant holds data written by an # older version (even if no old version is still published - the case a plain install cannot fix # and that leaves the app NotSynced). Equal/newer tenant data == install (§3a: a same-version # republish is never an upgrade, whatever the caller asked for). $doUpgrade = ($prior.Count -gt 0) if (-not $doUpgrade -and $tenantData -and ([version]$tenantData -lt [version]$info.Version)) { $doUpgrade = $true } if (-not $doUpgrade -and (& $prop $thisVer 'IsInstalled')) { # §3a: same version already installed (e.g. a force-sync republish of the current version) - # Install-NAVApp would error "already installed". It is a no-op; report and move on. [System.Console]::Out.WriteLine("$($info.Name) $($info.Version): already installed (tenant data '$tenantData') - nothing to install.") } elseif (-not $doUpgrade) { [System.Console]::Out.WriteLine("$($info.Name) $($info.Version): first-time install (tenant data '$tenantData').") $job = Start-Job -ScriptBlock { param($module, $si, $name, $ver, $tenant) if ($module) { Import-Module $module -DisableNameChecking -ErrorAction Stop } $wv = @() Install-NAVApp -ServerInstance $si -Name $name -Version $ver -Tenant $tenant -ErrorAction Stop -WarningVariable +wv -WarningAction SilentlyContinue foreach ($x in $wv) { "ALBUILD-WARN:$x" } } -ArgumentList $navMgmtPath, $ServerInstance, $info.Name, $info.Version, $Tenant $r = Wait-BcStepJob -Job $job -Label "Installing $app" if (-not $r.Ok) { [System.Console]::Out.WriteLine("ALBUILD-ERROR:$($r.Error)"); [System.Console]::Out.Flush(); exit 1 } } else { [System.Console]::Out.WriteLine("$($info.Name) $($info.Version): upgrading from $(@($prior | ForEach-Object { $_.Version }) -join ', ').") $job = Start-Job -ScriptBlock { param($module, $si, $name, $ver, $tenant) if ($module) { Import-Module $module -DisableNameChecking -ErrorAction Stop } $wv = @() Start-NAVAppDataUpgrade -ServerInstance $si -Name $name -Version $ver -Tenant $tenant -ErrorAction Stop -WarningVariable +wv -WarningAction SilentlyContinue foreach ($x in $wv) { "ALBUILD-WARN:$x" } } -ArgumentList $navMgmtPath, $ServerInstance, $info.Name, $info.Version, $Tenant $r = Wait-BcStepJob -Job $job -Label "Upgrading to $app" if (-not $r.Ok) { [System.Console]::Out.WriteLine("ALBUILD-ERROR:$($r.Error)"); [System.Console]::Out.Flush(); exit 1 } foreach ($old in $prior) { $job = Start-Job -ScriptBlock { param($module, $si, $name, $publisher, $ver) if ($module) { Import-Module $module -DisableNameChecking -ErrorAction Stop } Unpublish-NAVApp -ServerInstance $si -Name $name -Publisher $publisher -Version $ver -ErrorAction Stop } -ArgumentList $navMgmtPath, $ServerInstance, $info.Name, $info.Publisher, $old.Version $r = Wait-BcStepJob -Job $job -Label "Unpublishing superseded $($info.Name) $($old.Version)" # Best-effort cleanup: the upgrade already succeeded, so a failed unpublish of an old # version must NOT fail the release. Warn and carry on (do not exit). if (-not $r.Ok) { [System.Console]::Out.WriteLine("WARNING: Could not unpublish superseded $($info.Name) $($old.Version): $($r.Error). Continuing."); [System.Console]::Out.Flush() } } } } [System.Console]::Out.WriteLine("Published $($info.Name) $($info.Version)") } # Stream the in-container output so the progress line is visible live; the full output is still # returned. Log a concise host-side summary (the per-app line already streamed). $null = Invoke-BcContainerCommand -ContainerName $Name -ScriptBlock $script -DockerExecutable $DockerExecutable -StreamOutput -Variables @{ Path = $containerPath; ServerInstance = $ServerInstance; Scope = $Scope SkipVerification = [bool]$SkipVerification; DoSync = [bool]$Sync; DoInstall = [bool]$Install; Mode = $SyncMode; Tenant = $Tenant # A ';'-joined string: a one-element array would cross the JSON boundary as a scalar. IfExists = $IfExists; ReplaceableAppIds = (@($ReplaceableAppId | Where-Object { $_ }) -join ';') OperationTimeoutSeconds = [int]$OperationTimeoutSeconds; PollSeconds = 10 } Write-ALbuildLog -Level Success "Published & installed '$(Split-Path -Path $AppFile -Leaf)' into '$Name'." } |