Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Match a machine's template by build in Launchpad's inspector

Jackyeb7799756413
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swift
index cf49b508..b196b912 100644
--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift
@@ -12,6 +12,7 @@ struct TemplatesTests {
try templateList()
try templateFind()
notices()
+ try templateOrigins()
try await diskUsage()
}
@@ -484,6 +485,67 @@ struct TemplatesTests {
print("Delete note tests passed")
}
+ // MARK: - Template of a machine
+
+ /// Retest L2: a template deleted and built again keeps its identifier,
+ /// so the inspector matches a machine to the build, as `vphone-cli` does.
+ static func templateOrigins() throws {
+ typealias Origin = VPhoneLaunchpadTemplateOrigin
+ let id = "3c16c372ca03"
+ let frozen = Date(timeIntervalSince1970: 1_791_453_600)
+ let template = Origin.Template(identifier: id, build: "B2", created: frozen.addingTimeInterval(-3600), frozenAt: frozen)
+
+ // Both records name a build: the build decides, not the dates.
+ let current = Origin.Source(identifier: id, build: "B2", cloned: frozen.addingTimeInterval(60))
+ precondition(Origin(current, template: template).match == .current, "Current build")
+ let earlier = Origin.Source(identifier: id, build: "B1", cloned: frozen.addingTimeInterval(60))
+ precondition(Origin(earlier, template: template).match == .earlierBuild, "Earlier build, cloned after the new one froze")
+ precondition(Origin(earlier, template: template).identifier == id, "Identifier kept")
+
+ // A clone record from before builds were recorded: the dates decide.
+ let legacyAfter = Origin.Source(identifier: id, cloned: frozen)
+ precondition(Origin(legacyAfter, template: template).match == .current, "Legacy clone at or after FrozenAt")
+ let legacyBefore = Origin.Source(identifier: id, cloned: frozen.addingTimeInterval(-1))
+ precondition(Origin(legacyBefore, template: template).match == .earlierBuild, "Legacy clone before FrozenAt")
+ // A legacy template on the other side, with no FrozenAt: Created.
+ let legacyTemplate = Origin.Template(identifier: id, created: frozen)
+ precondition(Origin(current, template: legacyTemplate).match == .current, "Build on one side only, cloned after Created")
+ precondition(Origin(legacyBefore, template: legacyTemplate).match == .earlierBuild, "Cloned before Created")
+
+ precondition(Origin(current, template: nil).match == .deleted, "Template missing")
+ precondition(!Origin.isClone(current, of: Origin.Template(identifier: "52b1fcc75e0c", build: "B2", created: frozen)), "Another identifier")
+
+ // Read from the folders, as the library does.
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("templates-origin-\(UUID().uuidString)", isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let machine = root.appendingPathComponent("e2e-a", isDirectory: true)
+ let templateFolder = root.appendingPathComponent(".templates/\(id)", isDirectory: true)
+ try FileManager.default.createDirectory(at: machine, withIntermediateDirectories: true)
+ func write(_ plist: [String: Any], to file: URL) throws {
+ try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0).write(to: file)
+ }
+ func read() -> Origin? {
+ Origin.read(machine: machine, libraryRoot: root.path)
+ }
+ precondition(read() == nil, "Not a clone")
+ try write(["Identifier": id, "Build": "B1", "Cloned": frozen.addingTimeInterval(60)], to: machine.appendingPathComponent("TemplateSource.plist"))
+ precondition(read() == Origin(identifier: id, match: .deleted), "Template folder missing: \(String(describing: read()))")
+ try FileManager.default.createDirectory(at: templateFolder, withIntermediateDirectories: true)
+ let record: [String: Any] = ["Identifier": id, "Build": "B2", "Created": frozen, "Frozen": true, "FrozenAt": frozen]
+ try write(record, to: templateFolder.appendingPathComponent("Template.plist"))
+ precondition(read()?.match == .earlierBuild, "Rebuilt template")
+ try write(record.merging(["Build": "B1"]) { $1 }, to: templateFolder.appendingPathComponent("Template.plist"))
+ precondition(read()?.match == .current, "Same build")
+ try write(record.merging(["Build": "B1", "Frozen": false]) { $1 }, to: templateFolder.appendingPathComponent("Template.plist"))
+ precondition(read()?.match == .deleted, "A template never frozen is not listed")
+ try write(["Identifier": id, "Cloned": frozen.addingTimeInterval(-60)], to: machine.appendingPathComponent("TemplateSource.plist"))
+ try write(record.merging(["Build": "B1"]) { $1 }, to: templateFolder.appendingPathComponent("Template.plist"))
+ precondition(read()?.match == .earlierBuild, "Legacy record read without Build, cloned before FrozenAt")
+ try write(["Identifier": id], to: machine.appendingPathComponent("TemplateSource.plist"))
+ precondition(read() == nil, "No Cloned: unreadable, as the CLI decodes it")
+ print("Template origin tests passed")
+ }
+
// MARK: - Disk use
static func diskUsage() async throws {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index e51755b9..0fa101ea 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -987,6 +987,142 @@
}
}
},
+ "Created from an earlier build of this template, since deleted. It shares its SEP root secret and Data volume keys only with the machines created from that build, not with the template that has this identifier now or the machines created from it." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Created from an earlier build of this template, since deleted. It shares its SEP root secret and Data volume keys only with the machines created from that build, not with the template that has this identifier now or the machines created from it."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "このテンプレートの以前のビルドから作成されました。そのビルドは削除されています。SEP ルートシークレットと Data ボリュームの鍵はそのビルドから作成したマシンとだけ共有し、現在この識別子を持つテンプレートやそこから作成したマシンとは共有しません。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이 템플릿의 이전 빌드에서 생성되었으며, 그 빌드는 삭제되었습니다. SEP 루트 시크릿과 Data 볼륨 키는 그 빌드에서 만든 머신과만 공유하며, 현재 이 식별자를 가진 템플릿이나 그 템플릿에서 만든 머신과는 공유하지 않습니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Được tạo từ một bản dựng trước của mẫu này, bản dựng đó đã bị xóa. Máy ảo chỉ dùng chung bí mật gốc SEP và khóa ổ Data với các máy ảo tạo từ bản dựng đó, không dùng chung với mẫu hiện mang mã định danh này hay các máy ảo tạo từ mẫu đó."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "从此模板较早的一次构建创建,该构建已被删除。它只与从那次构建创建的虚拟机共享 SEP 根密钥和 Data 卷密钥,不与现在使用此标识符的模板及从其创建的虚拟机共享。"
+ }
+ }
+ }
+ },
+ "Created from this template, which was deleted. It shares the template's SEP root secret and Data volume keys with every machine created from it." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Created from this template, which was deleted. It shares the template's SEP root secret and Data volume keys with every machine created from it."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "このテンプレートから作成されました。テンプレートは削除されています。テンプレートの SEP ルートシークレットと Data ボリュームの鍵を、このテンプレートから作成したすべてのマシンと共有しています。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이 템플릿에서 생성되었으며, 템플릿은 삭제되었습니다. 템플릿의 SEP 루트 시크릿과 Data 볼륨 키를 이 템플릿에서 만든 모든 머신과 공유합니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Được tạo từ mẫu này, mẫu đó đã bị xóa. Máy ảo dùng chung bí mật gốc SEP và khóa ổ Data của mẫu với mọi máy ảo tạo từ mẫu."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "从此模板创建,该模板已被删除。它与从该模板创建的每台虚拟机共享模板的 SEP 根密钥和 Data 卷密钥。"
+ }
+ }
+ }
+ },
+ "%@ (earlier build, deleted)" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ (earlier build, deleted)"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@(以前のビルド、削除済み)"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@(이전 빌드, 삭제됨)"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ (bản dựng trước, đã xóa)"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@(较早的构建,已删除)"
+ }
+ }
+ }
+ },
+ "%@ (deleted)" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ (deleted)"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@(削除済み)"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@(삭제됨)"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ (đã xóa)"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@(已删除)"
+ }
+ }
+ }
+ },
"Delete IPSWs…" : {
"localizations" : {
"en" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
index 95aed9dd..f8f7b003 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift
@@ -171,11 +171,10 @@ struct VPhoneLaunchpadMachineInspector: View {
if let udid = machine.udid {
value("UDID", udid)
}
- if let template = library.templateSources[machine.path] {
+ if let origin = library.templateSources[machine.path] {
LabeledContent("Template") {
- Text(verbatim: template)
+ templateLabel(origin)
.textSelection(.enabled)
- .help(String(localized: "Created from this template. It shares the template's SEP root secret and Data volume keys with every machine created from it."))
}
}
value(
@@ -460,6 +459,24 @@ struct VPhoneLaunchpadMachineInspector: View {
}
}
+ /// The template's identifier. A clone of an earlier build of the same
+ /// key, or of a deleted template, says so, and shares no key with the
+ /// template that has the identifier now.
+ @ViewBuilder
+ private func templateLabel(_ origin: VPhoneLaunchpadTemplateOrigin) -> some View {
+ switch origin.match {
+ case .current:
+ Text(verbatim: origin.identifier)
+ .help(String(localized: "Created from this template. It shares the template's SEP root secret and Data volume keys with every machine created from it."))
+ case .earlierBuild:
+ Text("\(origin.identifier) (earlier build, deleted)")
+ .help(String(localized: "Created from an earlier build of this template, since deleted. It shares its SEP root secret and Data volume keys only with the machines created from that build, not with the template that has this identifier now or the machines created from it."))
+ case .deleted:
+ Text("\(origin.identifier) (deleted)")
+ .help(String(localized: "Created from this template, which was deleted. It shares the template's SEP root secret and Data volume keys with every machine created from it."))
+ }
+ }
+
private func creationSummary(_ creation: VPhoneLaunchpadCreationPipeline) -> some View {
LabeledContent {
Button(creation.isRunning ? LocalizedStringKey("Show Progress") : LocalizedStringKey("View Details")) {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index d87205a7..21c5eb57 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -771,8 +771,9 @@ final class VPhoneLaunchpadMachineLibrary {
/// What each listed machine takes on disk, measured off the main actor
/// at most every `diskUsageInterval` seconds.
private(set) var diskUsage: [Path: VPhoneLaunchpadDiskUsage] = [:]
- /// The template each machine was cloned from (its `TemplateSource.plist`).
- private(set) var templateSources: [Path: String] = [:]
+ /// The template each machine was cloned from (its `TemplateSource.plist`),
+ /// and whether it is the build that has that identifier now.
+ private(set) var templateSources: [Path: VPhoneLaunchpadTemplateOrigin] = [:]
private var diskUsageMeasured: Date?
private var isMeasuringDiskUsage = false
/// A forced measurement asked for while one ran.
@@ -861,7 +862,7 @@ final class VPhoneLaunchpadMachineLibrary {
templatesMayOpen: Bool,
meter: VPhoneLaunchpadDiskMeter,
mayOpenNow: @escaping @Sendable (String) async -> Bool,
- ) async -> (usage: [Path: VPhoneLaunchpadDiskUsage], sources: [Path: String], templates: [String: VPhoneLaunchpadDiskUsage]) {
+ ) async -> (usage: [Path: VPhoneLaunchpadDiskUsage], sources: [Path: VPhoneLaunchpadTemplateOrigin], templates: [String: VPhoneLaunchpadDiskUsage]) {
// Templates are keyed as `usage(of:)` looks them up.
var templateKeys: [String: String] = [:]
for root in libraryRoots {
@@ -872,10 +873,10 @@ final class VPhoneLaunchpadMachineLibrary {
let folders = machineFolders + templateKeys.keys.sorted().map { VPhoneLaunchpadDiskMeter.Folder(path: $0, mayOpen: templatesMayOpen) }
let measured = await meter.measure(folders, mayOpenNow: mayOpenNow)
var usage: [Path: VPhoneLaunchpadDiskUsage] = [:]
- var sources: [Path: String] = [:]
+ var sources: [Path: VPhoneLaunchpadTemplateOrigin] = [:]
for path in paths {
usage[path] = measured[path.url.path]
- sources[path] = templateSource(in: path.url)
+ sources[path] = VPhoneLaunchpadTemplateOrigin.read(machine: path.url, libraryRoot: path.libraryRoot)
}
var templates: [String: VPhoneLaunchpadDiskUsage] = [:]
for (folder, key) in templateKeys {
@@ -884,20 +885,6 @@ final class VPhoneLaunchpadMachineLibrary {
return (usage, sources, templates)
}
- /// The `Identifier` of `TemplateSource.plist`, when it names a template.
- nonisolated static func templateSource(in folder: URL) -> String? {
- let file = folder.appendingPathComponent("TemplateSource.plist")
- guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]),
- values.isRegularFile == true, values.isSymbolicLink != true,
- let record = NSDictionary(contentsOf: file),
- let identifier = record["Identifier"] as? String,
- identifier.wholeMatch(of: /[0-9a-f]{12}/) != nil
- else {
- return nil
- }
- return identifier
- }
-
// MARK: - Templates
/// Every library's templates, from `vm template list --json` with the
@@ -1267,7 +1254,10 @@ final class VPhoneLaunchpadMachineLibrary {
research: VPhoneLaunchpadDiskUsage(allocated: 17_812_000_000, exclusive: 612_000_000),
VPhoneLaunchpadPreview.labMachine: VPhoneLaunchpadDiskUsage(allocated: 21_406_000_000, exclusive: 3_240_000_000),
]
- templateSources = [research: "52b1fcc75e0c", VPhoneLaunchpadPreview.labMachine: "2246f982776c"]
+ templateSources = [
+ research: VPhoneLaunchpadTemplateOrigin(identifier: "52b1fcc75e0c", match: .current),
+ VPhoneLaunchpadPreview.labMachine: VPhoneLaunchpadTemplateOrigin(identifier: "2246f982776c", match: .current),
+ ]
diskUsageMeasured = Date()
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
index 0fab38a9..8c986d5a 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
@@ -517,6 +517,139 @@ nonisolated struct VPhoneLaunchpadTemplateFind: Decodable, Sendable {
}
}
+// MARK: - Template of a machine
+
+/// The template a machine was cloned from, read from its
+/// `TemplateSource.plist`, and whether it is the template that has that
+/// identifier in its library now.
+///
+/// The identifier names a key, and a template deleted and built again gets
+/// the same one, but a clone of the earlier build shares no block and no key
+/// with the new template. The match is `vphone-cli`'s
+/// (`VPhoneMachineTemplateSource.isClone(of:)`).
+nonisolated struct VPhoneLaunchpadTemplateOrigin: Hashable, Sendable {
+ enum Match: Hashable, Sendable {
+ /// Cloned from the template that has the identifier now.
+ case current
+ /// Cloned from an earlier build with the same key, since deleted.
+ case earlierBuild
+ /// No template has the identifier now.
+ case deleted
+ }
+
+ /// `TemplateSource.plist` (`VPhoneMachineTemplateSource`).
+ struct Source: Hashable, Sendable {
+ let identifier: String
+ /// The build cloned from; nil in a record written before builds
+ /// were recorded.
+ let build: String?
+ let cloned: Date
+
+ init(identifier: String, build: String? = nil, cloned: Date) {
+ self.identifier = identifier
+ self.build = build
+ self.cloned = cloned
+ }
+
+ init?(_ plist: [String: Any]) {
+ guard let identifier = plist["Identifier"] as? String,
+ identifier.wholeMatch(of: /[0-9a-f]{12}/) != nil,
+ let cloned = plist["Cloned"] as? Date
+ else {
+ return nil
+ }
+ self.init(identifier: identifier, build: plist["Build"] as? String, cloned: cloned)
+ }
+ }
+
+ /// What the match needs of a frozen template's `Template.plist`
+ /// (`VPhoneMachineTemplateRecord`).
+ struct Template: Hashable, Sendable {
+ let identifier: String
+ /// Nil for a template frozen before builds were recorded.
+ let build: String?
+ let created: Date
+ let frozenAt: Date?
+
+ init(identifier: String, build: String? = nil, created: Date, frozenAt: Date? = nil) {
+ self.identifier = identifier
+ self.build = build
+ self.created = created
+ self.frozenAt = frozenAt
+ }
+
+ /// Nil for a template the CLI does not list: never frozen, or not
+ /// matching its folder name.
+ init?(_ plist: [String: Any], folderName: String) {
+ guard let identifier = plist["Identifier"] as? String, identifier == folderName,
+ plist["Frozen"] as? Bool == true,
+ let created = plist["Created"] as? Date
+ else {
+ return nil
+ }
+ self.init(identifier: identifier, build: plist["Build"] as? String, created: created, frozenAt: plist["FrozenAt"] as? Date)
+ }
+ }
+
+ let identifier: String
+ let match: Match
+
+ init(identifier: String, match: Match) {
+ self.identifier = identifier
+ self.match = match
+ }
+
+ /// `template` is the one with the source's identifier in the machine's
+ /// library, or nil when there is none.
+ init(_ source: Source, template: Template?) {
+ let match: Match = if let template {
+ Self.isClone(source, of: template) ? .current : .earlierBuild
+ } else {
+ .deleted
+ }
+ self.init(identifier: source.identifier, match: match)
+ }
+
+ /// Both builds known decide it. Otherwise (a record on either side
+ /// written before builds were recorded) a machine cloned before the
+ /// template was frozen cannot have come from it.
+ static func isClone(_ source: Source, of template: Template) -> Bool {
+ guard source.identifier == template.identifier else {
+ return false
+ }
+ if let build = source.build, let other = template.build {
+ return build == other
+ }
+ return source.cloned >= (template.frozenAt ?? template.created)
+ }
+
+ /// The origin of the machine in `folder`, nil when it was not cloned
+ /// from a template or its record cannot be read.
+ static func read(machine folder: URL, libraryRoot: String) -> Self? {
+ guard let source = plist(folder.appendingPathComponent("TemplateSource.plist")).flatMap(Source.init) else {
+ return nil
+ }
+ let templateFolder = URL(fileURLWithPath: libraryRoot, isDirectory: true)
+ .appendingPathComponent(".templates", isDirectory: true)
+ .appendingPathComponent(source.identifier, isDirectory: true)
+ let template = plist(templateFolder.appendingPathComponent("Template.plist")).flatMap {
+ Template($0, folderName: source.identifier)
+ }
+ return Self(source, template: template)
+ }
+
+ /// A regular file's property list dictionary, not through a link.
+ private static func plist(_ file: URL) -> [String: Any]? {
+ guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]),
+ values.isRegularFile == true, values.isSymbolicLink != true,
+ let data = try? Data(contentsOf: file)
+ else {
+ return nil
+ }
+ return (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any]
+ }
+}
+
// MARK: - Last machine of a template
/// What `vm delete` notes when the machine was the last one cloned from a