-
-
Notifications
You must be signed in to change notification settings - Fork 833
Expand file tree
/
Copy pathLumeController.swift
More file actions
1695 lines (1490 loc) · 64.2 KB
/
LumeController.swift
File metadata and controls
1695 lines (1490 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ArgumentParser
import Foundation
import Virtualization
// MARK: - Shared VM Manager
@MainActor
final class SharedVM {
static let shared: SharedVM = SharedVM()
private var runningVMs: [String: VM] = [:]
private init() {}
func getVM(name: String) -> VM? {
return runningVMs[name]
}
func setVM(name: String, vm: VM) {
runningVMs[name] = vm
}
func removeVM(name: String) {
runningVMs.removeValue(forKey: name)
}
}
// MARK: - Pull Progress Tracker
/// Tracks async pull progress keyed by VM name. Shared singleton used by
/// handlePullStart (writer) and handleGetVM (reader) across the same process.
actor PullProgressTracker {
static let shared = PullProgressTracker()
private var progress: [String: Double] = [:]
private var errors: [String: String] = [:]
func setProgress(_ value: Double, for name: String) {
progress[name] = value
errors.removeValue(forKey: name)
}
func setError(_ message: String, for name: String) {
errors[name] = message
progress.removeValue(forKey: name)
}
func complete(for name: String) {
progress.removeValue(forKey: name)
errors.removeValue(forKey: name)
}
func getProgress(for name: String) -> Double? {
return progress[name]
}
func getError(for name: String) -> String? {
return errors[name]
}
func isPulling(_ name: String) -> Bool {
return progress[name] != nil
}
}
/// Entrypoint for Commands and API server
final class LumeController {
// MARK: - Properties
let home: Home
private let imageLoaderFactory: ImageLoaderFactory
private let vmFactory: VMFactory
// MARK: - Initialization
init(
home: Home = Home(),
imageLoaderFactory: ImageLoaderFactory = DefaultImageLoaderFactory(),
vmFactory: VMFactory = DefaultVMFactory()
) {
self.home = home
self.imageLoaderFactory = imageLoaderFactory
self.vmFactory = vmFactory
}
// MARK: - Public VM Management Methods
/// Lists all virtual machines in the system
/// Uses a lightweight path that reads config directly without instantiating full VM objects
@MainActor
public func list(storage: String? = nil) throws -> [VMDetails] {
do {
if let storage = storage {
// If storage is specified, only return VMs from that location
if storage.contains("/") || storage.contains("\\") {
// Direct path - check if it exists
if !FileManager.default.fileExists(atPath: storage) {
// Return empty array if the path doesn't exist
return []
}
// Try to get all VMs from the specified path
let directoryURL = URL(fileURLWithPath: storage)
let contents = try FileManager.default.contentsOfDirectory(
at: directoryURL,
includingPropertiesForKeys: [.isDirectoryKey],
options: .skipsHiddenFiles
)
let statuses = contents.compactMap { subdir -> VMDetails? in
guard let isDirectory = try? subdir.resourceValues(forKeys: [.isDirectoryKey]).isDirectory,
isDirectory else {
return nil
}
let vmName = subdir.lastPathComponent
guard let vmDir = try? home.getVMDirectoryFromPath(vmName, storagePath: storage),
vmDir.initialized() else {
return nil
}
return getVMDetailsLightweight(vmDir: vmDir, locationName: storage)
}
return statuses.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
} else {
// Named storage
let vmsWithLoc = try home.getAllVMDirectories()
let statuses = vmsWithLoc.compactMap { vmWithLoc -> VMDetails? in
// Only include VMs from the specified location
if vmWithLoc.locationName != storage {
return nil
}
return getVMDetailsLightweight(
vmDir: vmWithLoc.directory,
locationName: vmWithLoc.locationName
)
}
return statuses.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
}
} else {
// No storage filter - get all VMs
let vmsWithLoc = try home.getAllVMDirectories()
let statuses = vmsWithLoc.compactMap { vmWithLoc -> VMDetails? in
return getVMDetailsLightweight(
vmDir: vmWithLoc.directory,
locationName: vmWithLoc.locationName
)
}
return statuses.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
}
} catch {
Logger.error("Failed to list VMs", metadata: ["error": error.localizedDescription])
throw error
}
}
/// Parses the VNC port from a VNC URL
/// - Parameter url: VNC URL like "vnc://:password@127.0.0.1:62295"
/// - Returns: The port number if successfully parsed, nil otherwise
private func parseVNCPort(from url: String) -> UInt16? {
// URL format: vnc://:password@host:port
guard let urlComponents = URLComponents(string: url.replacingOccurrences(of: "vnc://", with: "http://")),
let port = urlComponents.port else {
return nil
}
return UInt16(port)
}
/// Get VM details using lightweight path (no VM object instantiation)
/// Checks provisioning marker first, then SharedVM cache for running status
@MainActor
private func getVMDetailsLightweight(vmDir: VMDirectory, locationName: String) -> VMDetails? {
let vmName = vmDir.name
// Check provisioning marker FIRST - if present, VM may be in creation
if let marker = vmDir.loadProvisioningMarker() {
// Check if VM is actually complete (has all required files)
// If complete, the marker is stale and should be auto-cleaned
let hasRequiredFiles = vmDir.diskPath.exists() && vmDir.nvramPath.exists()
if hasRequiredFiles {
// VM is complete but marker wasn't cleaned up (e.g., after unattended setup)
// Auto-cleanup the stale marker
vmDir.clearProvisioningMarker()
Logger.info("Auto-cleaned stale provisioning marker for complete VM", metadata: ["name": vmName])
// Fall through to normal status check below
} else {
// VM is still being provisioned
let status = marker.isStale() ? "provisioning (stale)" : "provisioning"
if marker.isStale() {
Logger.info("VM provisioning may be stuck", metadata: [
"name": vmName,
"operation": marker.operation,
"hint": "If creation was interrupted, delete with: lume delete \(vmName)"
])
}
return vmDir.getDetails(
locationName: locationName,
status: status,
provisioningOperation: marker.operation,
vncUrl: nil,
ipAddress: nil,
sshAvailable: nil
)
}
}
// Check if VM is running via SharedVM cache (same-process fast path)
let runningVM = SharedVM.shared.getVM(name: vmName)
var isRunning = runningVM != nil
// Get VNC URL and IP address only if running
var vncUrl: String? = nil
var ipAddress: String? = nil
var sshAvailable: Bool? = nil
// If not in cache, check if session file exists (cross-process fallback)
// Session files are created when VM starts and deleted when VM stops
// Validate that the VNC port is actually in use to detect stale sessions
if !isRunning {
if let session = try? vmDir.loadSession() {
// Parse VNC port from URL like "vnc://:password@127.0.0.1:62295"
if let port = parseVNCPort(from: session.url),
NetworkUtils.isLocalPortInUse(port: port) {
isRunning = true
vncUrl = session.url
} else {
// Stale session file - VNC port not in use, clean it up
vmDir.clearSession()
Logger.info("Cleaned up stale session file", metadata: ["name": vmName])
}
}
}
if isRunning {
// Try to get VNC URL from session file (if not already loaded)
if vncUrl == nil {
vncUrl = try? vmDir.loadSession().url
}
// Try to get IP address from DHCP lease if we have MAC address
if let config = try? vmDir.loadConfig(),
let macAddress = config.macAddress {
ipAddress = DHCPLeaseParser.getIPAddress(forMAC: macAddress)
// Check if SSH is available
if let ip = ipAddress {
sshAvailable = NetworkUtils.isSSHAvailable(ipAddress: ip)
}
}
}
return vmDir.getDetails(
locationName: locationName,
status: isRunning ? "running" : "stopped",
provisioningOperation: nil,
vncUrl: vncUrl,
ipAddress: ipAddress,
sshAvailable: sshAvailable
)
}
/// Validates that a VM is not currently being provisioned
/// - Parameters:
/// - vmDir: The VM directory to check
/// - name: The VM name (for error message)
/// - Throws: VMError.stillProvisioning if the VM has a provisioning marker
private func validateNotProvisioning(_ vmDir: VMDirectory, name: String) throws {
if vmDir.loadProvisioningMarker() != nil {
throw VMError.stillProvisioning(name)
}
}
@MainActor
public func clone(
name: String, newName: String, sourceLocation: String? = nil, destLocation: String? = nil
) throws {
let normalizedName = normalizeVMName(name: name)
let normalizedNewName = normalizeVMName(name: newName)
Logger.info(
"Cloning VM",
metadata: [
"source": normalizedName,
"destination": normalizedNewName,
"sourceLocation": sourceLocation ?? "default",
"destLocation": destLocation ?? "default",
])
do {
// Validate source VM exists
let actualSourceLocation = try self.validateVMExists(normalizedName, storage: sourceLocation)
// Check if source VM is still being provisioned
let sourceVmDir = try home.getVMDirectory(normalizedName, storage: actualSourceLocation)
try validateNotProvisioning(sourceVmDir, name: normalizedName)
// Get the source VM and check if it's running
let sourceVM = try get(name: normalizedName, storage: sourceLocation)
if sourceVM.details.status == "running" {
Logger.error("Cannot clone a running VM", metadata: ["source": normalizedName])
throw VMError.alreadyRunning(normalizedName)
}
// Check if destination already exists
do {
let destDir = try home.getVMDirectory(normalizedNewName, storage: destLocation)
if destDir.exists() {
Logger.error(
"Destination VM already exists",
metadata: ["destination": normalizedNewName])
throw HomeError.directoryAlreadyExists(path: destDir.dir.path)
}
} catch VMLocationError.locationNotFound {
// Location not found is okay, we'll create it
} catch VMError.notFound {
// VM not found is okay, we'll create it
}
// Clone the VM directory (uses APFS clonefile for disk.img)
try home.cloneVMDirectory(
from: normalizedName,
to: normalizedNewName,
sourceLocation: sourceLocation,
destLocation: destLocation
)
// Update MAC address in the cloned VM to ensure uniqueness
let clonedVM = try get(name: normalizedNewName, storage: destLocation)
try clonedVM.setMacAddress(VZMACAddress.randomLocallyAdministered().string)
// Update MAC Identifier in the cloned VM to ensure uniqueness
try clonedVM.setMachineIdentifier(
DarwinVirtualizationService.generateMachineIdentifier())
Logger.info(
"VM cloned successfully",
metadata: ["source": normalizedName, "destination": normalizedNewName])
} catch {
Logger.error("Failed to clone VM", metadata: ["error": error.localizedDescription])
throw error
}
}
@MainActor
public func get(name: String, storage: String? = nil) throws -> VM {
let normalizedName = normalizeVMName(name: name)
do {
let vm: VM
if let storagePath = storage, storagePath.contains("/") || storagePath.contains("\\") {
// Storage is a direct path
let vmDir = try home.getVMDirectoryFromPath(normalizedName, storagePath: storagePath)
guard vmDir.initialized() else {
// Throw a specific error if the directory exists but isn't a valid VM
if vmDir.exists() {
throw VMError.notInitialized(normalizedName)
} else {
throw VMError.notFound(normalizedName)
}
}
// Pass the path as the storage context
vm = try self.loadVM(vmDir: vmDir, storage: storagePath)
} else {
// Storage is nil or a named location
let actualLocation = try self.validateVMExists(
normalizedName, storage: storage)
let vmDir = try home.getVMDirectory(normalizedName, storage: actualLocation)
// loadVM will re-check initialized, but good practice to keep validateVMExists result.
vm = try self.loadVM(vmDir: vmDir, storage: actualLocation)
}
return vm
} catch {
Logger.error(
"Failed to get VM",
metadata: [
"vmName": normalizedName, "storage": storage ?? "home",
"error": error.localizedDescription,
])
// Re-throw the original error to preserve its type
throw error
}
}
/// Gets VM details using the lightweight path (includes provisioning status)
/// Use this instead of get().details when you need accurate status including provisioning state
@MainActor
public func getDetails(name: String, storage: String? = nil) throws -> VMDetails {
let normalizedName = normalizeVMName(name: name)
do {
let vmDir: VMDirectory
let locationName: String
if let storagePath = storage, storagePath.contains("/") || storagePath.contains("\\") {
// Storage is a direct path
vmDir = try home.getVMDirectoryFromPath(normalizedName, storagePath: storagePath)
guard vmDir.initialized() else {
if vmDir.exists() {
throw VMError.notInitialized(normalizedName)
} else {
throw VMError.notFound(normalizedName)
}
}
locationName = storagePath
} else {
// Storage is nil or a named location - find the VM
let actualLocation = try self.validateVMExists(normalizedName, storage: storage)
vmDir = try home.getVMDirectory(normalizedName, storage: actualLocation)
locationName = actualLocation ?? "home"
}
// Use the lightweight path that includes provisioning status
guard let details = getVMDetailsLightweight(vmDir: vmDir, locationName: locationName) else {
throw VMError.notFound(normalizedName)
}
return details
} catch {
Logger.error(
"Failed to get VM details",
metadata: [
"vmName": normalizedName, "storage": storage ?? "home",
"error": error.localizedDescription,
])
throw error
}
}
@MainActor
public func create(
name: String,
os: String,
diskSize: UInt64,
cpuCount: Int,
memorySize: UInt64,
display: String,
ipsw: String?,
storage: String? = nil,
unattendedConfig: UnattendedConfig? = nil,
debug: Bool = false,
debugDir: String? = nil,
noDisplay: Bool = true,
vncPort: Int = 0,
networkMode: NetworkMode = .nat
) async throws {
Logger.info(
"Creating VM",
metadata: [
"name": name,
"os": os,
"location": storage ?? "home",
"disk_size": "\(diskSize / 1024 / 1024)MB",
"cpu_count": "\(cpuCount)",
"memory_size": "\(memorySize / 1024 / 1024)MB",
"display": display,
"ipsw": ipsw ?? "none",
"unattended": unattendedConfig != nil ? "yes" : "no",
"debug": "\(debug)",
"noDisplay": "\(noDisplay)",
])
// Validate parameters upfront
try validateCreateParameters(name: name, os: os, ipsw: ipsw, storage: storage)
// Create target VM directory early with provisioning marker
// so VM appears in list immediately with "provisioning" status
let vmDir = try home.getVMDirectory(name, storage: storage)
do {
try FileManager.default.createDirectory(
atPath: vmDir.dir.path,
withIntermediateDirectories: true
)
// Create minimal config so VM shows up in list
let config = try VMConfig(
os: os,
cpuCount: cpuCount,
memorySize: memorySize,
diskSize: diskSize,
display: display,
networkMode: networkMode
)
try vmDir.saveConfig(config)
// Write provisioning marker
try vmDir.saveProvisioningMarker(ProvisioningMarker(operation: "ipsw_install"))
Logger.info("Provisioning marker created", metadata: ["name": name])
} catch {
// Clean up if we fail to set up provisioning marker
try? vmDir.delete()
Logger.error("Failed to create VM", metadata: ["error": error.localizedDescription])
throw error
}
do {
// Use createInternal which handles all the actual work
try await createInternal(
name: name,
os: os,
diskSize: diskSize,
cpuCount: cpuCount,
memorySize: memorySize,
display: display,
ipsw: ipsw,
storage: storage,
unattendedConfig: unattendedConfig,
debug: debug,
debugDir: debugDir,
noDisplay: noDisplay,
vncPort: vncPort,
vmDir: vmDir,
networkMode: networkMode
)
// Clear provisioning marker on success
vmDir.clearProvisioningMarker()
Logger.info("Provisioning marker cleared", metadata: ["name": name])
} catch {
// Clean up the pre-created directory on failure. If deletion fails, keep the
// provisioning marker intact so the leftover VM remains discoverable.
cleanupFailedCreateVMDirectory(vmDir, context: "creation")
Logger.error("Failed to create VM", metadata: ["error": error.localizedDescription])
throw error
}
}
/// Creates a VM asynchronously, returning immediately while the VM is being provisioned.
/// The VM will appear with status "provisioning" in `lume ls` until creation completes.
/// Poll VM status to check progress.
///
/// - Parameters:
/// - name: Name for the new VM
/// - os: Operating system type ("macos" or "linux")
/// - diskSize: Disk size in bytes
/// - cpuCount: Number of CPU cores
/// - memorySize: Memory size in bytes
/// - display: Display resolution string (e.g., "1920x1080")
/// - ipsw: Path to IPSW file or "latest" for macOS
/// - storage: Optional storage location name or path
/// - unattendedConfig: Optional unattended setup configuration
@MainActor
public func createAsync(
name: String,
os: String,
diskSize: UInt64,
cpuCount: Int,
memorySize: UInt64,
display: String,
ipsw: String?,
storage: String? = nil,
unattendedConfig: UnattendedConfig? = nil,
networkMode: NetworkMode = .nat
) throws {
Logger.info(
"Starting async VM creation",
metadata: [
"name": name,
"os": os,
"location": storage ?? "home",
"unattended": unattendedConfig != nil ? "yes" : "no",
])
// Validate parameters upfront (this checks VM doesn't already exist)
try validateCreateParameters(name: name, os: os, ipsw: ipsw, storage: storage)
// Create VM directory and provisioning marker BEFORE spawning background task
// so VM appears in list immediately with "provisioning" status
let vmDir = try home.getVMDirectory(name, storage: storage)
do {
try FileManager.default.createDirectory(
atPath: vmDir.dir.path,
withIntermediateDirectories: true
)
// Create minimal config so VM shows up in list
let config = try VMConfig(
os: os,
cpuCount: cpuCount,
memorySize: memorySize,
diskSize: diskSize,
display: display,
networkMode: networkMode
)
try vmDir.saveConfig(config)
// Write provisioning marker
try vmDir.saveProvisioningMarker(ProvisioningMarker(operation: "ipsw_install"))
Logger.info("Provisioning marker created", metadata: ["name": name])
} catch {
// Clean up if we fail to set up provisioning marker
try? vmDir.delete()
Logger.error("Failed to create VM", metadata: ["error": error.localizedDescription])
throw error
}
Logger.info("Spawning background task for VM creation", metadata: ["name": name])
// All parameters passed to Task are value types (Sendable)
// The Task will create its own LumeController instance
Task.detached { @MainActor @Sendable in
// Create a new controller for the background task
let controller = LumeController()
do {
// Run the internal create which does all the work
// (skips validation since we already validated)
try await controller.createInternal(
name: name,
os: os,
diskSize: diskSize,
cpuCount: cpuCount,
memorySize: memorySize,
display: display,
ipsw: ipsw,
storage: storage,
unattendedConfig: unattendedConfig,
vmDir: vmDir,
networkMode: networkMode
)
// Clear marker on success
vmDir.clearProvisioningMarker()
Logger.info("Async VM creation completed successfully", metadata: ["name": name])
} catch {
// Clean up the pre-created directory on failure. If deletion fails, keep the
// provisioning marker intact so the leftover VM remains discoverable.
controller.cleanupFailedCreateVMDirectory(vmDir, context: "async creation")
Logger.error("Async VM creation failed",
metadata: ["name": name, "error": error.localizedDescription])
}
}
}
private func cleanupFailedCreateVMDirectory(_ vmDir: VMDirectory, context: String) {
do {
if vmDir.exists() {
try vmDir.delete()
}
} catch let cleanupError {
Logger.error("Failed to clean up VM directory after \(context) failure",
metadata: ["error": cleanupError.localizedDescription])
}
}
/// Internal create method that skips validation (used by createAsync)
@MainActor
private func createInternal(
name: String,
os: String,
diskSize: UInt64,
cpuCount: Int,
memorySize: UInt64,
display: String,
ipsw: String?,
storage: String? = nil,
unattendedConfig: UnattendedConfig? = nil,
debug: Bool = false,
debugDir: String? = nil,
noDisplay: Bool = true,
vncPort: Int = 0,
vmDir: VMDirectory? = nil,
networkMode: NetworkMode = .nat
) async throws {
Logger.info(
"Creating VM (internal)",
metadata: [
"name": name,
"os": os,
"location": storage ?? "home",
])
let vm = try await createTempVMConfig(
os: os,
cpuCount: cpuCount,
memorySize: memorySize,
diskSize: diskSize,
display: display,
networkMode: networkMode
)
// Track the temp directory for cleanup on failure
let tempVMDir = vm.vmDirContext.dir
do {
try await vm.setup(
ipswPath: ipsw ?? "none",
cpuCount: cpuCount,
memorySize: memorySize,
diskSize: diskSize,
display: display
)
// If vmDir was pre-created (async flow), we need to handle finalization differently
if let existingVmDir = vmDir {
// Delete the pre-created directory (with just config and marker)
// and let finalize create it fresh with all the VM files
try existingVmDir.delete()
}
try vm.finalize(to: name, home: home, storage: storage)
} catch {
// Clean up the temporary VM directory on setup/finalize failure
Logger.info("Cleaning up temporary VM directory after failed creation",
metadata: ["path": tempVMDir.dir.path])
do {
try tempVMDir.delete()
} catch let cleanupError {
Logger.error("Failed to clean up temporary VM directory",
metadata: ["error": cleanupError.localizedDescription])
}
throw error
}
Logger.info("VM created successfully", metadata: ["name": name])
// Run unattended setup if config is provided
if let config = unattendedConfig, os.lowercased() == "macos" {
// Note: We don't write a provisioning marker for unattended setup.
// The VM has disk + nvram at this point, so it's "running" during
// the setup automation, not "provisioning".
// Wait for the installation VZVirtualMachine to fully release auxiliary storage locks.
Logger.info("Waiting for installation resources to be released before unattended setup")
try await Task.sleep(nanoseconds: 3_000_000_000) // 3 seconds
Logger.info("Starting unattended Setup Assistant automation", metadata: ["name": name])
// Load the finalized VM
let finalVM = try get(name: name, storage: storage)
// Run the unattended installer
let installer = UnattendedInstaller()
do {
try await installer.install(
vm: finalVM,
config: config,
vncPort: vncPort,
noDisplay: noDisplay,
debug: debug,
debugDir: debugDir
)
} catch {
// Clean up the finalized VM directory on unattended setup failure
Logger.info("Cleaning up VM after failed unattended setup",
metadata: ["name": name])
do {
let vmDirToDelete = try home.getVMDirectory(name, storage: storage)
try vmDirToDelete.delete()
} catch let cleanupError {
Logger.error("Failed to clean up VM after unattended setup failure",
metadata: ["error": cleanupError.localizedDescription])
}
throw error
}
Logger.info("Unattended setup completed", metadata: ["name": name])
}
}
/// Run unattended Setup Assistant automation on an existing macOS VM
@MainActor
public func setup(
name: String,
config: UnattendedConfig,
storage: String? = nil,
vncPort: Int = 0,
noDisplay: Bool = false,
debug: Bool = false,
debugDir: String? = nil
) async throws {
let normalizedName = normalizeVMName(name: name)
Logger.info(
"Running unattended setup",
metadata: [
"name": normalizedName,
"storage": storage ?? "home",
"bootWait": "\(config.bootWait)s",
"commands": "\(config.bootCommands.count)",
"debug": "\(debug)",
"debugDir": debugDir ?? "default"
])
do {
// Get the VM
let vm = try get(name: normalizedName, storage: storage)
// Check if it's a macOS VM
guard vm.config.os.lowercased() == "macos" else {
throw VMError.unsupportedOS("Unattended setup is only supported for macOS VMs, got: \(vm.config.os)")
}
// Run the unattended installer
let installer = UnattendedInstaller()
try await installer.install(vm: vm, config: config, vncPort: vncPort, noDisplay: noDisplay, debug: debug, debugDir: debugDir)
Logger.info("Unattended setup completed", metadata: ["name": normalizedName])
} catch {
Logger.error("Failed to run unattended setup", metadata: ["error": error.localizedDescription])
throw error
}
}
/// Run agent-based Setup Assistant automation using Claude computer-use API
@MainActor
public func setupWithAgent(
name: String,
apiKey: String,
model: String = "claude-sonnet-4-6",
maxIterations: Int = 100,
systemPrompt: String? = nil,
storage: String? = nil,
vncPort: Int = 0,
noDisplay: Bool = false,
debug: Bool = false,
debugDir: String? = nil
) async throws {
let normalizedName = normalizeVMName(name: name)
Logger.info(
"Running agent-based setup",
metadata: [
"name": normalizedName,
"model": model,
"maxIterations": "\(maxIterations)",
"debug": "\(debug)"
])
do {
let vm = try get(name: normalizedName, storage: storage)
guard vm.config.os.lowercased() == "macos" else {
throw VMError.unsupportedOS("Unattended setup is only supported for macOS VMs, got: \(vm.config.os)")
}
let installer = UnattendedInstaller()
try await installer.installWithAgent(
vm: vm,
apiKey: apiKey,
model: model,
maxIterations: maxIterations,
systemPrompt: systemPrompt,
vncPort: vncPort,
noDisplay: noDisplay,
debug: debug,
debugDir: debugDir
)
Logger.info("Agent-based setup completed", metadata: ["name": normalizedName])
} catch {
Logger.error("Failed to run agent-based setup", metadata: ["error": error.localizedDescription])
throw error
}
}
@MainActor
public func delete(name: String, storage: String? = nil) async throws {
let normalizedName = normalizeVMName(name: name)
Logger.info(
"Deleting VM",
metadata: [
"name": normalizedName,
"location": storage ?? "home",
])
do {
let vmDir: VMDirectory
// Check if storage is a direct path
if let storagePath = storage, storagePath.contains("/") || storagePath.contains("\\") {
// Storage is a direct path
vmDir = try home.getVMDirectoryFromPath(normalizedName, storagePath: storagePath)
guard vmDir.initialized() else {
// Throw a specific error if the directory exists but isn't a valid VM
if vmDir.exists() {
throw VMError.notInitialized(normalizedName)
} else {
throw VMError.notFound(normalizedName)
}
}
} else {
// Storage is nil or a named location
let actualLocation = try self.validateVMExists(normalizedName, storage: storage)
vmDir = try home.getVMDirectory(normalizedName, storage: actualLocation)
}
// Stop VM if it's running
if SharedVM.shared.getVM(name: normalizedName) != nil {
try await stopVM(name: normalizedName)
}
try vmDir.delete()
Logger.info("VM deleted successfully", metadata: ["name": normalizedName])
} catch {
Logger.error("Failed to delete VM", metadata: ["error": error.localizedDescription])
throw error
}
}
// MARK: - VM Operations
@MainActor
public func updateSettings(
name: String,
cpu: Int? = nil,
memory: UInt64? = nil,
diskSize: UInt64? = nil,
display: String? = nil,
storage: String? = nil
) throws {
let normalizedName = normalizeVMName(name: name)
Logger.info(
"Updating VM settings",
metadata: [
"name": normalizedName,
"location": storage ?? "home",
"cpu": cpu.map { "\($0)" } ?? "unchanged",
"memory": memory.map { "\($0 / 1024 / 1024)MB" } ?? "unchanged",
"disk_size": diskSize.map { "\($0 / 1024 / 1024)MB" } ?? "unchanged",
"display": display ?? "unchanged",
])
do {
// Find the actual location of the VM
let actualLocation = try self.validateVMExists(
normalizedName, storage: storage)
let vm = try get(name: normalizedName, storage: actualLocation)
// Apply settings in order
if let cpu = cpu {
try vm.setCpuCount(cpu)
}
if let memory = memory {
try vm.setMemorySize(memory)
}
if let diskSize = diskSize {
try vm.setDiskSize(diskSize)
}
if let display = display {
try vm.setDisplay(display)
}
Logger.info("VM settings updated successfully", metadata: ["name": normalizedName])
} catch {
Logger.error(
"Failed to update VM settings", metadata: ["error": error.localizedDescription])
throw error
}
}
@MainActor
public func stopVM(name: String, storage: String? = nil) async throws {
let normalizedName = normalizeVMName(name: name)
Logger.info("Stopping VM", metadata: ["name": normalizedName])
do {
// Find the actual location of the VM
let actualLocation = try self.validateVMExists(
normalizedName, storage: storage)
// Check if VM is still being provisioned
let vmDir = try home.getVMDirectory(normalizedName, storage: actualLocation)
try validateNotProvisioning(vmDir, name: normalizedName)
// Try to get VM from cache first
let vm: VM
if let cachedVM = SharedVM.shared.getVM(name: normalizedName) {
vm = cachedVM
} else {
vm = try get(name: normalizedName, storage: actualLocation)
}
try await vm.stop()
// Remove VM from cache after stopping
SharedVM.shared.removeVM(name: normalizedName)
Logger.info("VM stopped successfully", metadata: ["name": normalizedName])
} catch {
// Clean up cache even if stop fails
SharedVM.shared.removeVM(name: normalizedName)
Logger.error("Failed to stop VM", metadata: ["error": error.localizedDescription])
throw error
}
}
@MainActor
public func runVM(
name: String,
noDisplay: Bool = false,
sharedDirectories: [SharedDirectory] = [],
mount: Path? = nil,
registry: String = "ghcr.io",
organization: String = "trycua",
vncPort: Int = 0,
vncPassword: String? = nil,
recoveryMode: Bool = false,
storage: String? = nil,
diskPath: Path? = nil,
nvramPath: Path? = nil,