From afbc2e07647affd4b1341d8891e5ceb70d276bfa Mon Sep 17 00:00:00 2001 From: Nikolay Edigaryev Date: Thu, 22 Sep 2022 18:24:14 +0400 Subject: [PATCH] tart ip: keep waiting for the /var/db/dhcpd_leases file to appear (#254) --- Sources/tart/Commands/IP.swift | 4 ++-- Sources/tart/MACAddressResolver/Leases.swift | 15 +++++++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Sources/tart/Commands/IP.swift b/Sources/tart/Commands/IP.swift index 23ffa54..7e5f234 100644 --- a/Sources/tart/Commands/IP.swift +++ b/Sources/tart/Commands/IP.swift @@ -44,10 +44,10 @@ struct IP: AsyncParsableCommand { let waitUntil = Calendar.current.date(byAdding: .second, value: Int(secondsToWait), to: Date.now)! repeat { - if let ip = try Leases().resolveMACAddress(macAddress: vmMACAddress) { + if let leases = try Leases(), let ip = try leases.resolveMACAddress(macAddress: vmMACAddress) { return ip } - + // wait a second try await Task.sleep(nanoseconds: 1_000_000_000) } while Date.now < waitUntil diff --git a/Sources/tart/MACAddressResolver/Leases.swift b/Sources/tart/MACAddressResolver/Leases.swift index 1ae5cfc..477fabb 100644 --- a/Sources/tart/MACAddressResolver/Leases.swift +++ b/Sources/tart/MACAddressResolver/Leases.swift @@ -19,14 +19,21 @@ enum LeasesError: Error { class Leases { private let leases: [MACAddress : Lease] - convenience init() throws { + convenience init?() throws { try self.init(URL(fileURLWithPath: "/var/db/dhcpd_leases")) } - convenience init(_ fromURL: URL) throws { - let fileContents = try String(contentsOf: fromURL, encoding: .utf8) + convenience init?(_ fromURL: URL) throws { + do { + let urlContents = try String(contentsOf: fromURL, encoding: .utf8) + try self.init(urlContents) + } catch { + if error.isFileNotFound() { + return nil + } - try self.init(fileContents) + throw error + } } init(_ fromString: String) throws {