Files
VirtualBuddy/VirtualCore/Source/Virtualization/ExternalVirtualMachineStore.swift

207 lines
8.0 KiB
Swift

import Foundation
import OSLog
import BuddyFoundation
/// Remembers virtual machines that are shown in the library but stored outside the library directory,
/// such as those opened from an external volume.
final class ExternalVirtualMachineStore {
/// Points to a virtual machine bundle stored outside the library directory.
struct Reference: Codable, Hashable {
/// Where the bundle was last seen. Used when the bookmark can't be resolved.
var path: String
/// Where the volume containing the bundle was mounted when the bundle was last seen.
/// Tells a bundle that's on a volume that isn't mounted apart from one that no longer exists.
var volumePath: String?
/// Follows the bundle when it's renamed or moved.
var bookmark: Data?
init(bundleURL: URL) {
self.path = ExternalVirtualMachineStore.canonicalPath(for: bundleURL)
self.volumePath = (try? bundleURL.resourceValues(forKeys: [.volumeURLKey]))?.volume?.path
self.bookmark = try? bundleURL.bookmarkData()
}
}
static let defaultsKey: String = {
#if DEBUG
ProcessInfo.isSwiftUIPreview ? "externalVirtualMachines-preview" : "externalVirtualMachines"
#else
"externalVirtualMachines"
#endif
}()
private let logger = Logger(for: ExternalVirtualMachineStore.self)
private let defaults: UserDefaults
private(set) var references: [Reference] {
didSet {
guard references != oldValue else { return }
write()
}
}
init(defaults: UserDefaults) {
self.defaults = defaults
self.references = Self.read(from: defaults)
}
/// `true` if the bundle is stored directly inside the library directory, which is where the library looks for virtual machines.
static func isBundle(at bundleURL: URL, inLibraryAt libraryURL: URL) -> Bool {
bundleURL.standardizedFileURL.deletingLastPathComponent().path == libraryURL.standardizedFileURL.path
}
/// The path used to tell bundles apart, which is the same no matter which symbolic links were followed to reach the bundle.
static func canonicalPath(for bundleURL: URL) -> String {
bundleURL.standardizedFileURL.resolvingSymlinksInPath().path
}
func contains(_ bundleURL: URL) -> Bool {
let path = Self.canonicalPath(for: bundleURL)
return references.contains { $0.path == path }
}
func add(_ bundleURL: URL) {
let reference = Reference(bundleURL: bundleURL)
if let index = references.firstIndex(where: { $0.path == reference.path }) {
references[index] = reference
} else {
references.append(reference)
}
}
func remove(_ bundleURL: URL) {
let path = Self.canonicalPath(for: bundleURL)
references.removeAll { $0.path == path }
}
/// Whether any of the virtual machines were last seen in the volume mounted at the specified location.
func hasReferences(inVolumeAt volumeURL: URL) -> Bool {
let volumePath = volumeURL.standardizedFileURL.path
let prefix = volumePath.hasSuffix("/") ? volumePath : volumePath + "/"
return references.contains { $0.volumePath == volumePath || $0.path.hasPrefix(prefix) }
}
/// Locations of the bundles that can currently be reached.
///
/// Bundles that were renamed or moved are followed to their new location.
/// Those that are now in the library directory or in the trash, or that no longer exist, are forgotten.
/// Those in a volume that isn't mounted are left out, but remembered so that they come back once it's mounted.
func resolveAvailableBundleURLs(excludingContentsOf libraryURL: URL) -> [URL] {
let libraryURL = libraryURL.resolvingSymlinksInPath()
var resolvedReferences = [Reference]()
var availableURLs = [URL]()
for reference in references {
guard let bundleURL = locateBundle(for: reference) else {
if isVolumeMounted(for: reference) {
logger.notice("Forgetting external virtual machine that no longer exists at \(reference.path.quoted)")
} else {
resolvedReferences.append(reference)
}
continue
}
guard !Self.isBundle(at: bundleURL, inLibraryAt: libraryURL) else {
logger.notice("Forgetting external virtual machine that's now in the library directory: \(bundleURL.lastPathComponent.quoted)")
continue
}
guard !bundleURL.isInTrash else {
logger.notice("Forgetting external virtual machine that's now in the trash: \(bundleURL.lastPathComponent.quoted)")
continue
}
/// A bundle can be referenced twice if it's moved to where another one that no longer exists used to be.
guard !availableURLs.contains(where: { $0.path == bundleURL.path }) else { continue }
/// The bookmark is only created again when the bundle has moved, since a bookmark that was just resolved is still good.
let isCurrent = reference.path == bundleURL.path && reference.bookmark != nil
resolvedReferences.append(isCurrent ? reference : Reference(bundleURL: bundleURL))
availableURLs.append(bundleURL)
}
references = resolvedReferences
return availableURLs
}
}
// MARK: - Resolution
private extension ExternalVirtualMachineStore {
/// The current location of the bundle, or `nil` if it can't be reached.
func locateBundle(for reference: Reference) -> URL? {
if let bookmark = reference.bookmark {
var isStale = false
/// Resolving must never prompt the user or attempt to mount a volume, as it happens whenever the library is loaded.
if let url = try? URL(resolvingBookmarkData: bookmark, options: [.withoutUI, .withoutMounting], bookmarkDataIsStale: &isStale),
url.isReadableDirectory
{
return URL(fileURLWithPath: Self.canonicalPath(for: url), isDirectory: true)
}
}
let lastKnownURL = URL(fileURLWithPath: reference.path, isDirectory: true)
return lastKnownURL.isReadableDirectory ? lastKnownURL : nil
}
/// `false` when it can't be determined, so that a virtual machine is never forgotten just because its volume is not mounted.
func isVolumeMounted(for reference: Reference) -> Bool {
guard let volumePath = reference.volumePath else { return false }
let volumeURL = URL(fileURLWithPath: volumePath, isDirectory: true)
/// An empty directory can be left behind where a volume used to be mounted, so check that a volume is really mounted there.
guard let mountedVolumeURL = (try? volumeURL.resourceValues(forKeys: [.volumeURLKey]))?.volume else { return false }
return mountedVolumeURL.standardizedFileURL.path == volumeURL.standardizedFileURL.path
}
}
private extension URL {
var isInTrash: Bool {
var relationship = FileManager.URLRelationship.other
do {
try FileManager.default.getRelationship(&relationship, of: .trashDirectory, in: [], toItemAt: self)
} catch {
return false
}
return relationship == .contains
}
}
// MARK: - Persistence
private extension ExternalVirtualMachineStore {
static func read(from defaults: UserDefaults) -> [Reference] {
guard let data = defaults.data(forKey: defaultsKey) else { return [] }
do {
return try PropertyListDecoder().decode([Reference].self, from: data)
} catch {
Logger(for: ExternalVirtualMachineStore.self).error("Failed to read external virtual machines: \(error, privacy: .public)")
return []
}
}
func write() {
do {
defaults.set(try PropertyListEncoder().encode(references), forKey: Self.defaultsKey)
} catch {
logger.error("Failed to save external virtual machines: \(error, privacy: .public)")
}
}
}