Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Shut the guest down before Launchpad stops a machine

Jacky8af70697cce9
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.md
index 42f41787..85be99f5 100644
--- a/Documents/Guides/launchpad-cli.md
+++ b/Documents/Guides/launchpad-cli.md
@@ -106,7 +106,7 @@ version while a machine is bound to it; rebind or delete those machines first.
| `bundle set-default <version>` / `bundle verify <version>` | Make a version the default, or re-check it. `bundle use` is the old name of `set-default` |
| `bundle accept <version> [--off]` / `bundle remove <version>` | Skip failed checks, or remove a version no machine is bound to |
| `vm list` | Machines in every library with run state, Core Bundle and log path |
-| `vm start <name> [--headless] [--wait]` / `vm stop <name>` | Launch with the machine's bundle, or stop; `--wait` waits for vphoned |
+| `vm start <name> [--headless] [--wait]` / `vm stop <name>` | Launch with the machine's bundle, or stop; `--wait` waits for vphoned. Stop asks the guest to shut down (vphoned `system.shutdown`) and waits up to 30 s; when the guest cannot be asked or does not stop, it ends the virtual machine as before |
| `vm wait <name>` / `vm log <name> [--kind create\|dfu\|patch]` | Wait for vphoned; read a console log |
| `vm create <name> [--bundle <version>] [...] [--device <product-type>] [--from <step>]` | The New Machine pipeline, bound to `--bundle` or the default; `--device` makes an iPad guest, `--from` retries from a step |
| `vm set-bundle <name> <version> [--update-environment]` | Bind a machine to another installed version. `--update-environment` also redeploys that version's guest environment and needs a stopped machine |
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
index 37c4b08e..5e3887a3 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -833,9 +833,12 @@ final nonisolated class VPhoneLaunchpadLogFollower: @unchecked Sendable {
/// One request to a machine's vphone.sock: a JSON line in, a JSON line out.
nonisolated enum VPhoneLaunchpadGuestSocket {
- static func send(_ object: [String: Any], socketPath: String) async throws -> Any {
+ /// `timeout` is how long to wait for the reply, in seconds. vphone-vm
+ /// waits on vphoned for up to its own limit, and an rpc such as a package
+ /// install can take a while, so the default is long.
+ static func send(_ object: [String: Any], socketPath: String, timeout: Int = 120) async throws -> Any {
let line = try JSONSerialization.data(withJSONObject: object) + Data([0x0A])
- let response = try await Task.detached { try exchange(line, socketPath: socketPath) }.value
+ let response = try await Task.detached { try exchange(line, socketPath: socketPath, timeout: timeout) }.value
guard let json = try? JSONSerialization.jsonObject(with: response) else {
throw VPhoneLaunchpadError("The machine sent a reply that could not be read. Try again.", detail: String(decoding: response.prefix(512), as: UTF8.self))
}
@@ -845,7 +848,7 @@ nonisolated enum VPhoneLaunchpadGuestSocket {
return json
}
- private static func exchange(_ line: Data, socketPath: String) throws -> Data {
+ private static func exchange(_ line: Data, socketPath: String, timeout seconds: Int) throws -> Data {
guard FileManager.default.fileExists(atPath: socketPath) else {
throw VPhoneLaunchpadError(
"The machine has no vphone.sock.",
@@ -861,9 +864,7 @@ nonisolated enum VPhoneLaunchpadGuestSocket {
throw VPhoneLaunchpadError("Unable to open a socket.")
}
defer { close(fd) }
- // vphone-vm waits on vphoned for up to its own limit; an rpc such as
- // a package install can take a while.
- var timeout = timeval(tv_sec: 120, tv_usec: 0)
+ var timeout = timeval(tv_sec: seconds, tv_usec: 0)
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
_ = fcntl(fd, F_SETNOSIGPIPE, 1)
let connected = withUnsafePointer(to: &address) {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index 87528d71..99b570ca 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -10747,6 +10747,40 @@
}
}
},
+ "Shutting down…" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Shutting down…"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "システム終了中…"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "종료 중…"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Đang tắt máy…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在关机…"
+ }
+ }
+ }
+ },
"Stopping…" : {
"localizations" : {
"en" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index f639f2d4..cf0eb341 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -527,11 +527,59 @@ final class VPhoneLaunchpadMachineLibrary {
await refresh()
}
+ /// Stops a machine. The guest is asked to shut down first, so it quits its
+ /// apps and unmounts its volumes. `vm stop`, which ends the virtual
+ /// machine the way cutting the power would, follows only when the guest
+ /// cannot be asked or has not stopped in time.
func stop(_ machine: Path) async {
+ if await shutDownGuest(machine) {
+ await refresh()
+ return
+ }
await perform(String(localized: "Stopping…"), on: machine, ["vm", "stop", machine.name] + machine.libraryArguments)
launched[machine]?.interrupt()
}
+ /// How long a guest gets to shut down before `vm stop` takes over.
+ private static let guestShutdownTimeout: TimeInterval = 30
+
+ /// Sends vphoned's `system.shutdown` over the machine's vphone.sock and
+ /// waits for the virtual machine to stop. False when the guest could not
+ /// be asked (not started up yet, in DFU, or a vphoned older than the
+ /// method) or is still running when the time is up.
+ private func shutDownGuest(_ machine: Path) async -> Bool {
+ // A panicked guest has no vphoned left to ask.
+ guard !panicked.contains(machine) else {
+ return false
+ }
+ activities[machine] = String(localized: "Shutting down…")
+ defer { activities[machine] = nil }
+ let request: [String: Any] = ["t": "rpc", "method": "system.shutdown", "params": ["force": true]]
+ let socket = machine.url.appendingPathComponent("vphone.sock").path
+ do {
+ _ = try await VPhoneLaunchpadGuestSocket.send(request, socketPath: socket, timeout: 10)
+ } catch {
+ return await !isRunning(machine)
+ }
+ let deadline = Date().addingTimeInterval(Self.guestShutdownTimeout)
+ while Date() < deadline {
+ if await !isRunning(machine) {
+ return true
+ }
+ try? await Task.sleep(for: .seconds(1))
+ }
+ return false
+ }
+
+ /// Whether the machine's virtual machine is still up: the process
+ /// Launchpad started, or for one started elsewhere, whoever holds its disk.
+ private func isRunning(_ machine: Path) async -> Bool {
+ if let child = launched[machine] {
+ return child.isRunning
+ }
+ return await Task.detached { !Self.machinesHoldingDisks([machine]).isEmpty }.value
+ }
+
// MARK: - Edits
/// `networkArguments` are further `vm config` options (address, MAC, forwards),
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
index c418be84..181332d3 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
@@ -161,7 +161,7 @@ nonisolated struct VPhoneLaunchpadControlCommand: Sendable {
Self(name: "vm.start", arguments: ["name"], options: ["root", "timeout"], flags: ["headless", "wait"],
summary: "Launch a machine. --wait blocks until vphoned answers on vphone.sock."),
Self(name: "vm.stop", arguments: ["name"], options: ["root"], flags: [],
- summary: "Stop a machine."),
+ summary: "Stop a machine: the guest shuts down first, and the virtual machine is ended only if it cannot or does not in time."),
Self(name: "vm.wait", arguments: ["name"], options: ["root", "timeout"], flags: [],
summary: "Wait until vphoned answers on the machine's vphone.sock."),
Self(name: "vm.log", arguments: ["name"], options: ["root", "lines", "kind"], flags: [],