448 lines
20 KiB
Swift
448 lines
20 KiB
Swift
import AppKit
|
|
import Foundation
|
|
|
|
struct ServerDefinition: Identifiable, Codable, Hashable {
|
|
var id = UUID()
|
|
var name: String
|
|
var vmName: String
|
|
var vmUUID: String? = nil
|
|
var host: String
|
|
var sshUser: String
|
|
var sshPort: Int = 22
|
|
var sshIdentityFile: String = ""
|
|
var mailpitPort: Int?
|
|
var customIconPath: String? = nil
|
|
|
|
static let orion = ServerDefinition(name: "Orion", vmName: "Ubuntu Linux Server", host: "10.211.55.100", sshUser: "sysadmin", sshPort: 22, sshIdentityFile: "", mailpitPort: 8025)
|
|
}
|
|
|
|
|
|
struct ParallelsVM: Identifiable, Hashable {
|
|
let id: String
|
|
let name: String
|
|
let status: String
|
|
let ipAddress: String
|
|
let operatingSystem: String
|
|
var bundlePath: String?
|
|
|
|
var symbol: String {
|
|
switch operatingSystem {
|
|
case "Windows": return "desktopcomputer"
|
|
case "Ubuntu": return "server.rack"
|
|
case "Debian": return "server.rack"
|
|
case "Fedora": return "server.rack"
|
|
case "CentOS": return "server.rack"
|
|
case "Alpine": return "server.rack"
|
|
case "Oracle Linux": return "server.rack"
|
|
default: return "desktopcomputer"
|
|
}
|
|
}
|
|
|
|
static func detectOS(_ name: String) -> String {
|
|
let value = name.lowercased()
|
|
|
|
if value.contains("windows") { return "Windows" }
|
|
if value.contains("ubuntu") { return "Ubuntu" }
|
|
if value.contains("debian") { return "Debian" }
|
|
if value.contains("fedora") { return "Fedora" }
|
|
if value.contains("centos") { return "CentOS" }
|
|
if value.contains("alpine") { return "Alpine" }
|
|
if value.contains("oracle") { return "Oracle Linux" }
|
|
if value.contains("rocky") { return "Rocky Linux" }
|
|
if value.contains("alma") { return "AlmaLinux" }
|
|
if value.contains("arch") { return "Arch Linux" }
|
|
if value.contains("gentoo") { return "Gentoo" }
|
|
if value.contains("freebsd") { return "FreeBSD" }
|
|
|
|
return "Other"
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
final class OrionVMController: ObservableObject {
|
|
enum VMStatus: Equatable {
|
|
case checking, running, stopped, suspended, transitioning, unavailable(String)
|
|
var title: String { switch self { case .checking: "Checking…"; case .running: "Running"; case .stopped: "Stopped"; case .suspended: "Suspended"; case .transitioning: "Working…"; case .unavailable: "Unavailable" } }
|
|
var symbolName: String { switch self { case .running: "server.rack"; case .stopped: "power"; case .suspended: "pause.circle"; case .transitioning, .checking: "arrow.triangle.2.circlepath"; case .unavailable: "exclamationmark.triangle" } }
|
|
}
|
|
|
|
@Published var servers: [ServerDefinition] { didSet { saveServers() } }
|
|
@Published var statuses: [UUID: VMStatus] = [:]
|
|
@Published var busyServers: Set<UUID> = []
|
|
@Published var lastError: String?
|
|
@Published var discoveredVMs: [ParallelsVM] = []
|
|
@Published var selectedVMIDs: Set<String> = []
|
|
@Published var discovering = false
|
|
@Published var busyVMIDs: Set<String> = []
|
|
private var timer: Timer?
|
|
private let defaultsKey = "serverDefinitions.v2"
|
|
private let vmOrderKey = "orionVMOrder.v1"
|
|
private var vmOrder: [String] {
|
|
get { UserDefaults.standard.stringArray(forKey: vmOrderKey) ?? [] }
|
|
set { UserDefaults.standard.set(newValue, forKey: vmOrderKey) }
|
|
}
|
|
|
|
func reorderVM(draggedID: String, onto targetID: String) {
|
|
guard draggedID != targetID,
|
|
discoveredVMs.contains(where: { $0.id == draggedID }),
|
|
discoveredVMs.contains(where: { $0.id == targetID }) else { return }
|
|
var order = discoveredVMs.map(\.id)
|
|
guard let from = order.firstIndex(of: draggedID),
|
|
let to = order.firstIndex(of: targetID) else { return }
|
|
order.remove(at: from)
|
|
order.insert(draggedID, at: to)
|
|
vmOrder = order
|
|
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
|
|
discoveredVMs.sort { (ranks[$0.id] ?? Int.max) < (ranks[$1.id] ?? Int.max) }
|
|
}
|
|
|
|
|
|
init() {
|
|
if let data = UserDefaults.standard.data(forKey: defaultsKey), let saved = try? JSONDecoder().decode([ServerDefinition].self, from: data) { servers = saved }
|
|
else { servers = [.orion] }
|
|
Task {
|
|
await discoverVMs()
|
|
await refreshAll()
|
|
}
|
|
timer = Timer.scheduledTimer(withTimeInterval: 15, repeats: true) { [weak self] _ in Task { @MainActor in guard let self else { return }; await self.discoverVMs(); await self.refreshAll() } }
|
|
}
|
|
deinit { timer?.invalidate() }
|
|
|
|
|
|
func discoverVMs() async {
|
|
guard !discovering else { return }
|
|
|
|
discovering = true
|
|
defer { discovering = false }
|
|
|
|
do {
|
|
let output = try await runPrlctl(["list", "-a", "-j"])
|
|
|
|
guard let data = output.data(using: .utf8),
|
|
let records = try JSONSerialization.jsonObject(
|
|
with: data
|
|
) as? [[String: Any]] else {
|
|
throw OrionError.commandFailed(
|
|
"Invalid Parallels VM discovery response."
|
|
)
|
|
}
|
|
|
|
let knownBundlePaths = Dictionary(uniqueKeysWithValues:
|
|
discoveredVMs.compactMap { machine -> (String, String)? in
|
|
guard let path = machine.bundlePath else { return nil }
|
|
return (machine.id, path)
|
|
}
|
|
)
|
|
discoveredVMs = records.compactMap { record in
|
|
guard let uuid = record["uuid"] as? String,
|
|
let name = record["name"] as? String else {
|
|
return nil
|
|
}
|
|
|
|
let status = record["status"] as? String ?? "unknown"
|
|
let ip = record["ip_configured"] as? String ?? ""
|
|
|
|
return ParallelsVM(
|
|
id: uuid,
|
|
name: name,
|
|
status: status,
|
|
ipAddress: ip == "-" ? "" : ip,
|
|
operatingSystem: ParallelsVM.detectOS(name),
|
|
bundlePath: knownBundlePaths[uuid]
|
|
)
|
|
}
|
|
.sorted {
|
|
$0.name.localizedStandardCompare($1.name)
|
|
== .orderedAscending
|
|
}
|
|
|
|
// Keep the user's VM order through every 15-second discovery refresh.
|
|
// New VMs are appended in discovery order.
|
|
let savedOrder = vmOrder
|
|
let ranks = Dictionary(uniqueKeysWithValues: savedOrder.enumerated().map { ($0.element, $0.offset) })
|
|
discoveredVMs.sort { left, right in
|
|
let a = ranks[left.id] ?? Int.max
|
|
let b = ranks[right.id] ?? Int.max
|
|
if a != b { return a < b }
|
|
return left.name.localizedStandardCompare(right.name) == .orderedAscending
|
|
}
|
|
|
|
// Resolve Parallels VM bundles without requiring the guest to run.
|
|
for i in discoveredVMs.indices where discoveredVMs[i].bundlePath == nil {
|
|
if let detail = try? await runPrlctl(["list", "-i", discoveredVMs[i].id]) {
|
|
// `Home:` ends with .pvm/ on this Parallels installation.
|
|
if let homeLine = detail.split(separator: "\n").first(where: {
|
|
$0.trimmingCharacters(in: .whitespaces).hasPrefix("Home:")
|
|
}) {
|
|
let trimmed = homeLine.trimmingCharacters(in: .whitespaces)
|
|
let raw = String(trimmed.dropFirst("Home:".count))
|
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
|
|
let expanded = (raw as NSString).expandingTildeInPath
|
|
let normalized = (expanded as NSString).standardizingPath
|
|
if FileManager.default.fileExists(atPath: normalized) {
|
|
discoveredVMs[i].bundlePath = normalized
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Keep selections only for VMs still present.
|
|
let available = Set(discoveredVMs.map(\.id))
|
|
selectedVMIDs.formIntersection(available)
|
|
|
|
// Associate existing configurations with discovered VMs.
|
|
// This preserves the original Orion configuration.
|
|
for machine in discoveredVMs {
|
|
guard let index = servers.firstIndex(where: {
|
|
$0.vmUUID == machine.id ||
|
|
($0.vmUUID == nil && $0.vmName == machine.name)
|
|
}) else {
|
|
continue
|
|
}
|
|
|
|
if servers[index].vmUUID == nil {
|
|
servers[index].vmUUID = machine.id
|
|
}
|
|
}
|
|
|
|
} catch {
|
|
lastError = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func isIntegrated(_ machine: ParallelsVM) -> Bool {
|
|
servers.contains {
|
|
$0.vmUUID == machine.id ||
|
|
($0.vmUUID == nil && $0.vmName == machine.name)
|
|
}
|
|
}
|
|
|
|
func toggleSelection(_ machine: ParallelsVM) {
|
|
if selectedVMIDs.contains(machine.id) {
|
|
selectedVMIDs.remove(machine.id)
|
|
} else {
|
|
selectedVMIDs.insert(machine.id)
|
|
}
|
|
}
|
|
|
|
func selectAllVMs() {
|
|
selectedVMIDs = Set(discoveredVMs.map(\.id))
|
|
}
|
|
|
|
func clearVMSelection() {
|
|
selectedVMIDs.removeAll()
|
|
}
|
|
|
|
func integrateSelectedVMs() {
|
|
let selected = discoveredVMs.filter {
|
|
selectedVMIDs.contains($0.id)
|
|
}
|
|
|
|
for machine in selected {
|
|
guard !isIntegrated(machine) else { continue }
|
|
|
|
let server = ServerDefinition(
|
|
name: machine.name,
|
|
vmName: machine.name,
|
|
vmUUID: machine.id,
|
|
host: machine.ipAddress,
|
|
sshUser: "sysadmin",
|
|
sshPort: 22,
|
|
sshIdentityFile: "",
|
|
mailpitPort: nil
|
|
)
|
|
|
|
add(server)
|
|
}
|
|
|
|
selectedVMIDs.removeAll()
|
|
}
|
|
|
|
func icon(for machine: ParallelsVM) -> NSImage? {
|
|
guard let path = machine.bundlePath,
|
|
FileManager.default.fileExists(atPath: path) else { return nil }
|
|
let bundle = URL(fileURLWithPath: path, isDirectory: true)
|
|
|
|
// Parallels stores the per-VM application under <VM>.pvm/VM.app.
|
|
// The .pvm Finder icon itself is generic and must not be used.
|
|
let app = bundle.appendingPathComponent("VM.app", isDirectory: true)
|
|
let plist = app.appendingPathComponent("Contents/Info.plist")
|
|
if let info = NSDictionary(contentsOf: plist) as? [String: Any] {
|
|
let resourceDir = app.appendingPathComponent("Contents/Resources", isDirectory: true)
|
|
for key in ["CFBundleIconFile", "CFBundleIconName"] {
|
|
if let name = info[key] as? String, !name.isEmpty {
|
|
let names = name.lowercased().hasSuffix(".icns") ? [name] : [name + ".icns", name]
|
|
for candidate in names {
|
|
if let image = NSImage(contentsOf: resourceDir.appendingPathComponent(candidate)) {
|
|
return image
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for name in ["icon.png", "Icon.png", "icon.icns", "Icon.icns", ".VolumeIcon.icns"] {
|
|
if let image = NSImage(contentsOf: bundle.appendingPathComponent(name)) { return image }
|
|
}
|
|
// Never return NSWorkspace.icon(forFile: path): it is the generic .pvm icon.
|
|
return nil
|
|
}
|
|
|
|
func status(for server: ServerDefinition) -> VMStatus { statuses[server.id] ?? .checking }
|
|
func isBusy(_ server: ServerDefinition) -> Bool { busyServers.contains(server.id) }
|
|
func add(_ server: ServerDefinition) { servers.append(server); Task { await refreshStatus(server) } }
|
|
func update(_ server: ServerDefinition) { if let i = servers.firstIndex(where: { $0.id == server.id }) { servers[i] = server; Task { await refreshStatus(server) } } }
|
|
func delete(at offsets: IndexSet) { for i in offsets { statuses[servers[i].id] = nil }; servers.remove(atOffsets: offsets) }
|
|
|
|
func refreshAll() async {
|
|
for server in servers { await refreshStatus(server) }
|
|
}
|
|
|
|
func refreshStatus(_ server: ServerDefinition) async {
|
|
guard !isBusy(server) else { return }
|
|
guard let machine = discoveredVMs.first(where: {
|
|
$0.id == server.vmUUID || $0.name == server.vmName
|
|
}) else {
|
|
statuses[server.id] = .unavailable("VM not found in Parallels")
|
|
return
|
|
}
|
|
switch machine.status.lowercased() {
|
|
case "running": statuses[server.id] = .running
|
|
case "stopped": statuses[server.id] = .stopped
|
|
case "suspended", "paused": statuses[server.id] = .suspended
|
|
default: statuses[server.id] = .unavailable(machine.status)
|
|
}
|
|
}
|
|
|
|
func removeDefinition(_ server: ServerDefinition) {
|
|
servers.removeAll { $0.id == server.id }
|
|
statuses.removeValue(forKey: server.id)
|
|
busyServers.remove(server.id)
|
|
}
|
|
|
|
var runningVMs: [ParallelsVM] {
|
|
discoveredVMs.filter { $0.status.lowercased() == "running" }
|
|
}
|
|
|
|
func start(_ s: ServerDefinition) { perform(["start", s.vmUUID ?? s.vmName], server: s) }
|
|
func stop(_ s: ServerDefinition) { perform(["stop", s.vmUUID ?? s.vmName], server: s) }
|
|
func restart(_ s: ServerDefinition) { perform(["restart", s.vmUUID ?? s.vmName], server: s) }
|
|
func forceStop(_ s: ServerDefinition) { perform(["stop", s.vmUUID ?? s.vmName, "--kill"], server: s) }
|
|
|
|
private func perform(_ arguments: [String], server: ServerDefinition) {
|
|
guard !isBusy(server) else { return }; busyServers.insert(server.id); statuses[server.id] = .transitioning; lastError = nil
|
|
Task { do { _ = try await runPrlctl(arguments) } catch { lastError = error.localizedDescription }; busyServers.remove(server.id); try? await Task.sleep(for: .seconds(1)); await refreshStatus(server) }
|
|
}
|
|
|
|
func operate(_ machine: ParallelsVM, action: String) {
|
|
guard !busyVMIDs.contains(machine.id) else { return }
|
|
busyVMIDs.insert(machine.id)
|
|
lastError = nil
|
|
Task {
|
|
let arguments = action == "force-stop"
|
|
? ["stop", machine.id, "--kill"]
|
|
: [action, machine.id]
|
|
do { _ = try await runPrlctl(arguments) }
|
|
catch { lastError = error.localizedDescription }
|
|
busyVMIDs.remove(machine.id)
|
|
await discoverVMs()
|
|
await refreshAll()
|
|
}
|
|
}
|
|
|
|
func integrate(_ machine: ParallelsVM) {
|
|
guard !isIntegrated(machine) else { return }
|
|
add(ServerDefinition(name: machine.name, vmName: machine.name,
|
|
vmUUID: machine.id, host: machine.ipAddress, sshUser: "",
|
|
sshPort: 22, sshIdentityFile: "", mailpitPort: nil))
|
|
}
|
|
|
|
func moveServer(from source: IndexSet, to destination: Int) {
|
|
servers.move(fromOffsets: source, toOffset: destination)
|
|
}
|
|
|
|
func moveServer(_ id: UUID, by delta: Int) {
|
|
guard let index = servers.firstIndex(where: { $0.id == id }) else { return }
|
|
let target = index + delta
|
|
guard servers.indices.contains(target) else { return }
|
|
servers.swapAt(index, target)
|
|
}
|
|
|
|
func reorderServer(draggedID: UUID, onto targetID: UUID) {
|
|
guard draggedID != targetID,
|
|
let from = servers.firstIndex(where: { $0.id == draggedID }),
|
|
let to = servers.firstIndex(where: { $0.id == targetID }) else { return }
|
|
let moved = servers.remove(at: from)
|
|
servers.insert(moved, at: to) // @Published didSet persists the order.
|
|
}
|
|
|
|
func icon(for server: ServerDefinition) -> NSImage? {
|
|
if let path = server.customIconPath, let image = NSImage(contentsOfFile: path) {
|
|
return image
|
|
}
|
|
|
|
guard let machine = discoveredVMs.first(where: {
|
|
$0.id == server.vmUUID || $0.name == server.vmName
|
|
}) else { return nil }
|
|
return icon(for: machine)
|
|
}
|
|
|
|
func openSSH(_ s: ServerDefinition) {
|
|
let userHost = "\(s.sshUser)@\(s.host)"
|
|
var command = "/usr/bin/ssh -p \(s.sshPort)"
|
|
let identity = s.sshIdentityFile.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
if !identity.isEmpty {
|
|
command += " -i \(shellQuote((identity as NSString).expandingTildeInPath))"
|
|
}
|
|
command += " \(shellQuote(userHost))"
|
|
|
|
do {
|
|
// Terminal reliably opens executable .command files without requiring
|
|
// Apple Events/Automation permission from this menu-bar application.
|
|
let directory = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("OrionToolbar", isDirectory: true)
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
|
|
let safeName = s.name.replacingOccurrences(of: "/", with: "-")
|
|
let scriptURL = directory.appendingPathComponent("SSH-\(safeName).command")
|
|
let script = """
|
|
#!/bin/zsh
|
|
clear
|
|
echo "Connecting to \(s.name) (\(userHost))..."
|
|
exec \(command)
|
|
"""
|
|
try script.write(to: scriptURL, atomically: true, encoding: .utf8)
|
|
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: scriptURL.path)
|
|
|
|
guard let terminalURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") else {
|
|
lastError = "Terminal.app could not be found."
|
|
return
|
|
}
|
|
|
|
let configuration = NSWorkspace.OpenConfiguration()
|
|
configuration.activates = true
|
|
NSWorkspace.shared.open([scriptURL], withApplicationAt: terminalURL, configuration: configuration) { _, error in
|
|
Task { @MainActor in
|
|
if let error { self.lastError = "Could not open Terminal: \(error.localizedDescription)" }
|
|
}
|
|
}
|
|
} catch {
|
|
lastError = "Could not create SSH launcher: \(error.localizedDescription)"
|
|
}
|
|
}
|
|
|
|
private func shellQuote(_ value: String) -> String {
|
|
"'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
|
|
}
|
|
func openMailpit(_ s: ServerDefinition) { if let p = s.mailpitPort, let url = URL(string: "http://\(s.host):\(p)") { NSWorkspace.shared.open(url) } }
|
|
func openParallels() { NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: "/Applications/Parallels Desktop.app"), configuration: .init()) }
|
|
|
|
private func saveServers() { if let data = try? JSONEncoder().encode(servers) { UserDefaults.standard.set(data, forKey: defaultsKey) } }
|
|
private func prlctlURL() -> URL? { ["/usr/local/bin/prlctl", "/Applications/Parallels Desktop.app/Contents/MacOS/prlctl"].map(URL.init(fileURLWithPath:)).first { FileManager.default.isExecutableFile(atPath: $0.path) } }
|
|
private func runPrlctl(_ arguments: [String]) async throws -> String {
|
|
guard let executable = prlctlURL() else { throw OrionError.prlctlNotFound }
|
|
return try await Task.detached(priority: .userInitiated) { let p = Process(); let pipe = Pipe(); p.executableURL = executable; p.arguments = arguments; p.standardOutput = pipe; p.standardError = pipe; try p.run(); let data = pipe.fileHandleForReading.readDataToEndOfFile(); p.waitUntilExit(); let out = String(decoding: data, as: UTF8.self); guard p.terminationStatus == 0 else { throw OrionError.commandFailed(out) }; return out }.value
|
|
}
|
|
}
|
|
|
|
enum OrionError: LocalizedError { case prlctlNotFound, commandFailed(String); var errorDescription: String? { switch self { case .prlctlNotFound: "Parallels prlctl was not found."; case .commandFailed(let o): o.trimmingCharacters(in: .whitespacesAndNewlines) } } }
|