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 {
5555 $pair = $line.Split('=', 2)
5656 if ($pair.Count -eq 2) { $values[$pair[0]] = $pair[1] }
5757 }
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 }
7758 $username = $values['USERNAME']
7859 $password = $values['PASSWORD']
79 $hostname = $values['HOSTNAME']
8060 if ($username -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,19}$') { throw 'The VM account name is unsupported.' }
8161 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.' }
8362 $sid = Get-Content "$root\template.sid"
8463 $user = Get-LocalUser | Where-Object { $_.SID.Value -eq $sid }
8564 if (!$user) { throw 'The template account is missing.' }
8665 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 }
8778 $user | Set-LocalUser -Password (ConvertTo-SecureString $password -AsPlainText -Force) -PasswordNeverExpires $true
8879 if ($user.Name -ine $username) { $user | Rename-LocalUser -NewName $username }
89 Rename-Computer -NewName $hostname -Force
9080 Set-ItemProperty $winlogon AutoAdminLogon '1'
9181 Set-ItemProperty $winlogon DefaultUserName $username
92 Set-ItemProperty $winlogon DefaultDomainName $hostname
82 Set-ItemProperty $winlogon DefaultDomainName $env:COMPUTERNAME
9383 Set-ItemProperty $winlogon DefaultPassword $password
9484 Remove-ItemProperty $winlogon AutoLogonCount -ErrorAction SilentlyContinue
95 Set-SetupStatus restarting
96 Restart-Computer -Force
85 $scheduler = New-Object -ComObject Schedule.Service
86 $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
97107} catch {
98108 if ($Prepare) { throw }
99109 Set-SetupStatus failed
100110 Add-Content "$root\setup.log" $_.Exception.Message
101111 exit 1
102112}
113finally {
114 Remove-ItemProperty $winlogon ForceAutoLogon -ErrorAction SilentlyContinue
115}
tools/dashboard-vms-test.py+12
......@@ -150,6 +150,18 @@ class VMTests(unittest.TestCase):
150150 with self.assertRaisesRegex(ValueError, 'Windows'):
151151 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
153165 def test_nixos_seed_uses_mutable_gdm_path_and_native_sshd(self):
154166 with tempfile.TemporaryDirectory() as temporary:
155167 directory = Path(temporary)
tools/prepare-windows-preset.py+1-1
......@@ -62,6 +62,6 @@ while vms.virsh('domstate', args.name).strip() != 'shut off':
6262 raise TimeoutError('The template did not shut down.')
6363 time.sleep(.5)
6464vms.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})
6666(vms.PRESETS / args.id / 'disk.qcow2').chmod(0o440)
6767print(args.id)
tools/vms.py+11-11
......@@ -313,7 +313,7 @@ def domains():
313313 "autostart": re.search(r"^Autostart:\s+enable", virsh("dominfo", name), re.MULTILINE) is not None,
314314 "startedAt": started,
315315 "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,
317317 "disks": disks,
318318 "media": media,
319319 "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():
327327
328328
329329def windows_setup(name):
330 for stage in ["ready", "failed", "restarting", "personalizing"]:
330 for stage in ["ready", "failed", "signingIn", "restarting", "personalizing"]:
331331 try:
332332 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"]
333333 except (subprocess.CalledProcessError, ValueError, KeyError, TypeError):
......@@ -526,7 +526,7 @@ def save_preset(spec):
526526 root = transition.normalize_vm(ET.fromstring(virsh("dumpxml", name, "--inactive")))
527527 if root.findtext(f"metadata/{NS}vm/{NS}platform") == "macos":
528528 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"}:
530530 raise ValueError("Prepare a Windows template before publishing another preset.")
531531 disks = root.findall("./devices/disk[@device='disk']")
532532 if len(disks) != 1 or root.findall("./devices/hostdev"):
......@@ -573,8 +573,8 @@ def save_preset(spec):
573573 "capacity": details["virtual-size"], "createdAt": int(time.time()),
574574 "recommended": {"vcpus": int(root.findtext("vcpu", "2")),
575575 "memory": int(root.findtext("memory")) * 1024, "disk": details["virtual-size"]}}
576 if spec.get("setup") == "windows-v3" and platform == "windows":
577 preset["setup"] = "windows-v3"
576 if spec.get("setup") in {"windows-v3", "windows-v4"} and platform == "windows":
577 preset["setup"] = spec["setup"]
578578 if supersedes := spec.get("supersedes"):
579579 ensure_name(supersedes)
580580 preset["supersedes"] = supersedes
......@@ -666,14 +666,14 @@ fi
666666 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):
670670 if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,19}", username):
671671 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 ""
673673 password = guest_access(directory, username, hostname)
674674 with tempfile.TemporaryDirectory(prefix=".seed-", dir=directory) as temporary:
675675 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 ""))
677677 command("genisoimage", "-quiet", "-output", str(directory / "seed.iso"), "-volid", "SNOWGLOBE", "-joliet", "-rock", str(marker))
678678
679679
......@@ -785,8 +785,8 @@ def create(spec):
785785 ET.SubElement(metadata, NS + "platform").text = spec["platform"]
786786 ET.SubElement(metadata, NS + "hardwareProfile").text = profile_name
787787 ET.SubElement(metadata, NS + "owner").text = spec["owner"]
788 if preset and preset.get("setup") == "windows-v3":
789 ET.SubElement(metadata, NS + "setup").text = "windows-v3"
788 if preset and preset.get("setup") in {"windows-v3", "windows-v4"}:
789 ET.SubElement(metadata, NS + "setup").text = preset["setup"]
790790 ET.SubElement(root, "memory", unit="bytes").text = str(spec["memory"])
791791 ET.SubElement(root, "vcpu").text = str(spec["vcpus"])
792792 firmware = spec["firmware"]
......@@ -875,7 +875,7 @@ def create(spec):
875875 ET.SubElement(seed, "serial").text = "snowglobe-cloud-init"
876876 ET.SubElement(seed, "readonly")
877877 if preset and spec["platform"] == "windows":
878 windows_seed(directory, spec["username"])
878 windows_seed(directory, spec["username"], rename=preset.get("setup") != "windows-v4")
879879 ET.SubElement(cd, "source", file=str(directory / "seed.iso"))
880880 ET.SubElement(cd, "serial").text = "snowglobe-provision"
881881 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
1010script with `-Prepare` from elevated 64-bit Windows PowerShell. Preparation
1111randomizes the template password, removes clone identity and completion state,
1212and installs the startup task. Shut down normally before capturing through
13`vms.save_preset` with `setup=windows-v3`. The dashboard deliberately rejects
13`vms.save_preset` with `setup=windows-v4`. The dashboard deliberately rejects
1414ordinary Windows preset capture because it cannot establish preparation.
1515
1616Validate 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,
1818the guest capture process, and the actual dashboard screen and input. Compare
1919the published disk and NVRAM bytes with the tested candidate, and check that
2020the disk is standalone with `qemu-img info` and `qemu-img check`. Never replace
2121an 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
2328## 2026-10-20 rollout
2429
2530The `windows-10-pro-v10` candidate was prepared and tested on HDD storage with
......@@ -82,3 +87,19 @@ The restricted raw trace is
8287`/var/lib/snowglobe/retirements/vms-20261020/windows-boot-trace.json`.
8388The trace guest was shut down and removed afterward; the published preset and
8489personal 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.