UTMScriptingVirtualMachineImpl.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. override var objectSpecifier: NSScriptObjectSpecifier? {
  81. let appDescription = NSApplication.classDescription() as! NSScriptClassDescription
  82. return NSUniqueIDSpecifier(containerClassDescription: appDescription,
  83. containerSpecifier: nil,
  84. key: "scriptingVirtualMachines",
  85. uniqueID: id)
  86. }
  87. init(for vm: VMData, data: UTMData) {
  88. self.box = vm
  89. self.data = data
  90. }
  91. @objc func start(_ command: NSScriptCommand) {
  92. let shouldSaveState = command.evaluatedArguments?["saveFlag"] as? Bool ?? true
  93. withScriptCommand(command) { [self] in
  94. if !shouldSaveState {
  95. guard type(of: vm).capabilities.supportsDisposibleMode else {
  96. throw ScriptingError.operationNotSupported
  97. }
  98. }
  99. data.run(vm: box, startImmediately: false)
  100. if vm.state == .stopped {
  101. try await vm.start(options: shouldSaveState ? [] : .bootDisposibleMode)
  102. } else if vm.state == .paused {
  103. try await vm.resume()
  104. } else {
  105. throw ScriptingError.operationNotAvailable
  106. }
  107. }
  108. }
  109. @objc func suspend(_ command: NSScriptCommand) {
  110. let shouldSaveState = command.evaluatedArguments?["saveFlag"] as? Bool ?? false
  111. withScriptCommand(command) { [self] in
  112. guard vm.state == .started else {
  113. throw ScriptingError.notRunning
  114. }
  115. try await vm.pause()
  116. if shouldSaveState {
  117. try await vm.saveSnapshot(name: nil)
  118. }
  119. }
  120. }
  121. @objc func stop(_ command: NSScriptCommand) {
  122. let stopMethod: UTMScriptingStopMethod
  123. if let stopMethodValue = command.evaluatedArguments?["stopBy"] as? AEKeyword {
  124. stopMethod = UTMScriptingStopMethod(rawValue: stopMethodValue) ?? .force
  125. } else {
  126. stopMethod = .force
  127. }
  128. withScriptCommand(command) { [self] in
  129. guard vm.state == .started || stopMethod == .kill else {
  130. throw ScriptingError.notRunning
  131. }
  132. switch stopMethod {
  133. case .force:
  134. try await vm.stop(usingMethod: .force)
  135. case .kill:
  136. try await vm.stop(usingMethod: .kill)
  137. case .request:
  138. try await vm.stop(usingMethod: .request)
  139. }
  140. }
  141. }
  142. @objc func delete(_ command: NSDeleteCommand) {
  143. withScriptCommand(command) { [self] in
  144. guard vm.state == .stopped else {
  145. throw ScriptingError.notStopped
  146. }
  147. try await data.delete(vm: box, alsoRegistry: true)
  148. }
  149. }
  150. @objc func clone(_ command: NSCloneCommand) {
  151. let properties = command.evaluatedArguments?["WithProperties"] as? [AnyHashable : Any]
  152. withScriptCommand(command) { [self] in
  153. guard vm.state == .stopped else {
  154. throw ScriptingError.notStopped
  155. }
  156. let newVM = try await data.clone(vm: box)
  157. if let properties = properties, let newConfiguration = properties["configuration"] as? [AnyHashable : Any] {
  158. let wrapper = UTMScriptingConfigImpl(newVM.config!)
  159. try wrapper.updateConfiguration(from: newConfiguration)
  160. try await data.save(vm: newVM)
  161. }
  162. }
  163. }
  164. @objc func export(_ command: NSCloneCommand) {
  165. let exportUrl = command.evaluatedArguments?["file"] as? URL
  166. withScriptCommand(command) { [self] in
  167. guard vm.state == .stopped else {
  168. throw ScriptingError.notStopped
  169. }
  170. try await data.export(vm: box, to: exportUrl!)
  171. }
  172. }
  173. }
  174. // MARK: - Guest agent suite
  175. @objc extension UTMScriptingVirtualMachineImpl {
  176. @nonobjc private func withGuestAgent<Result>(_ block: (QEMUGuestAgent) async throws -> Result) async throws -> Result {
  177. guard vm.state == .started else {
  178. throw ScriptingError.notRunning
  179. }
  180. guard let vm = vm as? UTMQemuVirtualMachine else {
  181. throw ScriptingError.operationNotSupported
  182. }
  183. guard let guestAgent = await vm.guestAgent else {
  184. throw ScriptingError.guestAgentNotRunning
  185. }
  186. return try await block(guestAgent)
  187. }
  188. @objc func valueInOpenFilesWithUniqueID(_ id: Int) -> UTMScriptingGuestFileImpl {
  189. UTMScriptingGuestFileImpl(from: id, parent: self)
  190. }
  191. @objc func openFile(_ command: NSScriptCommand) {
  192. let path = command.evaluatedArguments?["path"] as? String
  193. let mode = command.evaluatedArguments?["mode"] as? AEKeyword
  194. let isUpdate = command.evaluatedArguments?["isUpdate"] as? Bool ?? false
  195. withScriptCommand(command) { [self] in
  196. guard let path = path else {
  197. throw ScriptingError.invalidParameter
  198. }
  199. let modeValue: String
  200. if let mode = mode {
  201. switch UTMScriptingOpenMode(rawValue: mode) {
  202. case .reading: modeValue = "r"
  203. case .writing: modeValue = "w"
  204. case .appending: modeValue = "a"
  205. default: modeValue = "r"
  206. }
  207. } else {
  208. modeValue = "r"
  209. }
  210. return try await withGuestAgent { guestAgent in
  211. let handle = try await guestAgent.guestFileOpen(path, mode: modeValue + (isUpdate ? "+" : ""))
  212. return UTMScriptingGuestFileImpl(from: handle, parent: self)
  213. }
  214. }
  215. }
  216. @objc func valueInProcessesWithUniqueID(_ id: Int) -> UTMScriptingGuestProcessImpl {
  217. UTMScriptingGuestProcessImpl(from: id, parent: self)
  218. }
  219. @objc func execute(_ command: NSScriptCommand) {
  220. let path = command.evaluatedArguments?["path"] as? String
  221. let argv = command.evaluatedArguments?["argv"] as? [String]
  222. let envp = command.evaluatedArguments?["envp"] as? [String]
  223. let input = command.evaluatedArguments?["input"] as? String
  224. let isBase64Encoded = command.evaluatedArguments?["isBase64Encoded"] as? Bool ?? false
  225. let isCaptureOutput = command.evaluatedArguments?["isCaptureOutput"] as? Bool ?? false
  226. let inputData = dataFromText(input, isBase64Encoded: isBase64Encoded)
  227. withScriptCommand(command) { [self] in
  228. guard let path = path else {
  229. throw ScriptingError.invalidParameter
  230. }
  231. return try await withGuestAgent { guestAgent in
  232. let pid = try await guestAgent.guestExec(path, argv: argv, envp: envp, input: inputData, captureOutput: isCaptureOutput)
  233. return UTMScriptingGuestProcessImpl(from: pid, parent: self)
  234. }
  235. }
  236. }
  237. @objc func queryIp(_ command: NSScriptCommand) {
  238. withScriptCommand(command) { [self] in
  239. try await withGuestAgent { guestAgent in
  240. let interfaces = try await guestAgent.guestNetworkGetInterfaces()
  241. var ipv4: [String] = []
  242. var ipv6: [String] = []
  243. for interface in interfaces {
  244. for ip in interface.ipAddresses {
  245. if ip.isIpV6Address {
  246. if ip.ipAddress != "::1" && ip.ipAddress != "0:0:0:0:0:0:0:1" {
  247. ipv6.append(ip.ipAddress)
  248. }
  249. } else {
  250. if ip.ipAddress != "127.0.0.1" {
  251. ipv4.append(ip.ipAddress)
  252. }
  253. }
  254. }
  255. }
  256. return ipv4 + ipv6
  257. }
  258. }
  259. }
  260. }
  261. // MARK: - Errors
  262. extension UTMScriptingVirtualMachineImpl {
  263. enum ScriptingError: Error, LocalizedError {
  264. case operationNotAvailable
  265. case operationNotSupported
  266. case notRunning
  267. case notStopped
  268. case guestAgentNotRunning
  269. case invalidParameter
  270. var errorDescription: String? {
  271. switch self {
  272. case .operationNotAvailable: return NSLocalizedString("Operation not available.", comment: "UTMScriptingVirtualMachineImpl")
  273. case .operationNotSupported: return NSLocalizedString("Operation not supported by the backend.", comment: "UTMScriptingVirtualMachineImpl")
  274. case .notRunning: return NSLocalizedString("The virtual machine is not running.", comment: "UTMScriptingVirtualMachineImpl")
  275. case .notStopped: return NSLocalizedString("The virtual machine must be stopped before this operation can be performed.", comment: "UTMScriptingVirtualMachineImpl")
  276. case .guestAgentNotRunning: return NSLocalizedString("The QEMU guest agent is not running or not installed on the guest.", comment: "UTMScriptingVirtualMachineImpl")
  277. case .invalidParameter: return NSLocalizedString("One or more required parameters are missing or invalid.", comment: "UTMScriptingVirtualMachineImpl")
  278. }
  279. }
  280. }
  281. }