Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ jobs:
shell: pwsh
run: |
$now = Get-Date
$msi = "$($now.Year - 2000).$($now.Month).$($now.Day).$($now.ToString('HHmm'))"
"msi=$msi" | Out-File -Append $env:GITHUB_OUTPUT
$full = $now.ToString('yyyy.MM.dd.HHmm')
"full=$full" | Out-File -Append $env:GITHUB_OUTPUT

- name: Build CLI (managedbootstrapinstall.exe)
run: >
Expand Down Expand Up @@ -98,7 +98,7 @@ jobs:
"--configuration", "Release",
"--verbosity", "minimal",
"-p:Platform=${{ matrix.arch }}",
"-p:ProductVersion=${{ steps.version.outputs.msi }}",
"-p:FullVersion=${{ steps.version.outputs.full }}",
"-p:BinDir=$binDir",
"-p:AppDir=$appDir"
)
Expand Down
8 changes: 1 addition & 7 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,7 @@ jobs:
run: |
$tag = "${{ github.ref_name }}"
$full = $tag -replace '^v',''
if ($full -match '^(\d+)\.(\d+)\.(\d+)\.(\d+)$') {
$msi = "$([int]$Matches[1] - 2000).$([int]$Matches[2]).$([int]$Matches[3]).$($Matches[4])"
} else {
$msi = $full
}
"full=$full" | Out-File -Append $env:GITHUB_OUTPUT
"msi=$msi" | Out-File -Append $env:GITHUB_OUTPUT

- name: Build CLI (managedbootstrapinstall.exe)
run: >
Expand Down Expand Up @@ -152,7 +146,7 @@ jobs:
"--configuration", "Release",
"--verbosity", "detailed",
"-p:Platform=${{ matrix.arch }}",
"-p:ProductVersion=${{ steps.version.outputs.msi }}",
"-p:FullVersion=${{ steps.version.outputs.full }}",
"-p:BinDir=$binDir",
"-p:AppDir=$appDir"
)
Expand Down
4 changes: 4 additions & 0 deletions Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public static void Initialize(string logDirectory, string version = "Unknown", b
_verboseConsole = verboseConsole;
_silentMode = silentMode;
_sessionStartTime = DateTime.Now;
LogDirectory = logDirectory;

// Ensure log directory exists
if (!Directory.Exists(logDirectory))
Expand Down Expand Up @@ -449,6 +450,9 @@ public sealed record SessionOutcome(string Status, DateTime End, int Errors, int
/// <summary>Relabels the session with the mode the preflight chose.</summary>
public static void SetRunType(string runType) => _session?.SetRunType(runType);

/// <summary>The logs root this run's session directory sits under.</summary>
public static string? LogDirectory { get; private set; }

/// <summary>When this run's session started.</summary>
public static DateTime SessionStartTime => _sessionStartTime;

Expand Down
68 changes: 68 additions & 0 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,10 @@ private static int SaveSettingsFromArgs(string[] args)

// Initialize status tracking
StatusManager.Initialize(manifestUrl, Version);

// Looked at before the preflight, which consumes it: the throttle only looks.
bool forced = File.Exists(BaselineThrottle.ForceFilePath);

RunReport.Start(Version);
Logger.Debug($"Initialized status tracking with RunId: {StatusManager.GetCurrentRunId()}");

Expand Down Expand Up @@ -928,6 +932,24 @@ private static int SaveSettingsFromArgs(string[] args)
bool baseline = decision == PreflightDecision.Baseline;
if (baseline)
{
// Applied only once the preflight has chosen baseline, so provisioning is
// never limited. The manifest and preflight are small; a throttled run
// downloads no item.
var throttle = BaselineThrottle.Evaluate(BaselineThrottle.Read(), DateTimeOffset.Now,
ConfigManager.Instance.Config.BaselineMinIntervalHours, forced);
if (throttle.Skip)
{
Logger.WriteSkipped($"Baseline throttle: skipping this run: {throttle.Reason}");
RunReport.SetRunType(RunTypes.Skip);
StatusManager.SetPhaseStatus(InstallationPhase.SetupAssistant, InstallationStage.Skipped);
StatusManager.SetPhaseStatus(InstallationPhase.Userland, InstallationStage.Skipped);
Logger.WriteCompletion("Nothing downloaded: baseline throttled");
StatusManager.WriteSuccessfulCompletionRegistry();
await ReportManager.SendRunSummaryAsync(true, runStartUtc, Version, manifestUrl);
RunReport.Finish();
return ExitSuccess;
}
Logger.Info($"Baseline throttle: running ({throttle.Reason})");
Logger.Info("Baseline mode: refreshing setupassistant items without a dialog; userland is skipped.");
}
else
Expand Down Expand Up @@ -1567,6 +1589,44 @@ static async Task DownloadFile(string displayName, string url, string localPath)
Logger.WriteSubProgress("Downloaded", sizeText);
}

/// <summary>
/// The same checks as <see cref="BaselineSkipReason"/>, from manifest fields only:
/// the item's <c>hash</c> is in the install ledger, or an MSI item's
/// <c>productCode</c>/<c>upgradeCode</c> is installed at its <c>version</c> or newer.
/// Null when the manifest does not say enough, and the file is downloaded and
/// checked after.
/// </summary>
static string? BaselineSkipReasonBeforeDownload(JsonElement packageInfo, string type)
{
string? Field(string name) =>
packageInfo.ValueKind == JsonValueKind.Object &&
packageInfo.TryGetProperty(name, out var p) && p.ValueKind == JsonValueKind.String
? p.GetString() : null;

var hash = Field("hash");
if (!string.IsNullOrWhiteSpace(hash))
{
var bare = hash.Trim();
if (bare.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)) bare = bare[7..];
if (new InstallLedger().Contains(bare))
return "this file was already installed by BootstrapMate";
}

var version = Field("version");
var productCode = Field("productCode");
var upgradeCode = Field("upgradeCode");
if (type.Equals("msi", StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrWhiteSpace(version) &&
(!string.IsNullOrWhiteSpace(productCode) || !string.IsNullOrWhiteSpace(upgradeCode)))
{
var product = new MsiProduct.Info(productCode ?? "", version!, upgradeCode, PackageLabel(packageInfo));
if (MsiProduct.IsInstalledAtOrAbove(product, out var installed))
return $"version {installed} is installed (manifest version {version})";
}

return null;
}

/// <summary>
/// Why a baseline run can leave this file alone, or null when it must install it:
/// the same file is in the install ledger, or its MSI product is already
Expand Down Expand Up @@ -1599,6 +1659,14 @@ static async Task<bool> DownloadAndInstallPackage(string displayName, string url

try
{
// Baseline: decide from the manifest alone when possible, so an item that is
// already in place costs no download.
if (baseline && BaselineSkipReasonBeforeDownload(packageInfo, type) is { } earlySkip)
{
Logger.WriteSkipped($"{displayName} - {earlySkip} (not downloaded)");
return false;
}

DialogManager.Instance.NotifyDownloadStarted(displayName);
await DownloadFile(displayName, url, localPath);

Expand Down
47 changes: 45 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,11 @@ the preflight has decided, it is rewritten with `skip`, `baseline` or
run. It is written atomically when the run starts, with status `running`, and
again when the session closes. At the start, `end_time` and `duration_seconds` are
`null` and `items` is empty. Its status values match `session.json`: `running`,
`completed`, `partial_failure` (some items failed), and `failed` (the preflight
failed or the manifest would not load). The time in the `--last-run` line is UTC
`completed`, `partial_failure` (some items failed), `failed` (the preflight
failed or the manifest would not load), and `interrupted`: a run that died without
recording its end (a reboot, a killed process). The next run finds the record still
at `running`, relabels that run's `session.json`, and logs a warning before it
writes its own record. The time in the `--last-run` line is UTC
to the minute.

```json
Expand Down Expand Up @@ -214,6 +217,46 @@ install run started without elevation and without an interactive console (a scri
a remote shell, redirected input) exits `3` instead of waiting at the elevation
prompt.

## Baseline throttle

Every baseline run downloads from the package host, so baselines are rate-limited.
The check runs only after the preflight has chosen baseline, so provisioning is never
limited. It reads `C:\ProgramData\ManagedBootstrap\baseline.json`, which holds the
last baseline's `end_time`, `status` and `consecutive_failures`. `last-run.json`
cannot hold the clock, because every run rewrites it.

| Last baseline | Next baseline |
|---|---|
| Completed less than `BaselineMinIntervalHours` ago (default 144) | Skips |
| Failed, partially failed or interrupted for the first time | One retry after 24 hours, never sooner |
| Failed again after that retry | Waits the full interval |
| None: a provisioning run clears the record | Runs |
| Any, with `C:\ProgramData\ManagedBootstrap\.bootstrap_force` present | Runs; the preflight consumes the file |

A throttled run fetches the manifest and runs the preflight, then downloads nothing.
It logs why, ends as `skip`, records SetupAssistant and Userland as `Skipped` in
`status.json`, and leaves `baseline.json` alone. `--force` does not bypass the
throttle. `BaselineMinIntervalHours` comes from policy or the settings registry
(0-8760; 0 disables the limit for completed runs).

A baseline run also skips an item without downloading it when the manifest says
enough: its `hash` is already in the install ledger, or an `msi` item's `productCode`
or `upgradeCode` is installed at its `version` (the MSI ProductVersion) or newer.
Without those fields, the file is downloaded and checked afterwards.

## Versions

Everything carries the build stamp `YYYY.MM.DD.HHMM`: file and assembly versions,
`--version`, `HKLM\SOFTWARE\BootstrapMate\Version` (the Intune detection value),
logs, `last-run.json` and release tags.

The MSI ProductVersion is the only exception. Windows Installer fields are numeric
(255.255.65535), and upgrades compare only the first three fields, so the MSI uses
`YY.M.DDHH.MM`: `2026.10.04.1951` is `26.10.419.51`. Upgrades compare to the hour.
Two builds made in the same hour compare equal and do not upgrade each other, so
publish at most one build per hour. Pass `-p:FullVersion=YYYY.MM.DD.HHMM` to the
installer project; it derives the ProductVersion.

## Downloads

Package downloads stream to disk with no overall HTTP timeout. An attempt fails when
Expand Down
28 changes: 28 additions & 0 deletions RunReport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public static void Start(string version)
{
lock (_lock)
{
RecoverInterruptedRun();
_record = new LastRunRecord
{
SessionId = Logger.GetSessionId() ?? "",
Expand All @@ -29,6 +30,26 @@ public static void Start(string version)
}
}

/// <summary>
/// A last-run.json still at "running" belongs to a run that died: this run holds the
/// single-instance lock, so none other is going. Its session is relabelled
/// "interrupted", and an interrupted baseline counts as a failed one, so the throttle
/// gives it one retry a day later instead of letting whatever killed it loop.
/// </summary>
private static void RecoverInterruptedRun()
{
var orphan = LastRunFile.MarkInterrupted(LastRunFile.Read(), Logger.LogDirectory);
if (orphan is null) return;

Logger.Warning($"Previous run {orphan.SessionId} ({orphan.RunType}, started {orphan.StartTime}) " +
"never finished; recorded as interrupted");
if (string.Equals(orphan.RunType, RunTypes.Baseline, StringComparison.OrdinalIgnoreCase))
{
var when = DateTimeOffset.TryParse(orphan.StartTime, out var started) ? started : DateTimeOffset.Now;
BaselineThrottle.Write(BaselineThrottle.After(BaselineThrottle.Read(), RunStatuses.Interrupted, when));
}
}

public static void SetRunType(string runType)
{
Logger.SetRunType(runType);
Expand Down Expand Up @@ -72,6 +93,13 @@ public static void Finish(string? status = null)
_record.Errors = outcome.Errors;
_record.Warnings = outcome.Warnings;
LastRunFile.Write(_record);

// The baseline clock: a baseline sets it, a provisioning run clears it (a
// machine provisioned again starts over), a skip leaves it alone.
if (_record.RunType == RunTypes.Baseline)
BaselineThrottle.Write(BaselineThrottle.After(BaselineThrottle.Read(), outcome.Status, new DateTimeOffset(outcome.End)));
else if (_record.RunType == RunTypes.Provisioning && outcome.Status == RunStatuses.Completed)
BaselineThrottle.Clear();
}
}

Expand Down
16 changes: 6 additions & 10 deletions build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1507,14 +1507,10 @@ function Update-Version {
$newVersion = "$year.$month.$day.$revision"
Write-Log "Updating version to: $newVersion (YYYY.MM.DD.HHMM format for Intune compatibility)" "INFO"

# Create MSI-compatible version (major.minor.build < 65536)
# Convert YYYY.MM.DD.HHMM to YY.MM.DD.HHMM for MSI ProductVersion
$now = Get-Date
$msiMajor = $now.Year - 2000 # e.g., 25 for 2025
$msiMinor = [int]$now.ToString("MM") # e.g., 9 for September
$msiBuild = [int]$now.ToString("dd") # e.g., 2 for 2nd day
$msiRevision = [int]$now.ToString("HHmm") # e.g., 2141 for 21:41
$msiVersion = "$msiMajor.$msiMinor.$msiBuild.$msiRevision"
# MSI ProductVersion is YY.M.DDHH.MM (Windows Installer compares only the first
# three fields, so the hour has to be in them). The wixproj derives the same value
# from FullVersion; this copy is only for the log.
$msiVersion = "{0}.{1}.{2}.{3}" -f ($now.Year - 2000), $now.Month, ($now.Day * 100 + $now.Hour), $now.Minute

Write-Log "MSI ProductVersion: $msiVersion (MSI-compliant format)" "INFO"

Expand All @@ -1536,7 +1532,7 @@ function Update-Version {
# Return version information regardless of whether static version was found
return @{
FullVersion = $newVersion # YYYY.MM.DD.HHMM for Intune detection
MsiVersion = $msiVersion # YY.MM.DD.HHMM for MSI ProductVersion
MsiVersion = $msiVersion # YY.M.DDHH.MM for MSI ProductVersion
}
}

Expand Down Expand Up @@ -1571,7 +1567,7 @@ function Build-MSI {
"--configuration", "Release",
"--verbosity", "normal",
"-p:Platform=$Arch",
"-p:ProductVersion=$($versionInfo.MsiVersion)",
"-p:FullVersion=$($versionInfo.FullVersion)",
"-p:BinDir=$binDirAbsolute"
)
if ($appDirAbsolute) {
Expand Down
11 changes: 10 additions & 1 deletion installer/BootstrapMate.Installer.wixproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,23 @@
</PropertyGroup>

<PropertyGroup>
<!-- FullVersion is the build stamp everything else carries (YYYY.MM.DD.HHMM): file
versions, the CLI's version, HKLM\SOFTWARE\BootstrapMate\Version, logs and
release tags. Windows Installer fields are numeric (255.255.65535) and only the
first three are compared for upgrades, so the MSI ProductVersion is derived as
YY.M.DDHH.MM: upgrades compare to the hour and the minutes ride in the fourth
field. Two builds in the same hour compare equal; publish at most one per hour.
Same scheme as cimipkg (ReportMate 2026.09.15.21xx -> 26.9.1521). -->
<ProductVersion Condition="'$(ProductVersion)' == '' and '$(FullVersion)' != ''">$([System.Text.RegularExpressions.Regex]::Replace('$(FullVersion)', '^20(\d\d)\.0?(\d{1,2})\.0?(\d{1,2})\.(\d\d)0?(\d{1,2})$', '$1.$2.$3$4.$5'))</ProductVersion>
<ProductVersion Condition="'$(ProductVersion)' == ''">0.0.0</ProductVersion>
<FullVersion Condition="'$(FullVersion)' == ''">$(ProductVersion)</FullVersion>
<BinDir Condition="'$(BinDir)' == ''">$(MSBuildProjectDirectory)\..\publish\executables\$(Platform)</BinDir>
<AppDir Condition="'$(AppDir)' == ''">$(MSBuildProjectDirectory)\..\publish\app\$(Platform)</AppDir>
<SbinDir Condition="'$(SbinDir)' == ''">$(MSBuildProjectDirectory)\sbin-staging</SbinDir>
</PropertyGroup>

<PropertyGroup>
<DefineConstants>BIN_DIR=$(BinDir);APP_DIR=$(AppDir);SBIN_DIR=$(SbinDir);ProductVersion=$(ProductVersion)</DefineConstants>
<DefineConstants>BIN_DIR=$(BinDir);APP_DIR=$(AppDir);SBIN_DIR=$(SbinDir);ProductVersion=$(ProductVersion);FullVersion=$(FullVersion)</DefineConstants>
</PropertyGroup>

<ItemGroup>
Expand Down
7 changes: 5 additions & 2 deletions installer/Product.wxs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
<?ifndef ProductVersion?>
<?define ProductVersion = "0.0.0"?>
<?endif?>
<?ifndef FullVersion?>
<?define FullVersion = $(var.ProductVersion)?>
<?endif?>
<!-- Package Definition -->
<Package Name="Managed Bootstrap Install"
Version="$(var.ProductVersion)"
Expand Down Expand Up @@ -70,11 +73,11 @@
<!-- Registry entries for installation tracking AND detection -->
<Component Id="RegistryEntries" Directory="INSTALLDIR" Guid="E5F6A7B8-C9D0-1234-EF56-789012345ABC">
<RegistryValue Root="HKLM" Key="SOFTWARE\BootstrapMate" Name="InstallPath" Value="[INSTALLDIR]" Type="string" />
<RegistryValue Root="HKLM" Key="SOFTWARE\BootstrapMate" Name="Version" Value="$(var.ProductVersion)" Type="string" />
<RegistryValue Root="HKLM" Key="SOFTWARE\BootstrapMate" Name="Version" Value="$(var.FullVersion)" Type="string" />
<RegistryValue Root="HKLM" Key="SOFTWARE\BootstrapMate" Name="InstallDate" Value="[Date]" Type="string" />
<RegistryValue Root="HKLM" Key="SOFTWARE\BootstrapMate" Name="Architecture" Value="[ProcessorArchitecture]" Type="string" />
<!-- LastRunVersion for Intune detection - must match version in deploy.ps1 detection rule -->
<RegistryValue Root="HKLM" Key="SOFTWARE\BootstrapMate" Name="LastRunVersion" Value="$(var.ProductVersion)" Type="string" />
<RegistryValue Root="HKLM" Key="SOFTWARE\BootstrapMate" Name="LastRunVersion" Value="$(var.FullVersion)" Type="string" />
</Component>

<!-- Machine-level fallback settings: ConfigManager reads HKLM\SOFTWARE\BootstrapMate\Settings
Expand Down
13 changes: 13 additions & 0 deletions resources/BootstrapMate.admx
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,19 @@
</elements>
</policy>

<policy name="BaselineMinIntervalHours"
class="Machine"
displayName="$(string.BaselineMinIntervalHours)"
explainText="$(string.BaselineMinIntervalHours_Help)"
key="SOFTWARE\Policies\BootstrapMate"
presentation="$(presentation.BaselineMinIntervalHours)">
<parentCategory ref="Advanced" />
<supportedOn ref="windows:SUPPORTED_Windows_10_0" />
<elements>
<decimal id="BaselineMinIntervalHours_Value" valueName="BaselineMinIntervalHours" minValue="0" maxValue="8760" />
</elements>
</policy>

<!-- ═══ Reporting ═══ -->

<policy name="ReportingUrl"
Expand Down
Loading
Loading