From 3bbd5d1b55104fc08e88d1cfb7c141b5525bfdc3 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 20 Oct 2026 16:08:43 -0700 Subject: [PATCH] Personalize Windows clones with one boot Retain the template computer name, apply the chosen account and password, and refresh the interactive session without rebooting. Publish windows-v4 while preserving the windows-v3 seed contract. Fresh v11 validation reached ready in 59.88 seconds and confirmed the account, capture session, and password. Assisted-by: gpt-6-astra --- guest/windows-provision.ps1 | 63 ++++++++++++++++++++------------- tools/dashboard-vms-test.py | 12 +++++++ tools/prepare-windows-preset.py | 2 +- tools/vms.py | 22 ++++++------ tools/windows-presets.md | 25 +++++++++++-- 5 files changed, 85 insertions(+), 39 deletions(-) diff --git a/guest/windows-provision.ps1 b/guest/windows-provision.ps1 index 56c9bbad38019a257ff20a84a9d67233e1bded7c..08155d022ba125dd8ae10f199dd8a257ac7b4497 100644 --- a/guest/windows-provision.ps1 +++ b/guest/windows-provision.ps1 @@ -55,48 +55,61 @@ try { $pair = $line.Split('=', 2) if ($pair.Count -eq 2) { $values[$pair[0]] = $pair[1] } } - if (Test-Path "$status\restarting") { - if ($env:COMPUTERNAME -ine $values['HOSTNAME']) { throw 'The VM name was not applied.' } - $scheduler = New-Object -ComObject Schedule.Service - $scheduler.Connect() - $tasks = $scheduler.GetFolder('\').GetTasks(1) | Where-Object { $_.Name -like 'SnowglobeGuest-*' } - foreach ($task in $tasks) { $task.Enabled = $true } - $deadline = (Get-Date).AddMinutes(2) - while (!(Get-Process explorer -ErrorAction SilentlyContinue)) { - if ((Get-Date) -gt $deadline) { throw 'The desktop did not start.' } - Start-Sleep -Milliseconds 250 - } - foreach ($task in $tasks) { $task.Run($null) | Out-Null } - while (!(Get-Process explorer -ErrorAction SilentlyContinue) -or !(Get-Process snowglobe-guest -ErrorAction SilentlyContinue)) { - if ((Get-Date) -gt $deadline) { throw 'The desktop did not start.' } - Start-Sleep -Milliseconds 250 - } - Set-SetupStatus ready - return - } $username = $values['USERNAME'] $password = $values['PASSWORD'] - $hostname = $values['HOSTNAME'] if ($username -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,19}$') { throw 'The VM account name is unsupported.' } if ($password.Length -lt 12 -or $password.Length -gt 128 -or $password -match '[\r\n]') { throw 'The VM password is malformed.' } - if ($hostname -notmatch '^sgvm-[a-f0-9]{8}$') { throw 'The VM name is malformed.' } $sid = Get-Content "$root\template.sid" $user = Get-LocalUser | Where-Object { $_.SID.Value -eq $sid } if (!$user) { throw 'The template account is missing.' } if (Get-LocalUser | Where-Object { $_.Name -ieq $username -and $_.SID.Value -ne $sid }) { throw 'The VM account name is already in use.' } + $deadline = (Get-Date).AddMinutes(3) + function Find-Desktop { + Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { + $_.SessionId -gt 0 -and (Invoke-CimMethod $_ -MethodName GetOwnerSid -ErrorAction SilentlyContinue).Sid -eq $sid + } | Select-Object -First 1 + } + $desktop = Find-Desktop + while (!$desktop) { + if ((Get-Date) -gt $deadline) { throw 'The template desktop did not start.' } + Start-Sleep -Milliseconds 250 + $desktop = Find-Desktop + } $user | Set-LocalUser -Password (ConvertTo-SecureString $password -AsPlainText -Force) -PasswordNeverExpires $true if ($user.Name -ine $username) { $user | Rename-LocalUser -NewName $username } - Rename-Computer -NewName $hostname -Force Set-ItemProperty $winlogon AutoAdminLogon '1' Set-ItemProperty $winlogon DefaultUserName $username - Set-ItemProperty $winlogon DefaultDomainName $hostname + Set-ItemProperty $winlogon DefaultDomainName $env:COMPUTERNAME Set-ItemProperty $winlogon DefaultPassword $password Remove-ItemProperty $winlogon AutoLogonCount -ErrorAction SilentlyContinue - Set-SetupStatus restarting - Restart-Computer -Force + $scheduler = New-Object -ComObject Schedule.Service + $scheduler.Connect() + $task = $scheduler.GetFolder('\').GetTask("SnowglobeGuest-$sid") + $task.Enabled = $true + Set-ItemProperty $winlogon ForceAutoLogon '1' + Set-SetupStatus signingIn + & "$env:WINDIR\System32\logoff.exe" $desktop.SessionId + if ($LASTEXITCODE -ne 0) { throw 'The template session could not sign out.' } + do { + if ((Get-Date) -gt $deadline) { throw 'The personalized desktop did not start.' } + Start-Sleep -Milliseconds 250 + $fresh = Find-Desktop + } while (!$fresh -or ($fresh.ProcessId -eq $desktop.ProcessId -and $fresh.CreationDate -eq $desktop.CreationDate)) + $task.Run($null) | Out-Null + do { + if ((Get-Date) -gt $deadline) { throw 'Desktop capture did not start.' } + Start-Sleep -Milliseconds 250 + $capture = Get-CimInstance Win32_Process -Filter "Name='snowglobe-guest.exe'" | Where-Object { + $_.SessionId -eq $fresh.SessionId -and (Invoke-CimMethod $_ -MethodName GetOwnerSid -ErrorAction SilentlyContinue).Sid -eq $sid + } + } while (!$capture) + Set-SetupStatus ready } catch { if ($Prepare) { throw } Set-SetupStatus failed Add-Content "$root\setup.log" $_.Exception.Message exit 1 } +finally { + Remove-ItemProperty $winlogon ForceAutoLogon -ErrorAction SilentlyContinue +} diff --git a/tools/dashboard-vms-test.py b/tools/dashboard-vms-test.py index 3163411e563e39f322865648f3d3f8ae8a3a9d16..d403aad0ca3e22efd66973c0bb164d52a9ff944b 100644 --- a/tools/dashboard-vms-test.py +++ b/tools/dashboard-vms-test.py @@ -150,6 +150,18 @@ class VMTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'Windows'): vms.windows_seed(directory, 'bad\\nname') + def test_one_boot_windows_seed_does_not_claim_a_new_computer_name(self): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + seeds = [] + with patch.object(vms, 'command', side_effect=lambda *args, **kwargs: seeds.append(Path(args[-1]).read_text()) or ''): + vms.windows_seed(directory, 'fixture', rename=False) + self.assertNotIn('HOSTNAME=', seeds[0]) + access = json.loads((directory / 'access.json').read_text()) + self.assertEqual(access['hostname'], '') + self.assertEqual(access['username'], 'fixture') + self.assertGreaterEqual(len(access['password']), 12) + def test_nixos_seed_uses_mutable_gdm_path_and_native_sshd(self): with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) diff --git a/tools/prepare-windows-preset.py b/tools/prepare-windows-preset.py index 8c621389975c16b7903bdf52542a4b8ab9c3269d..e89715856f9331dcbdd8d097ae21958cf70df8c0 100644 --- a/tools/prepare-windows-preset.py +++ b/tools/prepare-windows-preset.py @@ -62,6 +62,6 @@ while vms.virsh('domstate', args.name).strip() != 'shut off': raise TimeoutError('The template did not shut down.') time.sleep(.5) vms.save_preset({'name': args.name, 'id': args.id, 'os': preset['os'], - 'description': 'Prepared desktop with cursor integration', 'setup': 'windows-v3', 'supersedes': args.supersedes}) + 'description': 'Prepared desktop with cursor integration', 'setup': 'windows-v4', 'supersedes': args.supersedes}) (vms.PRESETS / args.id / 'disk.qcow2').chmod(0o440) print(args.id) diff --git a/tools/vms.py b/tools/vms.py index b9e83a067faab71863358c244e35fd6df09995a4..f93369ee1f06ec23f237a24f181fd0027c458c23 100644 --- a/tools/vms.py +++ b/tools/vms.py @@ -313,7 +313,7 @@ def domains(): "autostart": re.search(r"^Autostart:\s+enable", virsh("dominfo", name), re.MULTILINE) is not None, "startedAt": started, "agent": agent.get("state", "disconnected") if agent is not None else None, - "setup": windows_setup(name) if setup == "windows-v3" and state == "running" else None, + "setup": windows_setup(name) if setup in {"windows-v3", "windows-v4"} and state == "running" else None, "disks": disks, "media": media, "firmware": "uefi" if root.find("./os/loader") is not None or root.find("os").get("firmware") == "efi" else "bios", @@ -327,7 +327,7 @@ def domains(): def windows_setup(name): - for stage in ["ready", "failed", "restarting", "personalizing"]: + for stage in ["ready", "failed", "signingIn", "restarting", "personalizing"]: try: handle = json.loads(virsh("qemu-agent-command", name, json.dumps({"execute": "guest-file-open", "arguments": {"path": "C:\\Snowglobe\\setup\\" + stage, "mode": "r"}}), "--timeout", "1"))["return"] except (subprocess.CalledProcessError, ValueError, KeyError, TypeError): @@ -526,7 +526,7 @@ def save_preset(spec): root = transition.normalize_vm(ET.fromstring(virsh("dumpxml", name, "--inactive"))) if root.findtext(f"metadata/{NS}vm/{NS}platform") == "macos": raise ValueError("Use a prepared OS X preset from the OS library.") - if root.findtext(f"metadata/{NS}vm/{NS}setup") in {"windows-v2", "windows-v3"} and spec.get("setup") != "windows-v3": + if root.findtext(f"metadata/{NS}vm/{NS}setup") in {"windows-v2", "windows-v3", "windows-v4"} and spec.get("setup") not in {"windows-v3", "windows-v4"}: raise ValueError("Prepare a Windows template before publishing another preset.") disks = root.findall("./devices/disk[@device='disk']") if len(disks) != 1 or root.findall("./devices/hostdev"): @@ -573,8 +573,8 @@ def save_preset(spec): "capacity": details["virtual-size"], "createdAt": int(time.time()), "recommended": {"vcpus": int(root.findtext("vcpu", "2")), "memory": int(root.findtext("memory")) * 1024, "disk": details["virtual-size"]}} - if spec.get("setup") == "windows-v3" and platform == "windows": - preset["setup"] = "windows-v3" + if spec.get("setup") in {"windows-v3", "windows-v4"} and platform == "windows": + preset["setup"] = spec["setup"] if supersedes := spec.get("supersedes"): ensure_name(supersedes) preset["supersedes"] = supersedes @@ -666,14 +666,14 @@ fi command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "cidata", "-joliet", "-rock", str(files / "user-data"), str(files / "meta-data")) -def windows_seed(directory, username): +def windows_seed(directory, username, *, rename=True): if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,19}", username): raise ValueError("Use an account username suitable for a Windows guest.") - hostname = "sgvm-" + secrets.token_hex(4) + hostname = "sgvm-" + secrets.token_hex(4) if rename else "" password = guest_access(directory, username, hostname) with tempfile.TemporaryDirectory(prefix=".seed-", dir=directory) as temporary: marker = Path(temporary) / "SNOWGLOB.INI" - marker.write_text(f"[snowglobe]\nUSERNAME={username}\nPASSWORD={password}\nHOSTNAME={hostname}\n") + marker.write_text(f"[snowglobe]\nUSERNAME={username}\nPASSWORD={password}\n" + (f"HOSTNAME={hostname}\n" if rename else "")) command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "SNOWGLOBE", "-joliet", "-rock", str(marker)) @@ -785,8 +785,8 @@ def create(spec): ET.SubElement(metadata, NS + "platform").text = spec["platform"] ET.SubElement(metadata, NS + "hardwareProfile").text = profile_name ET.SubElement(metadata, NS + "owner").text = spec["owner"] - if preset and preset.get("setup") == "windows-v3": - ET.SubElement(metadata, NS + "setup").text = "windows-v3" + if preset and preset.get("setup") in {"windows-v3", "windows-v4"}: + ET.SubElement(metadata, NS + "setup").text = preset["setup"] ET.SubElement(root, "memory", unit="bytes").text = str(spec["memory"]) ET.SubElement(root, "vcpu").text = str(spec["vcpus"]) firmware = spec["firmware"] @@ -875,7 +875,7 @@ def create(spec): ET.SubElement(seed, "serial").text = "snowglobe-cloud-init" ET.SubElement(seed, "readonly") if preset and spec["platform"] == "windows": - windows_seed(directory, spec["username"]) + windows_seed(directory, spec["username"], rename=preset.get("setup") != "windows-v4") ET.SubElement(cd, "source", file=str(directory / "seed.iso")) ET.SubElement(cd, "serial").text = "snowglobe-provision" if spec["platform"] == "macos": diff --git a/tools/windows-presets.md b/tools/windows-presets.md index 4e070a07a10d822232e40cb8c863dfefd62d5d0e..8176d230de3750d823d3b3b30c69dd7d1622a969 100644 --- a/tools/windows-presets.md +++ b/tools/windows-presets.md @@ -10,16 +10,21 @@ Prepare an isolated template with its account named `sandbox`, then run that script with `-Prepare` from elevated 64-bit Windows PowerShell. Preparation randomizes the template password, removes clone identity and completion state, and installs the startup task. Shut down normally before capturing through -`vms.save_preset` with `setup=windows-v3`. The dashboard deliberately rejects +`vms.save_preset` with `setup=windows-v4`. The dashboard deliberately rejects ordinary Windows preset capture because it cannot establish preparation. Validate fresh clones with different account names before publication. Check -the personalized account and computer name, the `ready` marker, Explorer, +the personalized account, unchanged computer name, one boot, the `ready` marker, Explorer, the guest capture process, and the actual dashboard screen and input. Compare the published disk and NVRAM bytes with the tested candidate, and check that the disk is standalone with `qemu-img info` and `qemu-img check`. Never replace an existing base in place. +New clones retain the template computer name. Account personalization uses one +sign-out/sign-in so the desktop inherits the selected username, without a second +OS boot. Each clone still gets a separate password, MAC address, and DHCP lease. +Published `windows-v3` bases keep their original rename-and-reboot seed contract. + ## 2026-10-20 rollout The `windows-10-pro-v10` candidate was prepared and tested on HDD storage with @@ -82,3 +87,19 @@ The restricted raw trace is `/var/lib/snowglobe/retirements/vms-20261020/windows-boot-trace.json`. The trace guest was shut down and removed afterward; the published preset and personal Mac remained intact. + +## One-boot rollout + +`windows-10-pro-v11` supersedes v10 and uses `windows-v4`: the computer name stays +unchanged, while the selected username and a fresh password are applied to the +existing account SID/profile. A targeted sign-out/sign-in refreshes the desktop +environment. The SID-bound capture task starts in the new interactive session. +Temporary `ForceAutoLogon` is removed on both success and failure. + +With four vCPUs, 4 GiB RAM and a 64 GiB HDD overlay, the candidate reached ready +in 60.10 seconds; a fresh clone of the published v11 reached ready in 59.88 +seconds. That is about 36 seconds faster than the quiet-host v10 trace above. +Both machines kept the template computer name and had one Kernel-General boot +event since creation. Interactive username, SID/profile, password authentication, +Explorer and capture session ownership, and removal of `ForceAutoLogon` were +checked. These are individual runs with differing cache warmth. -- 2.54.1