Reformat logging system

This commit is contained in:
Mykola Grymalyuk
2023-05-24 12:24:09 -06:00
parent 80ea0cd217
commit d8a79cf67e
30 changed files with 311 additions and 240 deletions

View File

@@ -2,6 +2,7 @@
import wx
import wx.adv
import logging
from resources import constants
@@ -12,6 +13,7 @@ class AboutFrame(wx.Frame):
if wx.FindWindowByName("About"):
return
logging.info("Generating About frame")
super(AboutFrame, self).__init__(None, title="About", size=(350, 350), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
self.constants: constants.Constants = global_constants
self.Centre()

View File

@@ -19,6 +19,7 @@ class BuildFrame(wx.Frame):
Uses a Modal Dialog for smoother transition from other frames
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None) -> None:
logging.info("Initializing Build Frame")
super(BuildFrame, self).__init__(parent, title=title, size=(350, 200), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
gui_support.GenerateMenubar(self, global_constants).generate()
@@ -121,7 +122,7 @@ class BuildFrame(wx.Frame):
try:
build.BuildOpenCore(self.constants.custom_model or self.constants.computer.real_model, self.constants)
except:
logging.error("- An internal error occurred while building:\n")
logging.error("An internal error occurred while building:\n")
logging.error(traceback.format_exc())
logger.removeHandler(logger.handlers[2])

View File

@@ -1,5 +1,6 @@
# Generate UI for downloading files
import wx
import logging
from resources import (
constants,
@@ -13,6 +14,7 @@ class DownloadFrame(wx.Frame):
Update provided frame with download stats
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, download_obj: network_handler.DownloadObject, item_name: str) -> None:
logging.info("Initializing Download Frame")
self.constants: constants.Constants = global_constants
self.title: str = title
self.parent: wx.Frame = parent
@@ -91,6 +93,7 @@ class DownloadFrame(wx.Frame):
Terminate download
"""
if wx.MessageBox("Are you sure you want to cancel the download?", "Cancel Download", wx.YES_NO | wx.ICON_QUESTION | wx.NO_DEFAULT) == wx.YES:
logging.info("User cancelled download")
self.user_cancelled = True
self.download_obj.stop()

View File

@@ -52,7 +52,7 @@ class EntryPoint:
entry = gui_sys_patch.SysPatchFrame
patches = sys_patch_detect.DetectRootPatch(self.constants.computer.real_model, self.constants).detect_patch_set()
logging.info(f"- Loading wxPython GUI: {entry.__name__}")
logging.info(f"Entry point set: {entry.__name__}")
self.frame: wx.Frame = entry(
None,
title=f"{self.constants.patcher_name} ({self.constants.patcher_version})",
@@ -79,7 +79,7 @@ class EntryPoint:
if not self.frame:
return
logging.info("- Cleaning up wxPython GUI")
logging.info("Cleaning up wxPython GUI")
self.frame.SetTransparent(0)
wx.Yield()

View File

@@ -1,5 +1,6 @@
# Generate UI for help menu
import wx
import logging
import webbrowser
from resources import constants
@@ -10,7 +11,7 @@ class HelpFrame(wx.Frame):
Append to main menu through a modal dialog
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None) -> None:
logging.info("Initializing Help Frame")
self.dialog = wx.Dialog(parent, title=title, size=(300, 200))
self.constants: constants.Constants = global_constants

View File

@@ -13,6 +13,7 @@ class InstallOCFrame(wx.Frame):
Create a frame for installing OpenCore to disk
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None):
logging.info("Initializing Install OpenCore Frame")
super(InstallOCFrame, self).__init__(parent, title=title, size=(300, 120), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
gui_support.GenerateMenubar(self, global_constants).generate()
@@ -124,13 +125,14 @@ class InstallOCFrame(wx.Frame):
# disk6s1 -> disk6
disk_root = self.constants.booted_oc_disk.strip("disk")
disk_root = "disk" + disk_root.split("s")[0]
logging.info(f"- Checking if booted disk is present: {disk_root}")
logging.info(f"Checking if booted disk is present: {disk_root}")
# Add buttons for each disk
items = len(self.available_disks)
longest_label = max((len(self.available_disks[disk]['disk']) + len(self.available_disks[disk]['name']) + len(str(self.available_disks[disk]['size']))) for disk in self.available_disks)
longest_label = longest_label * 9
spacer = 0
logging.info("Available disks:")
for disk in self.available_disks:
# Create a button for each disk
logging.info(f"- {self.available_disks[disk]['disk']} - {self.available_disks[disk]['name']} - {self.available_disks[disk]['size']}")
@@ -195,6 +197,7 @@ class InstallOCFrame(wx.Frame):
items = len(partitions)
longest_label = max((len(partitions[partition]['partition']) + len(partitions[partition]['name']) + len(str(partitions[partition]['size']))) for partition in partitions)
longest_label = longest_label * 10
logging.info(f"Available partitions for {disk}:")
for partition in partitions:
logging.info(f"- {partitions[partition]['partition']} - {partitions[partition]['name']} - {partitions[partition]['size']}")
disk_button = wx.Button(dialog, label=f"{partitions[partition]['partition']} - {partitions[partition]['name']} - {partitions[partition]['size']}", size=(longest_label,30), pos=(-1, text_label.GetPosition()[1] + text_label.GetSize()[1] + 5))
@@ -306,14 +309,14 @@ class InstallOCFrame(wx.Frame):
"""
Install OpenCore to disk
"""
logging.info(f"- Installing OpenCore to {partition}")
logging.info(f"Installing OpenCore to {partition}")
logger = logging.getLogger()
logger.addHandler(gui_support.ThreadHandler(self.text_box))
try:
self.result = install.tui_disk_installation(self.constants).install_opencore(partition)
except:
logging.error("- An internal error occurred while installing:\n")
logging.error("An internal error occurred while installing:\n")
logging.error(traceback.format_exc())
logger.removeHandler(logger.handlers[2])

View File

@@ -28,7 +28,7 @@ class macOSInstallerDownloadFrame(wx.Frame):
Note: Flashing installers is passed to gui_macos_installer_flash.py
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None):
logging.info("Initializing macOS Installer Download Frame")
self.constants: constants.Constants = global_constants
self.title: str = title
self.parent: wx.Frame = parent

View File

@@ -22,6 +22,7 @@ from data import os_data
class macOSInstallerFlashFrame(wx.Frame):
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None):
logging.info("Initializing macOS Installer Flash Frame")
super(macOSInstallerFlashFrame, self).__init__(parent, title=title, size=(350, 200), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
gui_support.GenerateMenubar(self, global_constants).generate()
@@ -354,14 +355,14 @@ class macOSInstallerFlashFrame(wx.Frame):
def _flash_installer(self, disk) -> bool:
utilities.disable_sleep_while_running()
logging.info("- Creating macOS installer")
logging.info("Creating macOS installer")
thread = threading.Thread(target=self._auto_package_handler)
thread.start()
# print contents of installer.sh
with open(self.constants.installer_sh_path, "r") as f:
logging.info(f"- installer.sh contents:\n{f.read()}")
logging.info(f"installer.sh contents:\n{f.read()}")
args = [self.constants.oclp_helper_path, "/bin/sh", self.constants.installer_sh_path]
result = subprocess.run(args, capture_output=True, text=True)
@@ -369,17 +370,17 @@ class macOSInstallerFlashFrame(wx.Frame):
error = result.stderr if result.stderr else ""
if "Install media now available at" not in output:
logging.info("- Failed to create macOS installer")
logging.info("Failed to create macOS installer")
popup = wx.MessageDialog(self, f"Failed to create macOS installer\n\nOutput: {output}\n\nError: {error}", "Error", wx.OK | wx.ICON_ERROR)
popup.ShowModal()
return False
logging.info("- Successfully created macOS installer")
logging.info("Successfully created macOS installer")
while thread.is_alive():
# wait for download_thread to finish
# though highly unlikely this thread is still alive (flashing an Installer will take a while)
time.sleep(0.1)
logging.info("- Installing Root Patcher to drive")
logging.info("Installing Root Patcher to drive")
self._install_installer_pkg(disk)
utilities.enable_sleep_after_running()
@@ -396,7 +397,7 @@ class macOSInstallerFlashFrame(wx.Frame):
"""
link = self.constants.installer_pkg_url
if network_handler.NetworkUtilities(link).validate_link() is False:
logging.info("- Stock Install.pkg is missing on Github, falling back to Nightly")
logging.info("Stock Install.pkg is missing on Github, falling back to Nightly")
link = self.constants.installer_pkg_url_nightly
if link.endswith(".zip"):
@@ -408,7 +409,7 @@ class macOSInstallerFlashFrame(wx.Frame):
autopkg_download.download(spawn_thread=False)
if autopkg_download.download_complete is False:
logging.warning("- Failed to download Install.pkg")
logging.warning("Failed to download Install.pkg")
logging.warning(autopkg_download.error_msg)
return
@@ -434,7 +435,7 @@ class macOSInstallerFlashFrame(wx.Frame):
os_version = plistlib.load(Path(path + "/System/Library/CoreServices/SystemVersion.plist").open("rb"))
kernel_version = os_data.os_conversion.os_to_kernel(os_version["ProductVersion"])
if int(kernel_version) < os_data.os_data.big_sur:
logging.info("- Installer unsupported, requires Big Sur or newer")
logging.info("Installer unsupported, requires Big Sur or newer")
return
subprocess.run(["mkdir", "-p", f"{path}/Library/Packages/"])
@@ -460,29 +461,29 @@ class macOSInstallerFlashFrame(wx.Frame):
if kdk_pkg_path.exists():
kdk_pkg_path.unlink()
logging.info("- Initiating KDK download")
logging.info(f" - Build: {build}")
logging.info(f" - Version: {version}")
logging.info(f" - Working Directory: {download_dir}")
logging.info("Initiating KDK download")
logging.info(f"- Build: {build}")
logging.info(f"- Version: {version}")
logging.info(f"- Working Directory: {download_dir}")
kdk_obj = kdk_handler.KernelDebugKitObject(self.constants, build, version, ignore_installed=True)
if kdk_obj.success is False:
logging.info("- Failed to retrieve KDK")
logging.info("Failed to retrieve KDK")
logging.info(kdk_obj.error_msg)
return
kdk_download_obj = kdk_obj.retrieve_download(override_path=kdk_dmg_path)
if kdk_download_obj is None:
logging.info("- Failed to retrieve KDK")
logging.info("Failed to retrieve KDK")
logging.info(kdk_obj.error_msg)
# Check remaining disk space before downloading
space = utilities.get_free_space(download_dir)
if space < (kdk_obj.kdk_url_expected_size * 2):
logging.info("- Not enough disk space to download and install KDK")
logging.info(f"- Attempting to download locally first")
logging.info("Not enough disk space to download and install KDK")
logging.info(f"Attempting to download locally first")
if space < kdk_obj.kdk_url_expected_size:
logging.info("- Not enough disk space to install KDK, skipping")
logging.info("Not enough disk space to install KDK, skipping")
return
# Ideally we'd download the KDK onto the disk to display progress in the UI
# However we'll just download to our temp directory and move it to the target disk
@@ -490,34 +491,34 @@ class macOSInstallerFlashFrame(wx.Frame):
kdk_download_obj.download(spawn_thread=False)
if kdk_download_obj.download_complete is False:
logging.info("- Failed to download KDK")
logging.info("Failed to download KDK")
logging.info(kdk_download_obj.error_msg)
return
if not kdk_dmg_path.exists():
logging.info(f"- KDK missing: {kdk_dmg_path}")
logging.info(f"KDK missing: {kdk_dmg_path}")
return
# Now that we have a KDK, extract it to get the pkg
with tempfile.TemporaryDirectory() as mount_point:
logging.info("- Mounting KDK")
logging.info("Mounting KDK")
result = subprocess.run(["hdiutil", "attach", kdk_dmg_path, "-mountpoint", mount_point, "-nobrowse"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if result.returncode != 0:
logging.info("- Failed to mount KDK")
logging.info("Failed to mount KDK")
logging.info(result.stdout.decode("utf-8"))
return
logging.info("- Copying KDK")
logging.info("Copying KDK")
subprocess.run(["cp", "-r", f"{mount_point}/KernelDebugKit.pkg", kdk_pkg_path])
logging.info("- Unmounting KDK")
logging.info("Unmounting KDK")
result = subprocess.run(["hdiutil", "detach", mount_point], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if result.returncode != 0:
logging.info("- Failed to unmount KDK")
logging.info("Failed to unmount KDK")
logging.info(result.stdout.decode("utf-8"))
return
logging.info("- Removing KDK Disk Image")
logging.info("Removing KDK Disk Image")
kdk_dmg_path.unlink()
def _validate_installer_pkg(self, disk: str) -> bool:

View File

@@ -24,6 +24,7 @@ from data import os_data
class MainFrame(wx.Frame):
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None):
logging.info("Initializing Main Menu Frame")
super(MainFrame, self).__init__(parent, title=title, size=(600, 400), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
gui_support.GenerateMenubar(self, global_constants).generate()
@@ -213,11 +214,11 @@ class MainFrame(wx.Frame):
pop_up.ShowModal()
if pop_up.GetReturnCode() != wx.ID_YES:
print("- Skipping OpenCore and root volume patch update...")
print("Skipping OpenCore and root volume patch update...")
return
print("- Updating OpenCore and root volume patches...")
print("Updating OpenCore and root volume patches...")
self.constants.update_stage = gui_support.AutoUpdateStages.CHECKING
self.Hide()
pos = self.GetPosition()

View File

@@ -32,6 +32,7 @@ class SettingsFrame(wx.Frame):
Modal-based Settings Frame
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None):
logging.info("Initializing Settings Frame")
self.constants: constants.Constants = global_constants
self.title: str = title
self.parent: wx.Frame = parent
@@ -1257,11 +1258,12 @@ Hardware Information:
def on_export_constants(self, event: wx.Event) -> None:
# Throw pop up to get save location
with wx.FileDialog(self.parent, "Save Constants File", wildcard="JSON files (*.txt)|*.txt", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog:
with wx.FileDialog(self.parent, "Save Constants File", wildcard="JSON files (*.txt)|*.txt", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT, defaultFile=f"constants-{self.constants.patcher_version}.txt") as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return
# Save the current contents in the file
pathname = fileDialog.GetPath()
logging.info(f"Saving constants to {pathname}")
with open(pathname, 'w') as file:
file.write(pprint.pformat(vars(self.constants), indent=4))

View File

@@ -289,7 +289,7 @@ class RelaunchApplicationAsRoot:
wx.Yield()
logging.info(f"- Relaunching as root with command: {program_arguments}")
logging.info(f"Relaunching as root with command: {program_arguments}")
subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:

View File

@@ -33,6 +33,7 @@ class SysPatchFrame(wx.Frame):
Uses a Modal Dialog for smoother transition from other frames
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None, patches: dict = {}):
logging.info("Initializing Root Patching Frame")
self.frame = parent
self.initiated_with_parent = False
if not self.frame and patches == {}:
@@ -167,7 +168,7 @@ class SysPatchFrame(wx.Frame):
can_unpatch: bool = patches["Validation: Unpatching Possible"]
if not any(not patch.startswith("Settings") and not patch.startswith("Validation") and patches[patch] is True for patch in patches):
logging.info("- No applicable patches available")
logging.info("No applicable patches available")
patches = []
# Check if OCLP has already applied the same patches
@@ -198,10 +199,11 @@ class SysPatchFrame(wx.Frame):
anchor.Centre(wx.HORIZONTAL)
anchor.Hide()
logging.info("Available patches:")
for patch in patches:
if (not patch.startswith("Settings") and not patch.startswith("Validation") and patches[patch] is True):
i = i + 20
logging.info(f"- Adding patch: {patch} - {patches[patch]}")
logging.info(f"- {patch}")
patch_label = wx.StaticText(frame, label=f"- {patch}", pos=(anchor.GetPosition()[0], available_label.GetPosition()[1] + i))
patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, ".AppleSystemUIFont"))
@@ -346,9 +348,10 @@ class SysPatchFrame(wx.Frame):
# Labels
i = 0
logging.info("Available patches:")
for patch in patches:
if (not patch.startswith("Settings") and not patch.startswith("Validation") and patches[patch] is True):
logging.info(f"- Adding patch: {patch} - {patches[patch]}")
logging.info(f"- {patch}")
patch_label = wx.StaticText(dialog, label=f"- {patch}", pos=(anchor.GetPosition()[0], label.GetPosition()[1] + 20 + i))
patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, ".AppleSystemUIFont"))
i = i + 20
@@ -422,7 +425,7 @@ class SysPatchFrame(wx.Frame):
try:
sys_patch.PatchSysVolume(self.constants.computer.real_model, self.constants, patches).start_patch()
except:
logging.error("- An internal error occurred while running the Root Patcher:\n")
logging.error("An internal error occurred while running the Root Patcher:\n")
logging.error(traceback.format_exc())
logger.removeHandler(logger.handlers[2])
@@ -454,7 +457,7 @@ class SysPatchFrame(wx.Frame):
try:
sys_patch.PatchSysVolume(self.constants.computer.real_model, self.constants, patches).start_unpatch()
except:
logging.error("- An internal error occurred while running the Root Patcher:\n")
logging.error("An internal error occurred while running the Root Patcher:\n")
logging.error(traceback.format_exc())
logger.removeHandler(logger.handlers[2])
@@ -525,6 +528,8 @@ class SysPatchFrame(wx.Frame):
Thus we'll need to see if the exact same OCLP build was used already
"""
logging.info("Checking if new patches are needed")
if self.constants.commit_info[0] in ["Running from source", "Built from source"]:
return True
@@ -557,5 +562,5 @@ class SysPatchFrame(wx.Frame):
logging.info(f"- Patch {patch} not installed")
return True
logging.info("- No new patches detected for system")
logging.info("No new patches detected for system")
return False

View File

@@ -22,6 +22,7 @@ class UpdateFrame(wx.Frame):
Create a frame for updating the patcher
"""
def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: wx.Point, url: str = "", version_label: str = "") -> None:
logging.info("Initializing Update Frame")
if parent:
self.parent: wx.Frame = parent
@@ -55,6 +56,9 @@ class UpdateFrame(wx.Frame):
self.version_label = version_label
self.url = url
logging.info(f"Update URL: {url}")
logging.info(f"Update Version: {version_label}")
self.frame: wx.Frame = wx.Frame(
parent=parent if parent else self,
title=self.title,
@@ -180,6 +184,7 @@ class UpdateFrame(wx.Frame):
["ditto", "-xk", str(self.constants.payload_path / "OpenCore-Patcher-GUI.app.zip"), str(self.constants.payload_path)], capture_output=True
)
if result.returncode != 0:
logging.error(f"Failed to extract update. Error: {result.stderr.decode('utf-8')}")
wx.CallAfter(self.progress_bar_animation.stop_pulse)
wx.CallAfter(self.progress_bar.SetValue, 0)
wx.CallAfter(wx.MessageBox, f"Failed to extract update. Error: {result.stderr.decode('utf-8')}", "Critical Error!", wx.OK | wx.ICON_ERROR)
@@ -190,6 +195,7 @@ class UpdateFrame(wx.Frame):
break
if i == 1:
logging.error("Failed to extract update. Error: Update file does not exist")
wx.CallAfter(self.progress_bar_animation.stop_pulse)
wx.CallAfter(self.progress_bar.SetValue, 0)
wx.CallAfter(wx.MessageBox, "Failed to extract update. Error: Update file does not exist", "Critical Error!", wx.OK | wx.ICON_ERROR)
@@ -251,8 +257,10 @@ EOF
wx.CallAfter(self.progress_bar_animation.stop_pulse)
wx.CallAfter(self.progress_bar.SetValue, 0)
if "User cancelled" in result.stderr.decode("utf-8"):
logging.info("User cancelled update")
wx.CallAfter(wx.MessageBox, "User cancelled update", "Update Cancelled", wx.OK | wx.ICON_INFORMATION)
else:
logging.critical(f"Failed to install update. Error: {result.stderr.decode('utf-8')}")
wx.CallAfter(wx.MessageBox, f"Failed to install update. Error: {result.stderr.decode('utf-8')}", "Critical Error!", wx.OK | wx.ICON_ERROR)
wx.CallAfter(sys.exit, 1)