UTMScriptingVirtualMachineImpl.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. import QEMUKitInternal
  18. @MainActor
  19. @objc(UTMScriptingVirtualMachineImpl)
  20. class UTMScriptingVirtualMachineImpl: NSObject, UTMScriptable {
  21. @nonobjc var box: VMData
  22. @nonobjc var data: UTMData
  23. @nonobjc var vm: (any UTMVirtualMachine)! {
  24. box.wrapped
  25. }
  26. @objc var id: String {
  27. vm.id.uuidString
  28. }
  29. @objc var name: String {
  30. box.detailsTitleLabel
  31. }
  32. @objc var notes: String {
  33. box.detailsNotes ?? ""
  34. }
  35. @objc var machine: String {
  36. box.detailsSystemTargetLabel
  37. }
  38. @objc var architecture: String {
  39. box.detailsSystemArchitectureLabel
  40. }
  41. @objc var memory: String {
  42. box.detailsSystemMemoryLabel
  43. }
  44. @objc var backend: UTMScriptingBackend {
  45. if vm is UTMQemuVirtualMachine {
  46. return .qemu
  47. } else if vm is UTMAppleVirtualMachine {
  48. return .apple
  49. } else {
  50. return .unavailable
  51. }
  52. }
  53. @objc var status: UTMScriptingStatus {
  54. switch vm.state {
  55. case .stopped: return .stopped
  56. case .starting: return .starting
  57. case .started: return .started
  58. case .pausing: return .pausing
  59. case .paused: return .paused
  60. case .resuming: return .resuming
  61. case .stopping: return .stopping
  62. case .saving: return .pausing // FIXME: new entries
  63. case .restoring: return .resuming // FIXME: new entries
  64. }
  65. }
  66. @objc var serialPorts: [UTMScriptingSerialPortImpl] {
  67. if let config = vm.config as? UTMQemuConfiguration {
  68. return config.serials.indices.map({ UTMScriptingSerialPortImpl(qemuSerial: config.serials[$0], parent: self, index: $0) })
  69. } else if let config = vm.config as? UTMAppleConfiguration {
  70. return config.serials.indices.map({ UTMScriptingSerialPortImpl(appleSerial: config.serials[$0], parent: self, index: $0) })
  71. } else {
  72. return []
  73. }
  74. }
  75. var guestAgent: QEMUGuestAgent! {
  76. get async {
  77. await (vm as? UTMQemuVirtualMachine)?.guestAgent
  78. }
  79. }
  80. var qemuProcess: UTMQemuSystem? {
  81. get async {
  82. await (vm as? UTMQemuVirtualMachine)?.system
  83. }
  84. }
  85. override var objectSpecifier: NSScriptObjectSpecifier? {
  86. let appDescription = NSApplication.classDescription() as! NSScriptClassDescription
  87. return NSUniqueIDSpecifier(containerClassDescription: appDescription,
  88. containerSpecifier: nil,
  89. key: "scriptingVirtualMachines",
  90. uniqueID: id)
  91. }
  92. init(for vm: VMData, data: UTMData) {
  93. self.box = vm
  94. self.data = data
  95. }
  96. @objc func start(_ command: NSScriptCommand) {
  97. let shouldSaveState = command.evaluatedArguments?["saveFlag"] as? Bool ?? true
  98. let bootRecoveryMode = command.evaluatedArguments?["bootRecoveryFlag"] as? Bool ?? false
  99. withScriptCommand(command) { [self] in
  100. var options: UTMVirtualMachineStartOptions = []
  101. if !shouldSaveState {
  102. guard type(of: vm).capabilities.supportsDisposibleMode else {
  103. throw ScriptingError.operationNotSupported
  104. }
  105. options.insert(.bootDisposibleMode)
  106. }
  107. if bootRecoveryMode {
  108. guard type(of: vm).capabilities.supportsRecoveryMode else {
  109. throw ScriptingError.operationNotSupported
  110. }
  111. options.insert(.bootRecovery)
  112. }
  113. data.run(vm: box, startImmediately: false)
  114. if vm.state == .stopped {
  115. try await vm.start(options: options)
  116. } else if vm.state == .paused {
  117. try await vm.resume()
  118. } else {
  119. throw ScriptingError.operationNotAvailable
  120. }
  121. }
  122. }
  123. @objc func suspend(_ command: NSScriptCommand) {
  124. let shouldSaveState = command.evaluatedArguments?["saveFlag"] as? Bool ?? false
  125. withScriptCommand(command) { [self] in
  126. guard vm.state == .started else {
  127. throw ScriptingError.notRunning
  128. }
  129. try await vm.pause()
  130. if shouldSaveState {
  131. try await vm.saveSnapshot(name: nil)
  132. }
  133. }
  134. }
  135. @objc func stop(_ command: NSScriptCommand) {
  136. let stopMethod: UTMScriptingStopMethod
  137. if let stopMethodValue = command.evaluatedArguments?["stopBy"] as? AEKeyword {
  138. stopMethod = UTMScriptingStopMethod(rawValue: stopMethodValue) ?? .force
  139. } else {
  140. stopMethod = .force
  141. }
  142. withScriptCommand(command) { [self] in
  143. guard vm.state == .started || stopMethod == .kill else {
  144. throw ScriptingError.notRunning
  145. }
  146. switch stopMethod {
  147. case .force:
  148. try await vm.stop(usingMethod: .force)
  149. case .kill:
  150. try await vm.stop(usingMethod: .kill)
  151. case .request:
  152. try await vm.stop(usingMethod: .request)
  153. }
  154. }
  155. }
  156. @objc func delete(_ command: NSDeleteCommand) {
  157. withScriptCommand(command) { [self] in
  158. guard vm.state == .stopped else {
  159. throw ScriptingError.notStopped
  160. }
  161. try await data.delete(vm: box, alsoRegistry: true)
  162. }
  163. }
  164. @objc func clone(_ command: NSCloneCommand) {
  165. let properties = command.evaluatedArguments?["WithProperties"] as? [AnyHashable : Any]
  166. withScriptCommand(command) { [self] in
  167. guard vm.state == .stopped else {
  168. throw ScriptingError.notStopped
  169. }
  170. let newVM = try await data.clone(vm: box)
  171. if let properties = properties, let newConfiguration = properties["configuration"] as? [AnyHashable : Any] {
  172. let wrapper = UTMScriptingConfigImpl(newVM.config!)
  173. try wrapper.updateConfiguration(from: newConfiguration)
  174. try await data.save(vm: newVM)
  175. }
  176. }
  177. }
  178. @objc func export(_ command: NSCloneCommand) {
  179. let exportUrl = command.evaluatedArguments?["file"] as? URL
  180. withScriptCommand(command) { [self] in
  181. guard vm.state == .stopped else {
  182. throw ScriptingError.notStopped
  183. }
  184. try await data.export(vm: box, to: exportUrl!)
  185. }
  186. }
  187. }
  188. // MARK: - Guest agent suite
  189. @objc extension UTMScriptingVirtualMachineImpl {
  190. @nonobjc private func withGuestAgent<Result>(_ block: (QEMUGuestAgent) async throws -> Result) async throws -> Result {
  191. guard vm.state == .started else {
  192. throw ScriptingError.notRunning
  193. }
  194. guard let vm = vm as? UTMQemuVirtualMachine else {
  195. throw ScriptingError.operationNotSupported
  196. }
  197. guard let guestAgent = await vm.guestAgent else {
  198. throw ScriptingError.guestAgentNotRunning
  199. }
  200. return try await block(guestAgent)
  201. }
  202. @objc func valueInOpenFilesWithUniqueID(_ id: Int) -> UTMScriptingGuestFileImpl {
  203. UTMScriptingGuestFileImpl(from: id, parent: self)
  204. }
  205. @objc func openFile(_ command: NSScriptCommand) {
  206. let path = command.evaluatedArguments?["path"] as? String
  207. let mode = command.evaluatedArguments?["mode"] as? AEKeyword
  208. let isUpdate = command.evaluatedArguments?["isUpdate"] as? Bool ?? false
  209. withScriptCommand(command) { [self] in
  210. guard let path = path else {
  211. throw ScriptingError.invalidParameter
  212. }
  213. let modeValue: String
  214. if let mode = mode {
  215. switch UTMScriptingOpenMode(rawValue: mode) {
  216. case .reading: modeValue = "r"
  217. case .writing: modeValue = "w"
  218. case .appending: modeValue = "a"
  219. default: modeValue = "r"
  220. }
  221. } else {
  222. modeValue = "r"
  223. }
  224. return try await withGuestAgent { guestAgent in
  225. let handle = try await guestAgent.guestFileOpen(path, mode: modeValue + (isUpdate ? "+" : ""))
  226. return UTMScriptingGuestFileImpl(from: handle, parent: self)
  227. }
  228. }
  229. }
  230. @objc func valueInProcessesWithUniqueID(_ id: Int) -> UTMScriptingGuestProcessImpl {
  231. UTMScriptingGuestProcessImpl(from: id, parent: self)
  232. }
  233. @objc func execute(_ command: NSScriptCommand) {
  234. let path = command.evaluatedArguments?["path"] as? String
  235. let argv = command.evaluatedArguments?["argv"] as? [String]
  236. let envp = command.evaluatedArguments?["envp"] as? [String]
  237. let input = command.evaluatedArguments?["input"] as? String
  238. let isBase64Encoded = command.evaluatedArguments?["isBase64Encoded"] as? Bool ?? false
  239. let isCaptureOutput = command.evaluatedArguments?["isCaptureOutput"] as? Bool ?? false
  240. let inputData = dataFromText(input, isBase64Encoded: isBase64Encoded)
  241. withScriptCommand(command) { [self] in
  242. guard let path = path else {
  243. throw ScriptingError.invalidParameter
  244. }
  245. return try await withGuestAgent { guestAgent in
  246. let pid = try await guestAgent.guestExec(path, argv: argv, envp: envp, input: inputData, captureOutput: isCaptureOutput)
  247. return UTMScriptingGuestProcessImpl(from: pid, parent: self)
  248. }
  249. }
  250. }
  251. @objc func queryIp(_ command: NSScriptCommand) {
  252. withScriptCommand(command) { [self] in
  253. try await withGuestAgent { guestAgent in
  254. let interfaces = try await guestAgent.guestNetworkGetInterfaces()
  255. var ipv4: [String] = []
  256. var ipv6: [String] = []
  257. for interface in interfaces {
  258. for ip in interface.ipAddresses {
  259. if ip.isIpV6Address {
  260. if ip.ipAddress != "::1" && ip.ipAddress != "0:0:0:0:0:0:0:1" {
  261. ipv6.append(ip.ipAddress)
  262. }
  263. } else {
  264. if ip.ipAddress != "127.0.0.1" {
  265. ipv4.append(ip.ipAddress)
  266. }
  267. }
  268. }
  269. }
  270. return ipv4 + ipv6
  271. }
  272. }
  273. }
  274. }
  275. // MARK: - Errors
  276. extension UTMScriptingVirtualMachineImpl {
  277. enum ScriptingError: Error, LocalizedError {
  278. case operationNotAvailable
  279. case operationNotSupported
  280. case notRunning
  281. case notStopped
  282. case guestAgentNotRunning
  283. case invalidParameter
  284. var errorDescription: String? {
  285. switch self {
  286. case .operationNotAvailable: return NSLocalizedString("Operation not available.", comment: "UTMScriptingVirtualMachineImpl")
  287. case .operationNotSupported: return NSLocalizedString("Operation not supported by the backend.", comment: "UTMScriptingVirtualMachineImpl")
  288. case .notRunning: return NSLocalizedString("The virtual machine is not running.", comment: "UTMScriptingVirtualMachineImpl")
  289. case .notStopped: return NSLocalizedString("The virtual machine must be stopped before this operation can be performed.", comment: "UTMScriptingVirtualMachineImpl")
  290. case .guestAgentNotRunning: return NSLocalizedString("The QEMU guest agent is not running or not installed on the guest.", comment: "UTMScriptingVirtualMachineImpl")
  291. case .invalidParameter: return NSLocalizedString("One or more required parameters are missing or invalid.", comment: "UTMScriptingVirtualMachineImpl")
  292. }
  293. }
  294. }
  295. }