From 467f699103afc5d1c9cd4fcec8a9790d45bcd7bd Mon Sep 17 00:00:00 2001 From: ek-dyoder Date: Tue, 17 Nov 2026 00:13:07 -0500 Subject: [PATCH] add update script for cloud backup --- Fix-UpdateLocalHosts.ps1 | 59 ++++---- Install-EmberkomCloudBackup.ps1 | 44 ++---- Tools.ps1 | 62 ++++++++ Update-EmberkomCloudBackup.ps1 | 126 +++++++++++++++++ docs/EmberkomCloudBackup-Updates.md | 21 +++ resources/EmberkomCloudBackup.json | 12 ++ rmm/Update-EmberkomCloudBackup.ps1 | 9 ++ tests/Update-EmberkomCloudBackup.Tests.ps1 | 157 +++++++++++++++++++++ 8 files changed, 426 insertions(+), 64 deletions(-) create mode 100644 Update-EmberkomCloudBackup.ps1 create mode 100644 docs/EmberkomCloudBackup-Updates.md create mode 100644 resources/EmberkomCloudBackup.json create mode 100644 rmm/Update-EmberkomCloudBackup.ps1 create mode 100644 tests/Update-EmberkomCloudBackup.Tests.ps1 diff --git a/Fix-UpdateLocalHosts.ps1 b/Fix-UpdateLocalHosts.ps1 index a801beb..be50db3 100644 --- a/Fix-UpdateLocalHosts.ps1 +++ b/Fix-UpdateLocalHosts.ps1 @@ -1,30 +1,34 @@ $DNSHelper = $Global:ToolsDirectory + '\ekdns.exe' -$DNSHelperRequiredVersion = '2.3.0' -$DownloadRequired = $false - -If (Test-Path $DNSHelper) { - $versionOutput = (& $DNSHelper 2>&1 | Select-Object -First 1) - If ($versionOutput -match 'v(\d+\.\d+\.\d+)') { - If ($Matches[1] -ne $DNSHelperRequiredVersion) { - $DownloadRequired = $true - } - } Else { - $DownloadRequired = $true - } +# SHA-256 of ekdns.exe from each v2.3.0 Windows release archive. +If ([Environment]::Is64BitOperatingSystem) { + $DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe' + $DNSHelperHash = '308E36680C0E4AD7CE802F4B1D8C38E89B0D8E24BBCE4F33550721C78BA2224C' } Else { - $DownloadRequired = $true + $DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x86-exe/download/ekdns-x86.exe' + $DNSHelperHash = 'F987E75D8FFB87B587B57D2394131B072957C0E3EB6B73B4FB784E9B0D65277B' } -# Download the latest version of ekDNSHelper -If ($DownloadRequired) { - $DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe' - If (!(Test-Path ${Env:ProgramFiles(x86)})) { - $DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x86-exe/download/ekdns-x86.exe' +$InstalledHash = (Get-FileHash -LiteralPath $DNSHelper -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash +If ($InstalledHash -ne $DNSHelperHash) { + $StagedHelper = $DNSHelper + '.' + [guid]::NewGuid().ToString('N') + '.tmp' + Try { + Write-Output "Downloading latest version of ekDNSHelper" + $null = Download-File -URL $DNSHelperURL -File $StagedHelper + If ((Get-FileHash -LiteralPath $StagedHelper -Algorithm SHA256 -ErrorAction Stop).Hash -ne $DNSHelperHash) { + Throw 'Downloaded ekdns.exe failed SHA-256 verification.' + } + If ([IO.File]::Exists($DNSHelper)) { + [IO.File]::Replace($StagedHelper, $DNSHelper, [NullString]::Value) + } Else { + [IO.File]::Move($StagedHelper, $DNSHelper) + } + } Catch { + Write-Error $_.Exception.Message + Exit 1 + } Finally { + Remove-Item -LiteralPath $StagedHelper -Force -ErrorAction SilentlyContinue } - If (Test-Path $DNSHelper) { Remove-Item -Path $DNSHelper -Force -ErrorAction SilentlyContinue } - Write-Output "Downloading latest version of ekDNSHelper" - Download-File -URL $DNSHelperURL -File $DNSHelper } # Delete the old version of ekDNSHelper if it exists @@ -62,15 +66,14 @@ If ( Test-Path $DNSHelper ) { $commandString = """${DNSHelper}"" add -host ${HostString}" $content = $RefreshScriptHeader + $commandString Write-Output "Creating latest refresh script" - If ( Test-Path $RefreshScript ) { Remove-Item -Path $RefreshScript -Force } Try { - New-Item -Path $RefreshScript -ItemType File -Force | Out-Null - Set-Content -Path $RefreshScript -Value $content + Set-Content -LiteralPath $RefreshScript -Value $content -Force -ErrorAction Stop + Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}" + & "${RefreshScript}" + If ($LASTEXITCODE -ne 0) { Exit $LASTEXITCODE } } - Catch { Write-Error $_.Exception.Message } - - Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}" - & "${RefreshScript}" + Catch { Write-Error $_.Exception.Message ; Exit 1 } } Else { Write-Error "Cannot find the DNS Helper executable: ""${DNSHelper}""" + Exit 1 } diff --git a/Install-EmberkomCloudBackup.ps1 b/Install-EmberkomCloudBackup.ps1 index fe75d45..de75f9d 100644 --- a/Install-EmberkomCloudBackup.ps1 +++ b/Install-EmberkomCloudBackup.ps1 @@ -1,15 +1,8 @@ -# Specify URL to "Backup for Windows" agent installer -$ECB_WIN_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VmK3VHNmxBVEZTQkxhMFhNR2ZuZzJCeE80MDJxVkRSWXdNa0dqSHdpbUN1bE01c3BWNFBVUmt2Q1c4endncjVZemFSSjEyYmFNL3hESHR2eWpVYXpBVlV2eU1kZVZFaEpvalk2Rk40Wk96UG9QdUwxYnZrRHREMmhLeTZoMW5Rbz0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4' - -# Specify URL to "Backup Virtual Machine Edition" agent installer -$ECB_VMM_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNwOTFVa3h6WUdoeVVod1JmT2lRQ1FlVTE3Y0pnUncwSEJwS3FFcDBmTWt3cEdnSy9YemRsSTRiQWJHNi96cUtWbzZsc25QVllaR1QyQ21VVS95dFFVTkNndXdPVStGQXBIT0FZb2FIUzFuZy9mMU5qZUd5emhab1hFYjZWODB4ND0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4' - -# Set the correct download URL and agent edition -switch ( $Edition.ToLower() ) { - 'server' { $URL = $ECB_WIN_URL; $AgentEdition = 'baremetal' } - 'desktop' { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop' } - 'vm' { $URL = $ECB_VMM_URL; $AgentEdition = 'vmedition' } - default { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop' } +# Install and update use the same published Emberkom packages. +switch ($Edition) { + 'server' { $CloudBackupBuild = 'Windows'; $AgentEdition = 'baremetal' } + 'vm' { $CloudBackupBuild = 'VM'; $AgentEdition = 'vmedition' } + default { $CloudBackupBuild = 'Windows'; $AgentEdition = 'desktop' } } # Install and import additional Powershell module @@ -21,30 +14,9 @@ If ( $(Get-MBSAgent -ErrorAction SilentlyContinue) ) { Return } -# -# The URL is now too long to pass as a variable to other functions and cmdlets, so this is a workaround to download the file -# - -# Make sure the URL is valid -$StatusCode = [System.Net.WebRequest]::Create($URL).GetResponse().StatusCode -If ( !(($StatusCode -ge 200) -and ($StatusCode -lt 400)) ) { Write-Output "URL cannot be reached (status code ${StatusCode}): ${URL}" ; Return } - -# Make a local file to download to -$Installer = '{0}EmberkomCloudBackup.exe' -f (Get-TempPath) - -# Delete previous local file if it exists -If ( Test-Path $Installer ) { Write-Output "Deleting previously downloaded file: ${Installer}" ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue } - -# Download the file -Try { (New-Object System.Net.WebClient).DownloadFile($URL,$Installer) } -Catch { Write-Error $_.Exception.Message ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue } - -# Make sure the file exists -If ( !(Test-Path $Installer) ) { Write-Output "There was a problem downloading the file, this script will not continue" ; Return } - -# -# End the workaround -# +$CloudBackupRelease = Get-EmberkomCloudBackupRelease -Build $CloudBackupBuild +$Installer = Join-Path (Get-TempPath) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid()) +Save-EmberkomCloudBackupInstaller -Release $CloudBackupRelease -Path $Installer # Install the agent Write-Output "Installing Emberkom Cloud Backup agent" diff --git a/Tools.ps1 b/Tools.ps1 index 182481e..4e5edd7 100644 --- a/Tools.ps1 +++ b/Tools.ps1 @@ -219,6 +219,38 @@ Function ConvertTo-RmmBoolean { } } +# Convert an RMM semicolon-separated text variable into individual strings. +Function ConvertTo-RmmList { + <# + .SYNOPSIS + Splits an RMM text value on semicolons and trims each item. + .DESCRIPTION + Null, blank, and empty items are omitted. Item order, case, duplicates, + internal spaces, commas, and backslashes are preserved. Values are not + evaluated, expanded, resolved, or checked for existence. Semicolons are + always separators; there is no quoting or escaping syntax. + Wrap the call in @() to obtain an array for zero, one, or many items. + .EXAMPLE + $Paths = @(ConvertTo-RmmList -Value 'C:\QB Data; \\server\Archive;') + .EXAMPLE + $Shares = @(ConvertTo-RmmList -Value $QuickBooksShareNames) + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] + [AllowNull()] + [AllowEmptyString()] + [string]$Value + ) + process { + foreach ($Item in ([string]$Value).Split(';')) { + $Item = $Item.Trim() + if ($Item.Length -gt 0) { $Item } + } + } +} + # Determines whether a URL is valid Function IsURLValid { param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL) @@ -853,6 +885,36 @@ Function Disable-Log { Catch { Write-Error $_.Exception.Message } } +# Published packages for both Install- and Update-EmberkomCloudBackup. +Function Get-EmberkomCloudBackupRelease { + param([Parameter(Mandatory=$true)][ValidateSet('Windows','VM')][string]$Build) + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $client = New-Object Net.WebClient + try { + $json = $client.DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/resources/EmberkomCloudBackup.json') + } finally { $client.Dispose() } + $release = ($json | ConvertFrom-Json -ErrorAction Stop).$Build + if ($release.Version -notmatch '^\d+\.\d+\.\d+\.\d+$' -or $release.Url -notmatch '^https://' -or + $release.SHA256 -notmatch '^[a-f0-9]{64}$') { + throw "Incomplete Emberkom Cloud Backup release for $Build." + } + return $release +} + +Function Save-EmberkomCloudBackupInstaller { + param([Parameter(Mandatory=$true)]$Release, [Parameter(Mandatory=$true)][string]$Path) + $client = New-Object Net.WebClient + try { + $client.DownloadFile($Release.Url, $Path) + if ((Get-FileHash -LiteralPath $Path -Algorithm SHA256 -ErrorAction Stop).Hash -ne $Release.SHA256) { + throw 'The installer SHA-256 does not match the published release.' + } + } catch { + if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Force -ErrorAction Stop } + throw + } finally { $client.Dispose() } +} + # Function to install the MSP360 Powershell module Function Import-MSP360Module { Try { diff --git a/Update-EmberkomCloudBackup.ps1 b/Update-EmberkomCloudBackup.ps1 new file mode 100644 index 0000000..63ee043 --- /dev/null +++ b/Update-EmberkomCloudBackup.ps1 @@ -0,0 +1,126 @@ +#Requires -Version 5.1 +# Update an existing Emberkom MSP360 Managed Backup agent during an idle RMM window. + +function Get-CloudBackupAgent { + # MSP360's managed-agent registration points to the branded uninstall key. + # Open the registry view explicitly so a 32-bit RMM host can see a 64-bit agent. + $views = if ([Environment]::Is64BitOperatingSystem) { 'Registry64', 'Registry32' } else { 'Registry32' } + foreach ($view in $views) { + $registry = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', $view) + $marker = $product = $null + try { + $marker = $registry.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}') + if (!$marker) { continue } + $product = $registry.OpenSubKey([string]$marker.GetValue('UninstallKey')) + if (!$product -or !$product.GetValue('')) { throw 'The MSP360 agent registration has no executable path.' } + if ($product.GetValue('Publisher') -ne 'Emberkom') { throw 'The registered backup agent belongs to a different publisher.' } + $cli = Join-Path (Split-Path -LiteralPath $product.GetValue('')) 'cbb.exe' + return (Read-CloudBackupAgent -Cli $cli) + } finally { + if ($product) { $product.Dispose() } + if ($marker) { $marker.Dispose() } + $registry.Dispose() + } + } +} + +function Read-CloudBackupAgent { + param([string]$Cli) + $details = & $Cli ver + if ($LASTEXITCODE -ne 0) { throw "MSP360 could not report the installed agent details (exit $LASTEXITCODE)." } + $edition = $service = $null + foreach ($line in $details) { + if ($line -match '^Backup Agent Edition:\s*(.+)$') { $edition = $Matches[1].Trim() } + if ($line -match '^Service name:\s*(.+)$') { $service = $Matches[1].Trim() } + } + if ($edition -in @('VMware','VMEdition','VM','Virtual Machine Edition')) { + $build = 'VM' + } elseif ($edition -in @('Desktop','DesktopIBB','FileBackup','BareMetal','Server','MsSql','SqlServer', + 'Exchange','MsExchange','SqlExchange','MsSqlExchange','MsSqlMsExchange','Enterprise','Ultimate')) { + $build = 'Windows' + } else { + throw "Unrecognized MSP360 agent edition '$edition'. Cannot choose a published package." + } + if (!$service) { throw 'MSP360 did not report its backup service name.' } + [pscustomobject]@{ + Version = [version][Diagnostics.FileVersionInfo]::GetVersionInfo($Cli).FileVersion + Build = $build + Service = $service + } +} + +function Test-CloudBackupUpdateWindow { + param([string]$Window, [datetime]$Now = (Get-Date)) + if ([string]::IsNullOrWhiteSpace($Window)) { return $true } + if ($Window.Trim() -notmatch '^((?:[01]\d|2[0-3]):[0-5]\d)-((?:[01]\d|2[0-3]):[0-5]\d)$') { + throw 'MSP360UpdateWindow must be a local 24-hour interval such as 12:00-13:00.' + } + $start = [timespan]::ParseExact($Matches[1], 'hh\:mm', $null) + $end = [timespan]::ParseExact($Matches[2], 'hh\:mm', $null) + if ($start -eq $end) { throw 'MSP360UpdateWindow needs different start and end times.' } + $time = $Now.TimeOfDay + if ($start -lt $end) { return ($time -ge $start -and $time -lt $end) } + return ($time -ge $start -or $time -lt $end) +} + +function Test-CloudBackupPlanRunning { + # The agent launches CBBackupPlan.exe for plan execution. This also works on + # CLI-password-protected agents, without passing credentials to a child process. + return [bool](Get-CimInstance -ClassName Win32_Process -Filter "Name = 'CBBackupPlan.exe'" -Property ProcessId -ErrorAction Stop) +} + +function Invoke-CloudBackupUpdate { + param([string]$Window) + if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host "Deferred. Outside the local update window $Window."; return 0 } + $agent = Get-CloudBackupAgent + if (!$agent) { Write-Host 'Skipped. MSP360 Managed Backup is not installed.'; return 0 } + $release = Get-EmberkomCloudBackupRelease -Build $agent.Build + $target = [version]$release.Version + if ($agent.Version -ge $target) { + Write-Host "No update needed. Installed $($agent.Version), published $($agent.Build) build $target." + return 0 + } + if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker is active.'; return 0 } + + $installer = Join-Path ([IO.Path]::GetTempPath()) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid()) + try { + Write-Host "Downloading the published $($agent.Build) update from $($agent.Version) to $target." + Save-EmberkomCloudBackupInstaller -Release $release -Path $installer + # A scheduled plan or the agent's own updater could have started during download. + $current = Get-CloudBackupAgent + if (!$current -or $current.Build -ne $agent.Build) { throw 'The installed agent changed during download.' } + if ($current.Version -ge $target) { Write-Host "Already updated to $($current.Version)."; return 0 } + if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host 'Deferred. The update window ended during download.'; return 0 } + if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker started during download.'; return 0 } + $setup = Start-Process -FilePath $installer -ArgumentList '/S' -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop + if ($setup.ExitCode -eq 3010) { Write-Host 'MSP360 setup requires a restart to finish. Run the check again after restart.'; return 3010 } + if ($setup.ExitCode -ne 0) { throw "MSP360 setup returned exit code $($setup.ExitCode)." } + $updated = Get-CloudBackupAgent + if (!$updated -or $updated.Build -ne $agent.Build -or $updated.Version -lt $target) { + throw "Setup exited successfully but the installed $($agent.Build) agent could not be verified at $target or newer." + } + $service = Get-Service -Name $updated.Service -ErrorAction Stop + $service.WaitForStatus('Running', [timespan]::FromSeconds(60)) + Write-Host "Updated MSP360 $($updated.Build) from $($agent.Version) to $($updated.Version). $($updated.Service) is running." + return 0 + } finally { + if (Test-Path -LiteralPath $installer) { Remove-Item -LiteralPath $installer -Force -ErrorAction Stop } + } +} + +$ErrorActionPreference = 'Stop' +$updateLock = [Threading.Mutex]::new($false, 'Global\EmberkomCloudBackupUpdate') +$ownsLock = $false +try { + try { $ownsLock = $updateLock.WaitOne(0) } + catch [Threading.AbandonedMutexException] { $ownsLock = $true } + if (!$ownsLock) { Write-Host 'Deferred. Another Emberkom Cloud Backup update check is running.'; exit 0 } + $windowInput = Get-Variable -Name MSP360UpdateWindow -ErrorAction SilentlyContinue + exit (Invoke-CloudBackupUpdate -Window ([string]$windowInput.Value)) +} catch { + Microsoft.PowerShell.Utility\Write-Error "Emberkom Cloud Backup update failed. $($_.Exception.Message)" -ErrorAction Continue + exit 1 +} finally { + if ($ownsLock) { $updateLock.ReleaseMutex() } + $updateLock.Dispose() +} diff --git a/docs/EmberkomCloudBackup-Updates.md b/docs/EmberkomCloudBackup-Updates.md new file mode 100644 index 0000000..d21660d --- /dev/null +++ b/docs/EmberkomCloudBackup-Updates.md @@ -0,0 +1,21 @@ +# Updating Emberkom Cloud Backup between plans + +Publish the repository changes to the live `master` branch, then upload [the RMM caller](../rmm/Update-EmberkomCloudBackup.ps1) to Syncro as a Windows PowerShell 5.1 script. Run it as SYSTEM on endpoints with Emberkom Cloud Backup. Schedule it in a gap long enough for the download, installation, and backup service restart. Include restore plans and consistency checks when choosing that gap. + +For endpoints that might receive a delayed RMM job, configure the optional **string** variable `MSP360UpdateWindow`. For example, `12:00-13:00` admits installation starts from noon until just before 1 p.m. in the endpoint's local time. Overnight windows such as `23:30-00:30` also work. With an omitted or blank value, Syncro controls the timing. Allow enough time after the last permitted start for setup to finish. + +The updater compares the installed version with the published Windows or VM package. Before downloading and again immediately before launching setup, it checks for MSP360's `CBBackupPlan.exe` worker. A busy endpoint defers to the next scheduled run. A plan can still start after the final check, so keep the RMM slot clear of scheduled plans. [MSP360 plan worker documentation](https://help.mspbackups.com/troubleshooting) + +**Syncro output and exit codes** + +| Code | Meaning | +| --- | --- | +| 0 | Update verified, version already current or newer, agent absent, or run deferred. The output gives the outcome. | +| 1 | Update failed. The output identifies the failed check or installer exit code. | +| 3010 | Setup requested a restart. Recheck after the endpoint restarts. | + +MSP360 also checks for updates at the start of plans when its console policy allows it. To make Syncro the sole update path on selected computers, use **Downloads → Options → Exclude from auto-update** in MSP360 after the RMM job is in service. Review the scope because this console setting also covers the MSP360 RMM Agent. [MSP360 agent update policy](https://help.mspbackups.com/downloads/agent-update) + +## Publishing a build + +Both the existing installer and the updater read [the shared release file](../resources/EmberkomCloudBackup.json). When approving a new public build, update its four-part version, console download URL, and SHA-256 in the corresponding `Windows` or `VM` entry. Take the version from the published build and compute the hash from that exact installer using `Get-FileHash -Algorithm SHA256`. Publish the three values together. The generated setup executables can have empty Windows file-version fields. diff --git a/resources/EmberkomCloudBackup.json b/resources/EmberkomCloudBackup.json new file mode 100644 index 0000000..1b5b163 --- /dev/null +++ b/resources/EmberkomCloudBackup.json @@ -0,0 +1,12 @@ +{ + "Windows": { + "Version": "8.7.1.177", + "Url": "https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VmK3VHNmxBVEZTQkxhMFhNR2ZuZzJCeE80MDJxVkRSWXdNa0dqSHdpbUN1bE01c3BWNFBVUmt2Q1c4endncjVZemFSSjEyYmFNL3hESHR2eWpVYXpBVlV2eU1kZVZFaEpvalk2Rk40Wk96UG9QdUwxYnZrRHREMmhLeTZoMW5Rbz0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4", + "SHA256": "1EC7E1FAF23DE3D5C23BC147823D8A41A7A75B631E5E041EDEDF0A76233BF2FE" + }, + "VM": { + "Version": "8.7.1.177", + "Url": "https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNwOTFVa3h6WUdoeVVod1JmT2lRQ1FlVTE3Y0pnUncwSEJwS3FFcDBmTWt3cEdnSy9YemRsSTRiQWJHNi96cUtWbzZsc25QVllaR1QyQ21VVS95dFFVTkNndXdPVStGQXBIT0FZb2FIUzFuZy9mMU5qZUd5emhab1hFYjZWODB4ND0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4", + "SHA256": "F247D73C30CCE522FDE6FCEB0F00984BB88D0010D657BC379A673BACAD32F804" + } +} diff --git a/rmm/Update-EmberkomCloudBackup.ps1 b/rmm/Update-EmberkomCloudBackup.ps1 new file mode 100644 index 0000000..c370438 --- /dev/null +++ b/rmm/Update-EmberkomCloudBackup.ps1 @@ -0,0 +1,9 @@ +#Requires -Version 5.1 +# Syncro: run as SYSTEM at a time reserved between backup, restore and consistency plans. +# Optional string $MSP360UpdateWindow, e.g. '12:00-13:00' in endpoint local time. +# Leave blank to use the Syncro schedule alone. See docs/EmberkomCloudBackup-Updates.md. +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) +Run-Script -LivePSScript Update-EmberkomCloudBackup +exit $LASTEXITCODE diff --git a/tests/Update-EmberkomCloudBackup.Tests.ps1 b/tests/Update-EmberkomCloudBackup.Tests.ps1 new file mode 100644 index 0000000..562b2fb --- /dev/null +++ b/tests/Update-EmberkomCloudBackup.Tests.ps1 @@ -0,0 +1,157 @@ +#Requires -Version 5.1 +# Run with Windows PowerShell. All downloads, plan checks and installs are fixtures. +$ErrorActionPreference = 'Stop' +$repo = Split-Path -Parent $PSScriptRoot +$fixtureDir = Join-Path ([IO.Path]::GetTempPath()) ('CloudBackupTest-' + [guid]::NewGuid()) +$null = New-Item -ItemType Directory -Path $fixtureDir + +function Read-TestAst($Path) { + $parseErrors = $null + $tree = [Management.Automation.Language.Parser]::ParseFile($Path, [ref]$null, [ref]$parseErrors) + if ($parseErrors) { throw ($parseErrors | Out-String) } + return $tree +} +function Find-TestFunction($Tree, $Name) { + $fn = $Tree.Find({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $Name}, $false) + if (!$fn) { throw "Missing $Name" } + return $fn +} + +try { + $core = Read-TestAst (Join-Path $repo 'Update-EmberkomCloudBackup.ps1') + $windowFn = Find-TestFunction $core 'Test-CloudBackupUpdateWindow' + . ([scriptblock]::Create($windowFn.Extent.Text)) + foreach ($case in @( + @('23:30-00:30','23:30',$true), @('23:30-00:30','00:29',$true), + @('23:30-00:30','00:30',$false), @('12:00-13:00','11:59',$false), + @('12:00-13:00','12:00',$true), @('12:00-13:00','13:00',$false), @('','02:00',$true) + )) { + if ((Test-CloudBackupUpdateWindow $case[0] ([datetime]::ParseExact($case[1],'HH:mm',$null))) -ne $case[2]) { + throw "Window boundary failed for $($case[0]) at $($case[1])" + } + } + # Substitute only discovery of the installed product in the downloaded core. + $discovery = Find-TestFunction $core 'Get-CloudBackupAgent' + $coreSource = $core.Extent.Text.Replace($discovery.Extent.Text, 'function Get-CloudBackupAgent { Get-FixtureAgent }') + $toolsAst = Read-TestAst (Join-Path $repo 'Tools.ps1') + $shimTools = (@('Run-Script','Get-EmberkomCloudBackupRelease','Save-EmberkomCloudBackupInstaller') | + ForEach-Object { (Find-TestFunction $toolsAst $_).Extent.Text }) -join [Environment]::NewLine + $fixtureBytes = [byte[]](1,2,3) + $sha = [Security.Cryptography.SHA256]::Create() + try { $hash = [BitConverter]::ToString($sha.ComputeHash($fixtureBytes)).Replace('-','') } finally { $sha.Dispose() } + $manifest = Get-Content -Raw -LiteralPath (Join-Path $repo 'resources/EmberkomCloudBackup.json') | ConvertFrom-Json + foreach ($kind in 'Windows','VM') { + if ($manifest.$kind.SHA256 -notmatch '^[a-f0-9]{64}$' -or $manifest.$kind.Url -notlike 'https://*') { throw "Bad $kind release" } + $manifest.$kind.SHA256 = $hash + $manifest.$kind.Version = '8.10.1.177' + } + function IsURLValid { param($URL) $true } + function Download-File { + param($URL) + if ($URL -notlike '*/Update-EmberkomCloudBackup.ps1') { throw "Unexpected script request" } + $path = Join-Path $fixtureDir 'downloaded.ps1' + [IO.File]::WriteAllText($path, $coreSource) + return $path + } + function New-Object { + param($TypeName) + if ($TypeName -ne 'Net.WebClient') { throw "Unexpected construction of $TypeName" } + $client = [pscustomobject]@{} + $client | Add-Member ScriptMethod DownloadString { param($url) + if ($url -like '*/Tools.ps1') { return $shimTools } + if ($url -like '*/Update-EmberkomCloudBackup.ps1') { return $coreSource } + if ($url -like '*/resources/EmberkomCloudBackup.json') { return ($manifest | ConvertTo-Json) } + throw "Unexpected URL" + } + $client | Add-Member ScriptMethod DownloadFile { param($url,$path) + $record.Downloads++ + if ($url -cne $manifest.$kind.Url) { throw 'Downloaded the wrong edition' } + $record.Staged = $path + [IO.File]::WriteAllBytes($path, $fixtureBytes) + if ($scenario -eq 'corrupt') { [IO.File]::AppendAllText($path,'x') } + if ($scenario -eq 'download failure') { throw 'Transfer interrupted' } + } + $client | Add-Member ScriptMethod Dispose {} + return $client + } + function Get-FixtureAgent { + if ($scenario -eq 'absent') { return } + $v = '8.9.1.177' + if ($scenario -eq 'current' -or ($record.Installs -and $scenario -ne 'unverified')) { $v = '8.10.1.177' } + if ($scenario -eq 'newer') { $v = '8.11.0.1' } + if ($scenario -eq 'already updated' -and $record.Downloads) { $v = '8.10.1.177' } + [pscustomobject]@{ Version=[version]$v; Build=$kind; Service='Fixture Service' } + } + function Get-Date { + if ($scenario -eq 'window ended' -and $record.Downloads) { return [datetime]'2026-01-01T13:00' } + return [datetime]'2026-01-01T12:30' + } + function Get-CimInstance { + param($ClassName,$Filter,$Property,$ErrorAction) + if ($ClassName -ne 'Win32_Process' -or $Filter -ne "Name = 'CBBackupPlan.exe'") { throw 'Unexpected worker query' } + if ($scenario -eq 'query failure') { throw 'Cannot enumerate processes' } + if ($scenario -eq 'busy' -or ($record.Downloads -and $scenario -eq 'late plan')) { [pscustomobject]@{ ProcessId=42 } } + } + function Start-Process { + param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru,$ErrorAction) + $record.Installs++ + if ($FilePath -ne $record.Staged -or $ArgumentList -cne '/S' -or !$Wait -or !$PassThru) { throw 'Unexpected setup invocation' } + $code = switch ($scenario) { reboot {3010} failure {1603} default {0} } + [pscustomobject]@{ ExitCode=$code } + } + function Get-Service { + param($Name,$ErrorAction) + if ($Name -ne 'Fixture Service') { throw 'Unexpected service name' } + $service = [pscustomobject]@{} + $service | Add-Member ScriptMethod WaitForStatus { param($state,$timeout) + if ($state -ne 'Running' -or $scenario -eq 'service down') { throw 'Backup service unavailable' } + } + return $service + } + foreach ($case in @( + @('absent',0,0,0), @('current',0,0,0), @('newer',0,0,0), + @('busy',0,0,0), @('late plan',0,1,0), @('query failure',1,0,0), + @('download failure',1,1,0), @('already updated',0,1,0), @('window ended',0,1,0), + @('bad window',1,0,0), @('corrupt',1,1,0), @('success',0,1,1), + @('VM',0,1,1), @('failure',1,1,1), @('unverified',1,1,1), + @('service down',1,1,1), @('reboot',3010,1,1) + )) { + $scenario,$expected,$expectedDownloads,$expectedInstalls = $case + $kind = if ($scenario -eq 'VM') { 'VM' } else { 'Windows' } + $MSP360UpdateWindow = switch ($scenario) { + 'bad window' { '25:00-26:00' } + 'window ended' { '12:00-13:00' } + default { '' } + } + $record = @{ Downloads=0; Installs=0; Staged=$null } + $messages = & (Join-Path $repo 'rmm/Update-EmberkomCloudBackup.ps1') *>&1 + if ($LASTEXITCODE -ne $expected -or $record.Downloads -ne $expectedDownloads -or $record.Installs -ne $expectedInstalls) { + throw "$scenario failed. Exit=$LASTEXITCODE Downloads=$($record.Downloads) Installs=$($record.Installs). $messages" + } + if ($record.Staged -and (Test-Path -LiteralPath $record.Staged)) { throw "$scenario left staged media" } + Write-Host "PASS $scenario" + } + + # Check the provisioner's existing edition mapping at the new release-file boundary. + & { + function Import-MSP360Module {} + function Get-MBSAgent { $false } + function Get-EmberkomCloudBackupRelease($Build) { + $record.Selected = $Build + $record.AgentEdition = $AgentEdition + throw 'Stopped at release lookup' + } + foreach ($pair in @(@('desktop','Windows','desktop'), @('server','Windows','baremetal'), @('vm','VM','vmedition'))) { + $Edition = $pair[0] + $record = @{} + try { & (Join-Path $repo 'Install-EmberkomCloudBackup.ps1') } + catch { if ($_.Exception.Message -ne 'Stopped at release lookup') { throw } } + if ($record.Selected -ne $pair[1] -or $record.AgentEdition -ne $pair[2]) { throw "Wrong provisioning package for $Edition" } + Write-Host "PASS existing $Edition installer release selection" + } + } +} finally { + $fixtureCore = Join-Path $fixtureDir 'downloaded.ps1' + if (Test-Path -LiteralPath $fixtureCore) { Remove-Item -LiteralPath $fixtureCore -Force } + Remove-Item -LiteralPath $fixtureDir -Force +}