authoravatarclover caruso<git@paperclover.net>2026-10-20 16:08:43-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-21 02:52:29-07:00
log3bbd5d1b55104fc08e88d1cfb7c141b5525bfdc3
treeba7e44b45c71a43b212c0bcf4bbd3ca69e7eff0c
parentb58af12506db1360952b0e6832425927c5cd8ab9
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

5 files changed, 85 insertions(+), 39 deletions(-)

guest/windows-provision.ps1+38-25
...@@ -55,48 +55,61 @@ try {...@@ -55,48 +55,61 @@ try {
55 $pair = $line.Split('=', 2)55 $pair = $line.Split('=', 2)
56 if ($pair.Count -eq 2) { $values[$pair[0]] = $pair[1] }56 if ($pair.Count -eq 2) { $values[$pair[0]] = $pair[1] }
57 }57 }
58 if (Test-Path "$status\restarting") {
59 if ($env:COMPUTERNAME -ine $values['HOSTNAME']) { throw 'The VM name was not applied.' }
60 $scheduler = New-Object -ComObject Schedule.Service
61 $scheduler.Connect()
62 $tasks = $scheduler.GetFolder('\').GetTasks(1) | Where-Object { $_.Name -like 'SnowglobeGuest-*' }
63 foreach ($task in $tasks) { $task.Enabled = $true }
64 $deadline = (Get-Date).AddMinutes(2)
65 while (!(Get-Process explorer -ErrorAction SilentlyContinue)) {
66 if ((Get-Date) -gt $deadline) { throw 'The desktop did not start.' }
67 Start-Sleep -Milliseconds 250
68 }
69 foreach ($task in $tasks) { $task.Run($null) | Out-Null }
70 while (!(Get-Process explorer -ErrorAction SilentlyContinue) -or !(Get-Process snowglobe-guest -ErrorAction SilentlyContinue)) {
71 if ((Get-Date) -gt $deadline) { throw 'The desktop did not start.' }
72 Start-Sleep -Milliseconds 250
73 }
74 Set-SetupStatus ready
75 return
76 }
77 $username = $values['USERNAME']58 $username = $values['USERNAME']
78 $password = $values['PASSWORD']59 $password = $values['PASSWORD']
79 $hostname = $values['HOSTNAME']
80 if ($username -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,19}$') { throw 'The VM account name is unsupported.' }60 if ($username -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,19}$') { throw 'The VM account name is unsupported.' }
81 if ($password.Length -lt 12 -or $password.Length -gt 128 -or $password -match '[\r\n]') { throw 'The VM password is malformed.' }61 if ($password.Length -lt 12 -or $password.Length -gt 128 -or $password -match '[\r\n]') { throw 'The VM password is malformed.' }
82 if ($hostname -notmatch '^sgvm-[a-f0-9]{8}$') { throw 'The VM name is malformed.' }
83 $sid = Get-Content "$root\template.sid"62 $sid = Get-Content "$root\template.sid"
84 $user = Get-LocalUser | Where-Object { $_.SID.Value -eq $sid }63 $user = Get-LocalUser | Where-Object { $_.SID.Value -eq $sid }
85 if (!$user) { throw 'The template account is missing.' }64 if (!$user) { throw 'The template account is missing.' }
86 if (Get-LocalUser | Where-Object { $_.Name -ieq $username -and $_.SID.Value -ne $sid }) { throw 'The VM account name is already in use.' }65 if (Get-LocalUser | Where-Object { $_.Name -ieq $username -and $_.SID.Value -ne $sid }) { throw 'The VM account name is already in use.' }
66 $deadline = (Get-Date).AddMinutes(3)
67 function Find-Desktop {
68 Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object {
69 $_.SessionId -gt 0 -and (Invoke-CimMethod $_ -MethodName GetOwnerSid -ErrorAction SilentlyContinue).Sid -eq $sid
70 } | Select-Object -First 1
71 }
72 $desktop = Find-Desktop
73 while (!$desktop) {
74 if ((Get-Date) -gt $deadline) { throw 'The template desktop did not start.' }
75 Start-Sleep -Milliseconds 250
76 $desktop = Find-Desktop
77 }
87 $user | Set-LocalUser -Password (ConvertTo-SecureString $password -AsPlainText -Force) -PasswordNeverExpires $true78 $user | Set-LocalUser -Password (ConvertTo-SecureString $password -AsPlainText -Force) -PasswordNeverExpires $true
88 if ($user.Name -ine $username) { $user | Rename-LocalUser -NewName $username }79 if ($user.Name -ine $username) { $user | Rename-LocalUser -NewName $username }
89 Rename-Computer -NewName $hostname -Force
90 Set-ItemProperty $winlogon AutoAdminLogon '1'80 Set-ItemProperty $winlogon AutoAdminLogon '1'
91 Set-ItemProperty $winlogon DefaultUserName $username81 Set-ItemProperty $winlogon DefaultUserName $username
92 Set-ItemProperty $winlogon DefaultDomainName $hostname82 Set-ItemProperty $winlogon DefaultDomainName $env:COMPUTERNAME
93 Set-ItemProperty $winlogon DefaultPassword $password83 Set-ItemProperty $winlogon DefaultPassword $password
94 Remove-ItemProperty $winlogon AutoLogonCount -ErrorAction SilentlyContinue84 Remove-ItemProperty $winlogon AutoLogonCount -ErrorAction SilentlyContinue
95 Set-SetupStatus restarting85 $scheduler = New-Object -ComObject Schedule.Service
96 Restart-Computer -Force86 $scheduler.Connect()
87 $task = $scheduler.GetFolder('\').GetTask("SnowglobeGuest-$sid")
88 $task.Enabled = $true
89 Set-ItemProperty $winlogon ForceAutoLogon '1'
90 Set-SetupStatus signingIn
91 & "$env:WINDIR\System32\logoff.exe" $desktop.SessionId
92 if ($LASTEXITCODE -ne 0) { throw 'The template session could not sign out.' }
93 do {
94 if ((Get-Date) -gt $deadline) { throw 'The personalized desktop did not start.' }
95 Start-Sleep -Milliseconds 250
96 $fresh = Find-Desktop
97 } while (!$fresh -or ($fresh.ProcessId -eq $desktop.ProcessId -and $fresh.CreationDate -eq $desktop.CreationDate))
98 $task.Run($null) | Out-Null
99 do {
100 if ((Get-Date) -gt $deadline) { throw 'Desktop capture did not start.' }
101 Start-Sleep -Milliseconds 250
102 $capture = Get-CimInstance Win32_Process -Filter "Name='snowglobe-guest.exe'" | Where-Object {
103 $_.SessionId -eq $fresh.SessionId -and (Invoke-CimMethod $_ -MethodName GetOwnerSid -ErrorAction SilentlyContinue).Sid -eq $sid
104 }
105 } while (!$capture)
106 Set-SetupStatus ready
97} catch {107} catch {
98 if ($Prepare) { throw }108 if ($Prepare) { throw }
99 Set-SetupStatus failed109 Set-SetupStatus failed
100 Add-Content "$root\setup.log" $_.Exception.Message110 Add-Content "$root\setup.log" $_.Exception.Message
101 exit 1111 exit 1
102}112}
113finally {
114 Remove-ItemProperty $winlogon ForceAutoLogon -ErrorAction SilentlyContinue
115}
tools/dashboard-vms-test.py+12
...@@ -150,6 +150,18 @@ class VMTests(unittest.TestCase):...@@ -150,6 +150,18 @@ class VMTests(unittest.TestCase):
150 with self.assertRaisesRegex(ValueError, 'Windows'):150 with self.assertRaisesRegex(ValueError, 'Windows'):
151 vms.windows_seed(directory, 'bad\\nname')151 vms.windows_seed(directory, 'bad\\nname')
152152
153 def test_one_boot_windows_seed_does_not_claim_a_new_computer_name(self):
154 with tempfile.TemporaryDirectory() as temporary:
155 directory = Path(temporary)
156 seeds = []
157 with patch.object(vms, 'command', side_effect=lambda *args, **kwargs: seeds.append(Path(args[-1]).read_text()) or ''):
158 vms.windows_seed(directory, 'fixture', rename=False)
159 self.assertNotIn('HOSTNAME=', seeds[0])
160 access = json.loads((directory / 'access.json').read_text())
161 self.assertEqual(access['hostname'], '')
162 self.assertEqual(access['username'], 'fixture')
163 self.assertGreaterEqual(len(access['password']), 12)
164
153 def test_nixos_seed_uses_mutable_gdm_path_and_native_sshd(self):165 def test_nixos_seed_uses_mutable_gdm_path_and_native_sshd(self):
154 with tempfile.TemporaryDirectory() as temporary:166 with tempfile.TemporaryDirectory() as temporary:
155 directory = Path(temporary)167 directory = Path(temporary)
tools/prepare-windows-preset.py+1-1
...@@ -62,6 +62,6 @@ while vms.virsh('domstate', args.name).strip() != 'shut off':...@@ -62,6 +62,6 @@ while vms.virsh('domstate', args.name).strip() != 'shut off':
62 raise TimeoutError('The template did not shut down.')62 raise TimeoutError('The template did not shut down.')
63 time.sleep(.5)63 time.sleep(.5)
64vms.save_preset({'name': args.name, 'id': args.id, 'os': preset['os'],64vms.save_preset({'name': args.name, 'id': args.id, 'os': preset['os'],
65 'description': 'Prepared desktop with cursor integration', 'setup': 'windows-v3', 'supersedes': args.supersedes})65 'description': 'Prepared desktop with cursor integration', 'setup': 'windows-v4', 'supersedes': args.supersedes})
66(vms.PRESETS / args.id / 'disk.qcow2').chmod(0o440)66(vms.PRESETS / args.id / 'disk.qcow2').chmod(0o440)
67print(args.id)67print(args.id)
tools/vms.py+11-11
...@@ -313,7 +313,7 @@ def domains():...@@ -313,7 +313,7 @@ def domains():
313 "autostart": re.search(r"^Autostart:\s+enable", virsh("dominfo", name), re.MULTILINE) is not None,313 "autostart": re.search(r"^Autostart:\s+enable", virsh("dominfo", name), re.MULTILINE) is not None,
314 "startedAt": started,314 "startedAt": started,
315 "agent": agent.get("state", "disconnected") if agent is not None else None,315 "agent": agent.get("state", "disconnected") if agent is not None else None,
316 "setup": windows_setup(name) if setup == "windows-v3" and state == "running" else None,316 "setup": windows_setup(name) if setup in {"windows-v3", "windows-v4"} and state == "running" else None,
317 "disks": disks,317 "disks": disks,
318 "media": media,318 "media": media,
319 "firmware": "uefi" if root.find("./os/loader") is not None or root.find("os").get("firmware") == "efi" else "bios",319 "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():...@@ -327,7 +327,7 @@ def domains():
327327
328328
329def windows_setup(name):329def windows_setup(name):
330 for stage in ["ready", "failed", "restarting", "personalizing"]:330 for stage in ["ready", "failed", "signingIn", "restarting", "personalizing"]:
331 try:331 try:
332 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"]332 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"]
333 except (subprocess.CalledProcessError, ValueError, KeyError, TypeError):333 except (subprocess.CalledProcessError, ValueError, KeyError, TypeError):
...@@ -526,7 +526,7 @@ def save_preset(spec):...@@ -526,7 +526,7 @@ def save_preset(spec):
526 root = transition.normalize_vm(ET.fromstring(virsh("dumpxml", name, "--inactive")))526 root = transition.normalize_vm(ET.fromstring(virsh("dumpxml", name, "--inactive")))
527 if root.findtext(f"metadata/{NS}vm/{NS}platform") == "macos":527 if root.findtext(f"metadata/{NS}vm/{NS}platform") == "macos":
528 raise ValueError("Use a prepared OS X preset from the OS library.")528 raise ValueError("Use a prepared OS X preset from the OS library.")
529 if root.findtext(f"metadata/{NS}vm/{NS}setup") in {"windows-v2", "windows-v3"} and spec.get("setup") != "windows-v3":529 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"}:
530 raise ValueError("Prepare a Windows template before publishing another preset.")530 raise ValueError("Prepare a Windows template before publishing another preset.")
531 disks = root.findall("./devices/disk[@device='disk']")531 disks = root.findall("./devices/disk[@device='disk']")
532 if len(disks) != 1 or root.findall("./devices/hostdev"):532 if len(disks) != 1 or root.findall("./devices/hostdev"):
...@@ -573,8 +573,8 @@ def save_preset(spec):...@@ -573,8 +573,8 @@ def save_preset(spec):
573 "capacity": details["virtual-size"], "createdAt": int(time.time()),573 "capacity": details["virtual-size"], "createdAt": int(time.time()),
574 "recommended": {"vcpus": int(root.findtext("vcpu", "2")),574 "recommended": {"vcpus": int(root.findtext("vcpu", "2")),
575 "memory": int(root.findtext("memory")) * 1024, "disk": details["virtual-size"]}}575 "memory": int(root.findtext("memory")) * 1024, "disk": details["virtual-size"]}}
576 if spec.get("setup") == "windows-v3" and platform == "windows":576 if spec.get("setup") in {"windows-v3", "windows-v4"} and platform == "windows":
577 preset["setup"] = "windows-v3"577 preset["setup"] = spec["setup"]
578 if supersedes := spec.get("supersedes"):578 if supersedes := spec.get("supersedes"):
579 ensure_name(supersedes)579 ensure_name(supersedes)
580 preset["supersedes"] = supersedes580 preset["supersedes"] = supersedes
...@@ -666,14 +666,14 @@ fi...@@ -666,14 +666,14 @@ fi
666 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "cidata", "-joliet", "-rock", str(files / "user-data"), str(files / "meta-data"))666 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "cidata", "-joliet", "-rock", str(files / "user-data"), str(files / "meta-data"))
667667
668668
669def windows_seed(directory, username):669def windows_seed(directory, username, *, rename=True):
670 if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,19}", username):670 if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,19}", username):
671 raise ValueError("Use an account username suitable for a Windows guest.")671 raise ValueError("Use an account username suitable for a Windows guest.")
672 hostname = "sgvm-" + secrets.token_hex(4)672 hostname = "sgvm-" + secrets.token_hex(4) if rename else ""
673 password = guest_access(directory, username, hostname)673 password = guest_access(directory, username, hostname)
674 with tempfile.TemporaryDirectory(prefix=".seed-", dir=directory) as temporary:674 with tempfile.TemporaryDirectory(prefix=".seed-", dir=directory) as temporary:
675 marker = Path(temporary) / "SNOWGLOB.INI"675 marker = Path(temporary) / "SNOWGLOB.INI"
676 marker.write_text(f"[snowglobe]\nUSERNAME={username}\nPASSWORD={password}\nHOSTNAME={hostname}\n")676 marker.write_text(f"[snowglobe]\nUSERNAME={username}\nPASSWORD={password}\n" + (f"HOSTNAME={hostname}\n" if rename else ""))
677 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "SNOWGLOBE", "-joliet", "-rock", str(marker))677 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "SNOWGLOBE", "-joliet", "-rock", str(marker))
678678
679679
...@@ -785,8 +785,8 @@ def create(spec):...@@ -785,8 +785,8 @@ def create(spec):
785 ET.SubElement(metadata, NS + "platform").text = spec["platform"]785 ET.SubElement(metadata, NS + "platform").text = spec["platform"]
786 ET.SubElement(metadata, NS + "hardwareProfile").text = profile_name786 ET.SubElement(metadata, NS + "hardwareProfile").text = profile_name
787 ET.SubElement(metadata, NS + "owner").text = spec["owner"]787 ET.SubElement(metadata, NS + "owner").text = spec["owner"]
788 if preset and preset.get("setup") == "windows-v3":788 if preset and preset.get("setup") in {"windows-v3", "windows-v4"}:
789 ET.SubElement(metadata, NS + "setup").text = "windows-v3"789 ET.SubElement(metadata, NS + "setup").text = preset["setup"]
790 ET.SubElement(root, "memory", unit="bytes").text = str(spec["memory"])790 ET.SubElement(root, "memory", unit="bytes").text = str(spec["memory"])
791 ET.SubElement(root, "vcpu").text = str(spec["vcpus"])791 ET.SubElement(root, "vcpu").text = str(spec["vcpus"])
792 firmware = spec["firmware"]792 firmware = spec["firmware"]
...@@ -875,7 +875,7 @@ def create(spec):...@@ -875,7 +875,7 @@ def create(spec):
875 ET.SubElement(seed, "serial").text = "snowglobe-cloud-init"875 ET.SubElement(seed, "serial").text = "snowglobe-cloud-init"
876 ET.SubElement(seed, "readonly")876 ET.SubElement(seed, "readonly")
877 if preset and spec["platform"] == "windows":877 if preset and spec["platform"] == "windows":
878 windows_seed(directory, spec["username"])878 windows_seed(directory, spec["username"], rename=preset.get("setup") != "windows-v4")
879 ET.SubElement(cd, "source", file=str(directory / "seed.iso"))879 ET.SubElement(cd, "source", file=str(directory / "seed.iso"))
880 ET.SubElement(cd, "serial").text = "snowglobe-provision"880 ET.SubElement(cd, "serial").text = "snowglobe-provision"
881 if spec["platform"] == "macos":881 if spec["platform"] == "macos":
tools/windows-presets.md+23-2
...@@ -10,16 +10,21 @@ Prepare an isolated template with its account named `sandbox`, then run that...@@ -10,16 +10,21 @@ Prepare an isolated template with its account named `sandbox`, then run that
10script with `-Prepare` from elevated 64-bit Windows PowerShell. Preparation10script with `-Prepare` from elevated 64-bit Windows PowerShell. Preparation
11randomizes the template password, removes clone identity and completion state,11randomizes the template password, removes clone identity and completion state,
12and installs the startup task. Shut down normally before capturing through12and installs the startup task. Shut down normally before capturing through
13`vms.save_preset` with `setup=windows-v3`. The dashboard deliberately rejects13`vms.save_preset` with `setup=windows-v4`. The dashboard deliberately rejects
14ordinary Windows preset capture because it cannot establish preparation.14ordinary Windows preset capture because it cannot establish preparation.
1515
16Validate fresh clones with different account names before publication. Check16Validate fresh clones with different account names before publication. Check
17the personalized account and computer name, the `ready` marker, Explorer,17the personalized account, unchanged computer name, one boot, the `ready` marker, Explorer,
18the guest capture process, and the actual dashboard screen and input. Compare18the guest capture process, and the actual dashboard screen and input. Compare
19the published disk and NVRAM bytes with the tested candidate, and check that19the published disk and NVRAM bytes with the tested candidate, and check that
20the disk is standalone with `qemu-img info` and `qemu-img check`. Never replace20the disk is standalone with `qemu-img info` and `qemu-img check`. Never replace
21an existing base in place.21an existing base in place.
2222
23New clones retain the template computer name. Account personalization uses one
24sign-out/sign-in so the desktop inherits the selected username, without a second
25OS boot. Each clone still gets a separate password, MAC address, and DHCP lease.
26Published `windows-v3` bases keep their original rename-and-reboot seed contract.
27
23## 2026-10-20 rollout28## 2026-10-20 rollout
2429
25The `windows-10-pro-v10` candidate was prepared and tested on HDD storage with30The `windows-10-pro-v10` candidate was prepared and tested on HDD storage with
...@@ -82,3 +87,19 @@ The restricted raw trace is...@@ -82,3 +87,19 @@ The restricted raw trace is
82`/var/lib/snowglobe/retirements/vms-20261020/windows-boot-trace.json`.87`/var/lib/snowglobe/retirements/vms-20261020/windows-boot-trace.json`.
83The trace guest was shut down and removed afterward; the published preset and88The trace guest was shut down and removed afterward; the published preset and
84personal Mac remained intact.89personal Mac remained intact.
90
91## One-boot rollout
92
93`windows-10-pro-v11` supersedes v10 and uses `windows-v4`: the computer name stays
94unchanged, while the selected username and a fresh password are applied to the
95existing account SID/profile. A targeted sign-out/sign-in refreshes the desktop
96environment. The SID-bound capture task starts in the new interactive session.
97Temporary `ForceAutoLogon` is removed on both success and failure.
98
99With four vCPUs, 4 GiB RAM and a 64 GiB HDD overlay, the candidate reached ready
100in 60.10 seconds; a fresh clone of the published v11 reached ready in 59.88
101seconds. That is about 36 seconds faster than the quiet-host v10 trace above.
102Both machines kept the template computer name and had one Kernel-General boot
103event since creation. Interactive username, SID/profile, password authentication,
104Explorer and capture session ownership, and removal of `ForceAutoLogon` were
105checked. These are individual runs with differing cache warmth.