UTMScriptingVirtualMachineImpl.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. //
  2. // Copyright © 2022 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import Foundation
  17. @MainActor
  18. @objc(UTMScriptingVirtualMachineImpl)
  19. class UTMScriptingVirtualMachineImpl: NSObject, UTMScriptable {
  20. @nonobjc var vm: UTMVirtualMachine
  21. @nonobjc var data: UTMData
  22. @objc var id: String {
  23. vm.id.uuidString
  24. }
  25. @objc var name: String {
  26. vm.detailsTitleLabel
  27. }
  28. @objc var notes: String {
  29. vm.detailsNotes ?? ""
  30. }
  31. @objc var machine: String {
  32. vm.detailsSystemTargetLabel
  33. }
  34. @objc var architecture: String {
  35. vm.detailsSystemArchitectureLabel
  36. }
  37. @objc var memory: String {
  38. vm.detailsSystemMemoryLabel
  39. }
  40. @objc var backend: UTMScriptingBackend {
  41. if vm is UTMQemuVirtualMachine {
  42. return .qemu
  43. } else if vm is UTMAppleVirtualMachine {
  44. return .apple
  45. } else {
  46. return .unavailable
  47. }
  48. }
  49. @objc var status: UTMScriptingStatus {
  50. switch vm.state {
  51. case .vmStopped: return .stopped
  52. case .vmStarting: return .starting
  53. case .vmStarted: return .started
  54. case .vmPausing: return .pausing
  55. case .vmPaused: return .paused
  56. case .vmResuming: return .resuming
  57. case .vmStopping: return .stopping
  58. @unknown default: return .stopped
  59. }
  60. }
  61. @objc var serialPorts: [UTMScriptingSerialPortImpl] {
  62. if let config = vm.config.qemuConfig {
  63. return config.serials.indices.map({ UTMScriptingSerialPortImpl(qemuSerial: config.serials[$0], parent: self, index: $0) })
  64. } else if let config = vm.config.appleConfig {
  65. return config.serials.indices.map({ UTMScriptingSerialPortImpl(appleSerial: config.serials[$0], parent: self, index: $0) })
  66. } else {
  67. return []
  68. }
  69. }
  70. var guestAgent: UTMQemuGuestAgent? {
  71. (vm as? UTMQemuVirtualMachine)?.guestAgent
  72. }
  73. override var objectSpecifier: NSScriptObjectSpecifier? {
  74. let appDescription = NSApplication.classDescription() as! NSScriptClassDescription
  75. return NSUniqueIDSpecifier(containerClassDescription: appDescription,
  76. containerSpecifier: nil,
  77. key: "scriptingVirtualMachines",
  78. uniqueID: id)
  79. }
  80. init(for vm: UTMVirtualMachine, data: UTMData) {
  81. self.vm = vm
  82. self.data = data
  83. }
  84. @objc func start(_ command: NSScriptCommand) {
  85. let shouldSaveState = command.evaluatedArguments?["saveFlag"] as? Bool ?? true
  86. withScriptCommand(command) { [self] in
  87. if !shouldSaveState {
  88. guard let vm = vm as? UTMQemuVirtualMachine else {
  89. throw ScriptingError.operationNotSupported
  90. }
  91. vm.isRunningAsSnapshot = true
  92. }
  93. data.run(vm: vm, startImmediately: false)
  94. if vm.state == .vmStopped {
  95. try await vm.vmStart()
  96. } else if vm.state == .vmPaused {
  97. try await vm.vmResume()
  98. } else {
  99. throw ScriptingError.operationNotAvailable
  100. }
  101. }
  102. }
  103. @objc func suspend(_ command: NSScriptCommand) {
  104. let shouldSaveState = command.evaluatedArguments?["saveFlag"] as? Bool ?? false
  105. withScriptCommand(command) { [self] in
  106. guard vm.state == .vmStarted else {
  107. throw ScriptingError.notRunning
  108. }
  109. try await vm.vmPause(save: shouldSaveState)
  110. }
  111. }
  112. @objc func stop(_ command: NSScriptCommand) {
  113. let stopMethod: UTMScriptingStopMethod
  114. if let stopMethodValue = command.evaluatedArguments?["stopBy"] as? AEKeyword {
  115. stopMethod = UTMScriptingStopMethod(rawValue: stopMethodValue) ?? .force
  116. } else {
  117. stopMethod = .force
  118. }
  119. withScriptCommand(command) { [self] in
  120. guard vm.state == .vmStarted || stopMethod == .kill else {
  121. throw ScriptingError.notRunning
  122. }
  123. switch stopMethod {
  124. case .force:
  125. try await vm.vmStop(force: false)
  126. case .kill:
  127. try await vm.vmStop(force: true)
  128. case .request:
  129. vm.requestGuestPowerDown()
  130. }
  131. }
  132. }
  133. @objc func delete(_ command: NSDeleteCommand) {
  134. withScriptCommand(command) { [self] in
  135. guard vm.state == .vmStopped else {
  136. throw ScriptingError.notStopped
  137. }
  138. try await data.delete(vm: vm, alsoRegistry: true)
  139. }
  140. }
  141. @objc func clone(_ command: NSCloneCommand) {
  142. let properties = command.evaluatedArguments?["WithProperties"] as? [AnyHashable : Any]
  143. withScriptCommand(command) { [self] in
  144. guard vm.state == .vmStopped else {
  145. throw ScriptingError.notStopped
  146. }
  147. let newVM = try await data.clone(vm: vm)
  148. if let properties = properties, let newConfiguration = properties["configuration"] as? [AnyHashable : Any] {
  149. let wrapper = UTMScriptingConfigImpl(newVM.config.wrappedValue as! any UTMConfiguration)
  150. try wrapper.updateConfiguration(from: newConfiguration)
  151. try await data.save(vm: newVM)
  152. }
  153. }
  154. }
  155. }
  156. // MARK: - Guest agent suite
  157. @objc extension UTMScriptingVirtualMachineImpl {
  158. @nonobjc private func withGuestAgent<Result>(_ block: (UTMQemuGuestAgent) async throws -> Result) async throws -> Result {
  159. guard vm.state == .vmStarted else {
  160. throw ScriptingError.notRunning
  161. }
  162. guard let vm = vm as? UTMQemuVirtualMachine else {
  163. throw ScriptingError.operationNotSupported
  164. }
  165. guard let guestAgent = vm.guestAgent else {
  166. throw ScriptingError.guestAgentNotRunning
  167. }
  168. return try await block(guestAgent)
  169. }
  170. @objc func valueInOpenFilesWithUniqueID(_ id: Int) -> UTMScriptingGuestFileImpl {
  171. UTMScriptingGuestFileImpl(from: id, parent: self)
  172. }
  173. @objc func openFile(_ command: NSScriptCommand) {
  174. let path = command.evaluatedArguments?["path"] as? String
  175. let mode = command.evaluatedArguments?["mode"] as? AEKeyword
  176. let isUpdate = command.evaluatedArguments?["isUpdate"] as? Bool ?? false
  177. withScriptCommand(command) { [self] in
  178. guard let path = path else {
  179. throw ScriptingError.invalidParameter
  180. }
  181. let modeValue: String
  182. if let mode = mode {
  183. switch UTMScriptingOpenMode(rawValue: mode) {
  184. case .reading: modeValue = "r"
  185. case .writing: modeValue = "w"
  186. case .appending: modeValue = "a"
  187. default: modeValue = "r"
  188. }
  189. } else {
  190. modeValue = "r"
  191. }
  192. return try await withGuestAgent { guestAgent in
  193. let handle = try await guestAgent.guestFileOpen(path, mode: modeValue + (isUpdate ? "+" : ""))
  194. return UTMScriptingGuestFileImpl(from: handle, parent: self)
  195. }
  196. }
  197. }
  198. @objc func valueInProcessesWithUniqueID(_ id: Int) -> UTMScriptingGuestProcessImpl {
  199. UTMScriptingGuestProcessImpl(from: id, parent: self)
  200. }
  201. @objc func execute(_ command: NSScriptCommand) {
  202. let path = command.evaluatedArguments?["path"] as? String
  203. let argv = command.evaluatedArguments?["argv"] as? [String]
  204. let envp = command.evaluatedArguments?["envp"] as? [String]
  205. let input = command.evaluatedArguments?["input"] as? String
  206. let isBase64Encoded = command.evaluatedArguments?["isBase64Encoded"] as? Bool ?? false
  207. let isCaptureOutput = command.evaluatedArguments?["isCaptureOutput"] as? Bool ?? false
  208. let inputData = dataFromText(input, isBase64Encoded: isBase64Encoded)
  209. withScriptCommand(command) { [self] in
  210. guard let path = path else {
  211. throw ScriptingError.invalidParameter
  212. }
  213. return try await withGuestAgent { guestAgent in
  214. let pid = try await guestAgent.guestExec(path, argv: argv, envp: envp, input: inputData, captureOutput: isCaptureOutput)
  215. return UTMScriptingGuestProcessImpl(from: pid, parent: self)
  216. }
  217. }
  218. }
  219. @objc func queryIp(_ command: NSScriptCommand) {
  220. withScriptCommand(command) { [self] in
  221. try await withGuestAgent { guestAgent in
  222. let interfaces = try await guestAgent.guestNetworkGetInterfaces()
  223. var ipv4: [String] = []
  224. var ipv6: [String] = []
  225. for interface in interfaces {
  226. for ip in interface.ipAddresses {
  227. if ip.isIpV6Address {
  228. if ip.ipAddress != "::1" && ip.ipAddress != "0:0:0:0:0:0:0:1" {
  229. ipv6.append(ip.ipAddress)
  230. }
  231. } else {
  232. if ip.ipAddress != "127.0.0.1" {
  233. ipv4.append(ip.ipAddress)
  234. }
  235. }
  236. }
  237. }
  238. return ipv4 + ipv6
  239. }
  240. }
  241. }
  242. }
  243. // MARK: - Errors
  244. extension UTMScriptingVirtualMachineImpl {
  245. enum ScriptingError: Error, LocalizedError {
  246. case operationNotAvailable
  247. case operationNotSupported
  248. case notRunning
  249. case notStopped
  250. case guestAgentNotRunning
  251. case invalidParameter
  252. var errorDescription: String? {
  253. switch self {
  254. case .operationNotAvailable: return NSLocalizedString("Operation not available.", comment: "UTMScriptingVirtualMachineImpl")
  255. case .operationNotSupported: return NSLocalizedString("Operation not supported by the backend.", comment: "UTMScriptingVirtualMachineImpl")
  256. case .notRunning: return NSLocalizedString("The virtual machine is not running.", comment: "UTMScriptingVirtualMachineImpl")
  257. case .notStopped: return NSLocalizedString("The virtual machine must be stopped before this operation can be performed.", comment: "UTMScriptingVirtualMachineImpl")
  258. case .guestAgentNotRunning: return NSLocalizedString("The QEMU guest agent is not running or not installed on the guest.", comment: "UTMScriptingVirtualMachineImpl")
  259. case .invalidParameter: return NSLocalizedString("One or more required parameters are missing or invalid.", comment: "UTMScriptingVirtualMachineImpl")
  260. }
  261. }
  262. }
  263. }