From 4636c14dc31b014915501f28bf29c589a033fcf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2022 12:16:58 +0100 Subject: [PATCH 1/6] =?UTF-8?q?=E2=9C=A8=20Add=20new=20backup=20hooks=20fo?= =?UTF-8?q?r=20backup=20&=20restore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four new hooks were added: - octoprint.plugin.backup.before_backup - octoprint.plugin.backup.after_backup - octoprint.plugin.backup.before_restore - octoprint.plugin.backup.after_restore Those will allow plugins to perform additional tasks right before/after backup and right before/ after restore. This is a compromise for #4195: Instead of having an extension point in OctoPrint to pull in additional files, having to figure out readability, proper allow listing to prevent attempts to backup everything and the kitchen sink and such, plugins CAN pull in additional stuff they want to have in the backup into their data folder and then on restore (or start after restore) put it where it belongs. In an ideal world, we would ever only want to backup stuff that is already in the base folder anyhow, but as #4195 demonstrates there is sometimes a need for more. And since these hooks are not limited to this functionality specifically but could also be used for other stuff (think reregistering somewhere after restore or whatnot), I think they are a good compromise. Implements #4195 --- docs/bundledplugins/backup.rst | 54 ++- src/octoprint/plugins/backup/__init__.py | 513 +++++++++++++---------- 2 files changed, 345 insertions(+), 222 deletions(-) diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst index be4d392ff..08904875a 100644 --- a/docs/bundledplugins/backup.rst +++ b/docs/bundledplugins/backup.rst @@ -172,11 +172,61 @@ octoprint.plugin.backup.additional_excludes :return: A list of paths to exclude, relative to your plugin's data folder :rtype: list -Helpers -------- +.. _sec-bundledplugins-backup-hooks-before-backup: + +octoprint.plugin.backup.before_backup ++++++++++++++++++++++++++++++++++++++ + +.. py:function:: before_backup_hook(*args, **kwargs) + + .. versionadded:: 1.9.0 + + Use this to perform actions right before a backup is created. + +.. _sec-bundledplugins-backup-hooks-after-backup: + +octoprint.plugin.backup.after_backup +++++++++++++++++++++++++++++++++++++ + +.. py:function:: after_backup_hook(error=False, *args, **kwargs) + + .. versionadded:: 1.9.0 + + Use this to perform actions right after a backup was created or backup creation failed. The ``error`` parameter will be set to ``True`` if + the backup creation failed. + + :param error bool: Whether the backup creation failed or not + +.. _sec-bundledplugins-backup-hooks-before-restore: + +octoprint.plugin.backup.before_restore +++++++++++++++++++++++++++++++++++++++ + +.. py:function:: before_restore_hook(*args, **kwargs) + + .. versionadded:: 1.9.0 + + Use this to perform actions right before a backup is restored. + +.. _sec-bundledplugins-backup-hooks-after-restore: + +octoprint.plugin.backup.after_restore ++++++++++++++++++++++++++++++++++++++ + +.. py:function:: after_restore_hook(error=False, *args, **kwargs) + + .. versionadded:: 1.9.0 + + Use this to perform actions right after a backup was restored or backup restoration failed. The ``error`` parameter will be set to ``True`` if + the backup restoration failed. + + :param error bool: Whether the backup restoration failed or not .. _sec-bundledplugins-backup-helpers: +Helpers +------- + The Backup plugin exports two helpers that can be used by other plugins or internal methods from within OctoPrint, without going via the API. diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index aad296fb0..431c6e687 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -1008,87 +1008,115 @@ class BackupPlugin( compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED - if callable(on_backup_start): - on_backup_start(name, temporary_path, exclude) + backup_error = False + try: + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.before_backup" + ).items(): + try: + hook() + except Exception: + logger.exception( + f"Error while running before_backup hook from plugin {plugin}", + extra={"plugin": plugin}, + ) - with zipfile.ZipFile( - temporary_path, mode="w", compression=compression, allowZip64=True - ) as zip: + if callable(on_backup_start): + on_backup_start(name, temporary_path, exclude) - def add_to_zip(source, target, ignored=None): - if ignored is None: - ignored = [] + with zipfile.ZipFile( + temporary_path, mode="w", compression=compression, allowZip64=True + ) as zip: - if source in ignored: - return + def add_to_zip(source, target, ignored=None): + if ignored is None: + ignored = [] - if os.path.isdir(source): - for entry in os.scandir(source): - add_to_zip( - entry.path, - os.path.join(target, entry.name), - ignored=ignored, - ) - elif os.path.isfile(source): - zip.write(source, arcname=target) + if source in ignored: + return - # add metadata - metadata = { - "version": get_octoprint_version_string(), - "excludes": exclude, - } - zip.writestr("metadata.json", json.dumps(metadata)) + if os.path.isdir(source): + for entry in os.scandir(source): + add_to_zip( + entry.path, + os.path.join(target, entry.name), + ignored=ignored, + ) + elif os.path.isfile(source): + zip.write(source, arcname=target) - # backup current config file - add_to_zip( - configfile, - "basedir/config.yaml", - ignored=[ - own_folder, - ], - ) - - # backup configured folder paths - for folder in default_settings["folder"].keys(): - if folder in exclude or folder in exclude_by_default: - continue + # add metadata + metadata = { + "version": get_octoprint_version_string(), + "excludes": exclude, + } + zip.writestr("metadata.json", json.dumps(metadata)) + # backup current config file add_to_zip( - settings.global_get_basefolder(folder), - "basedir/" + folder.replace("_", "/"), + configfile, + "basedir/config.yaml", ignored=[ own_folder, + ], + ) + + # backup configured folder paths + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + + add_to_zip( + settings.global_get_basefolder(folder), + "basedir/" + folder.replace("_", "/"), + ignored=[ + own_folder, + ] + + additional_excludes, + ) + + # backup anything else that might be lying around in our basedir + add_to_zip( + basedir, + "basedir", + ignored=defaults + + [ + own_folder, ] + additional_excludes, ) - # backup anything else that might be lying around in our basedir - add_to_zip( - basedir, - "basedir", - ignored=defaults - + [ - own_folder, - ] - + additional_excludes, - ) - - # add list of installed plugins - helpers = plugin_manager.get_helpers( - "pluginmanager", "generate_plugins_json" - ) - if helpers and "generate_plugins_json" in helpers: - plugins = helpers["generate_plugins_json"]( - settings=settings, plugin_manager=plugin_manager + # add list of installed plugins + helpers = plugin_manager.get_helpers( + "pluginmanager", "generate_plugins_json" ) + if helpers and "generate_plugins_json" in helpers: + plugins = helpers["generate_plugins_json"]( + settings=settings, plugin_manager=plugin_manager + ) - if len(plugins): - zip.writestr("plugin_list.json", json.dumps(plugins)) + if len(plugins): + zip.writestr("plugin_list.json", json.dumps(plugins)) - shutil.move(temporary_path, final_path) + shutil.move(temporary_path, final_path) - if callable(on_backup_done): - on_backup_done(name, final_path, exclude) + if callable(on_backup_done): + on_backup_done(name, final_path, exclude) + + except Exception: + backup_error = True + raise + finally: + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.after_backup" + ).items(): + try: + hook(error=backup_error) + except Exception: + logger.exception( + f"Error while running after_backup hook from plugin {plugin}", + extra={"plugin": plugin}, + ) except Exception as exc: # noqa: F841 # TODO py3: use the exception, not sys.exc_info() @@ -1123,6 +1151,8 @@ class BackupPlugin( on_restore_failed(path) return False + logger = logging.getLogger(__name__) + restart_command = settings.global_get( ["server", "commands", "serverRestartCommand"] ) @@ -1136,199 +1166,242 @@ class BackupPlugin( plugin_repo = cls._get_plugin_repository_data(repo_url) - if callable(on_restore_start): - on_restore_start(path) - + restore_error = False try: - - with zipfile.ZipFile(path, "r") as zip: - # read metadata + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.before_restore" + ).items(): try: - metadata_zipinfo = zip.getinfo("metadata.json") - except KeyError: - if callable(on_invalid_backup): - on_invalid_backup("Not an OctoPrint backup, lacks metadata.json") - if callable(on_restore_failed): - on_restore_failed(path) - return False + hook() + except Exception: + logger.exception( + f"Error while running before_restore hook from plugin {plugin}", + extra={"plugin": plugin}, + ) - metadata_bytes = zip.read(metadata_zipinfo) - metadata = json.loads(metadata_bytes) + if callable(on_restore_start): + on_restore_start(path) - backup_version = get_comparable_version(metadata["version"], cut=1) - if backup_version > get_octoprint_version(cut=1): - if callable(on_invalid_backup): - on_invalid_backup( - "Backup is from a newer version of OctoPrint and cannot be applied" - ) - if callable(on_restore_failed): - on_restore_failed(path) - return False + try: - # unzip to temporary folder - temp = tempfile.mkdtemp() - try: - if callable(on_log_progress): - on_log_progress(f"Unpacking backup to {temp}...") - - abstemp = os.path.abspath(temp) - dirs = {} - for member in zip.infolist(): - abspath = os.path.abspath(os.path.join(temp, member.filename)) - if abspath.startswith(abstemp): - date_time = time.mktime(member.date_time + (0, 0, -1)) - - zip.extract(member, temp) - - if os.path.isdir(abspath): - dirs[abspath] = date_time - else: - os.utime(abspath, (date_time, date_time)) - - # set time on folders - for abspath, date_time in dirs.items(): - os.utime(abspath, (date_time, date_time)) - - # sanity check - configfile = os.path.join(temp, "basedir", "config.yaml") - if not os.path.exists(configfile): + with zipfile.ZipFile(path, "r") as zip: + # read metadata + try: + metadata_zipinfo = zip.getinfo("metadata.json") + except KeyError: if callable(on_invalid_backup): - on_invalid_backup("Backup lacks config.yaml") + on_invalid_backup( + "Not an OctoPrint backup, lacks metadata.json" + ) if callable(on_restore_failed): on_restore_failed(path) return False - configdata = yaml.load_from_file(path=configfile) + metadata_bytes = zip.read(metadata_zipinfo) + metadata = json.loads(metadata_bytes) - userfile = os.path.join(temp, "basedir", "users.yaml") - if not os.path.exists(userfile): + backup_version = get_comparable_version(metadata["version"], cut=1) + if backup_version > get_octoprint_version(cut=1): if callable(on_invalid_backup): - on_invalid_backup("Backup lacks users.yaml") + on_invalid_backup( + "Backup is from a newer version of OctoPrint and cannot be applied" + ) if callable(on_restore_failed): on_restore_failed(path) return False - if callable(on_log_progress): - on_log_progress("Unpacked") - - # install available plugins - plugins = [] - plugin_list_file = os.path.join(temp, "plugin_list.json") - if os.path.exists(plugin_list_file): - with open(os.path.join(temp, "plugin_list.json"), "rb") as f: - plugins = json.load(f) - - known_plugins = [] - unknown_plugins = [] - if plugins: - if plugin_repo: - for plugin in plugins: - if plugin["key"] in plugin_manager.plugins: - # already installed - continue - - if plugin["key"] in plugin_repo: - # not installed, can be installed from repository url - known_plugins.append(plugin_repo[plugin["key"]]) - else: - # not installed, not installable - unknown_plugins.append(plugin) - - else: - # no repo, all plugins are not installable - unknown_plugins = plugins - - if callable(on_log_progress): - if known_plugins: - on_log_progress( - "Known and installable plugins: {}".format( - ", ".join(map(lambda x: x["id"], known_plugins)) - ) - ) - if unknown_plugins: - on_log_progress( - "Unknown plugins: {}".format( - ", ".join( - map(lambda x: x["key"], unknown_plugins) - ) - ) - ) - - if callable(on_install_plugins): - on_install_plugins(known_plugins) - - if callable(on_report_unknown_plugins): - on_report_unknown_plugins(unknown_plugins) - - # move config data - basedir_backup = basedir + ".bck" - basedir_extracted = os.path.join(temp, "basedir") - - if callable(on_log_progress): - on_log_progress(f"Renaming {basedir} to {basedir_backup}...") - shutil.move(basedir, basedir_backup) - + # unzip to temporary folder + temp = tempfile.mkdtemp() try: if callable(on_log_progress): - on_log_progress(f"Moving {basedir_extracted} to {basedir}...") - shutil.move(basedir_extracted, basedir) - except Exception: - if callable(on_log_error): - on_log_error( - "Error while restoring config data", - exc_info=sys.exc_info(), - ) - on_log_error("Rolling back old config data") + on_log_progress(f"Unpacking backup to {temp}...") - shutil.move(basedir_backup, basedir) + abstemp = os.path.abspath(temp) + dirs = {} + for member in zip.infolist(): + abspath = os.path.abspath(os.path.join(temp, member.filename)) + if abspath.startswith(abstemp): + date_time = time.mktime(member.date_time + (0, 0, -1)) - if callable(on_restore_failed): - on_restore_failed(path) - return False + zip.extract(member, temp) + + if os.path.isdir(abspath): + dirs[abspath] = date_time + else: + os.utime(abspath, (date_time, date_time)) + + # set time on folders + for abspath, date_time in dirs.items(): + os.utime(abspath, (date_time, date_time)) + + # sanity check + configfile = os.path.join(temp, "basedir", "config.yaml") + if not os.path.exists(configfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks config.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + configdata = yaml.load_from_file(path=configfile) + + userfile = os.path.join(temp, "basedir", "users.yaml") + if not os.path.exists(userfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks users.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False - if unknown_plugins: if callable(on_log_progress): - on_log_progress("Writing info file about unknown plugins") + on_log_progress("Unpacked") - if not os.path.isdir(datafolder): - os.makedirs(datafolder) + # install available plugins + plugins = [] + plugin_list_file = os.path.join(temp, "plugin_list.json") + if os.path.exists(plugin_list_file): + with open(os.path.join(temp, "plugin_list.json"), "rb") as f: + plugins = json.load(f) + + known_plugins = [] + unknown_plugins = [] + if plugins: + if plugin_repo: + for plugin in plugins: + if plugin["key"] in plugin_manager.plugins: + # already installed + continue + + if plugin["key"] in plugin_repo: + # not installed, can be installed from repository url + known_plugins.append(plugin_repo[plugin["key"]]) + else: + # not installed, not installable + unknown_plugins.append(plugin) + + else: + # no repo, all plugins are not installable + unknown_plugins = plugins + + if callable(on_log_progress): + if known_plugins: + on_log_progress( + "Known and installable plugins: {}".format( + ", ".join( + map(lambda x: x["id"], known_plugins) + ) + ) + ) + if unknown_plugins: + on_log_progress( + "Unknown plugins: {}".format( + ", ".join( + map(lambda x: x["key"], unknown_plugins) + ) + ) + ) + + if callable(on_install_plugins): + on_install_plugins(known_plugins) + + if callable(on_report_unknown_plugins): + on_report_unknown_plugins(unknown_plugins) + + # move config data + basedir_backup = basedir + ".bck" + basedir_extracted = os.path.join(temp, "basedir") + + if callable(on_log_progress): + on_log_progress(f"Renaming {basedir} to {basedir_backup}...") + shutil.move(basedir, basedir_backup) - unknown_plugins_path = os.path.join( - datafolder, UNKNOWN_PLUGINS_FILE - ) try: - with open(unknown_plugins_path, mode="wb") as f: - f.write(to_bytes(json.dumps(unknown_plugins))) + if callable(on_log_progress): + on_log_progress( + f"Moving {basedir_extracted} to {basedir}..." + ) + shutil.move(basedir_extracted, basedir) except Exception: if callable(on_log_error): on_log_error( - "Could not persist list of unknown plugins to {}".format( - unknown_plugins_path - ), + "Error while restoring config data", exc_info=sys.exc_info(), ) + on_log_error("Rolling back old config data") + shutil.move(basedir_backup, basedir) + + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if unknown_plugins: + if callable(on_log_progress): + on_log_progress("Writing info file about unknown plugins") + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + unknown_plugins_path = os.path.join( + datafolder, UNKNOWN_PLUGINS_FILE + ) + try: + with open(unknown_plugins_path, mode="wb") as f: + f.write(to_bytes(json.dumps(unknown_plugins))) + except Exception: + if callable(on_log_error): + on_log_error( + "Could not persist list of unknown plugins to {}".format( + unknown_plugins_path + ), + exc_info=sys.exc_info(), + ) + + finally: + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.before_restore" + ).items(): + try: + hook(error=restore_error) + except Exception: + logger.exception( + f"Error while running after_restore hook from plugin {plugin}", + extra={"plugin": plugin}, + ) + + if callable(on_log_progress): + on_log_progress("Removing temporary unpacked folder") + shutil.rmtree(temp) + + except Exception: + restore_error = True + exc_info = sys.exc_info() + try: + if callable(on_log_error): + on_log_error("Error while running restore", exc_info=exc_info) + if callable(on_restore_failed): + on_restore_failed(path) finally: - if callable(on_log_progress): - on_log_progress("Removing temporary unpacked folder") - shutil.rmtree(temp) + del exc_info + return False - except Exception: - exc_info = sys.exc_info() - try: - if callable(on_log_error): - on_log_error("Error while running restore", exc_info=exc_info) - if callable(on_restore_failed): - on_restore_failed(path) finally: - del exc_info - return False + # remove zip + if callable(on_log_progress): + on_log_progress("Removing temporary zip") + os.remove(path) finally: - # remove zip - if callable(on_log_progress): - on_log_progress("Removing temporary zip") - os.remove(path) + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.after_restore" + ).items(): + try: + hook(error=restore_error) + except Exception: + logger.exception( + f"Error while running after_restore hook from plugin {plugin}", + extra={"plugin": plugin}, + ) # restart server if not restart_command: From cb63baa1e27f7a8b09ade89b869c9146f8af239f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2022 15:30:02 +0100 Subject: [PATCH 2/6] =?UTF-8?q?=E2=9C=A8=20Autorefresh=20port=20list=20whi?= =?UTF-8?q?le=20not=20connected?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements #4473 --- src/octoprint/events.py | 1 + src/octoprint/schema/config/serial.py | 6 +++ src/octoprint/server/__init__.py | 54 +++++++++++++++++++ .../static/js/app/viewmodels/connection.js | 4 ++ 4 files changed, 65 insertions(+) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 010c20604..00d164fa0 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -36,6 +36,7 @@ class Events: CONNECTED = "Connected" DISCONNECTING = "Disconnecting" DISCONNECTED = "Disconnected" + CONNECTIONS_AUTOREFRESHED = "ConnectionsAutorefreshed" # State changes PRINTER_STATE_CHANGED = "PrinterStateChanged" diff --git a/src/octoprint/schema/config/serial.py b/src/octoprint/schema/config/serial.py index 6da0e2f5c..5d3130921 100644 --- a/src/octoprint/schema/config/serial.py +++ b/src/octoprint/schema/config/serial.py @@ -105,6 +105,12 @@ class SerialConfig(BaseModel): autoconnect: bool = False """Whether to try to automatically connect to the printer on startup or not""" + autorefresh: bool = True + """Whether to automatically refresh the port list while no connection is established""" + + autorefreshInterval: int = 1 + """Interval in seconds at which to refresh the port list while no connection is established""" + log: bool = False """Whether to log whole communication to serial.log (warning: might decrease performance)""" diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index c8a77dbbc..9bd7f6583 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -40,6 +40,7 @@ from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver from werkzeug.exceptions import HTTPException +import octoprint.events import octoprint.filemanager import octoprint.util import octoprint.util.net @@ -1148,6 +1149,59 @@ class Server: "Something went wrong while attempting to automatically connect to the printer" ) + # auto refresh serial ports while not connected + if self._settings.getBoolean(["serial", "autorefresh"]): + from octoprint.util.comm import serialList + + last_ports = None + autorefresh = None + + def refresh_serial_list(): + nonlocal last_ports + + new_ports = sorted(serialList()) + if new_ports != last_ports: + self._logger.info( + "Serial port list was updated, refreshing the port list in the frontend" + ) + eventManager.fire( + events.Events.CONNECTIONS_AUTOREFRESHED, + payload={"ports": new_ports}, + ) + last_ports = new_ports + + def autorefresh_active(): + return printer.is_closed_or_error() + + def autorefresh_stopped(): + nonlocal autorefresh + + self._logger.info("Autorefresh of serial port list stopped") + autorefresh = None + + def run_autorefresh(): + nonlocal autorefresh + + if autorefresh is not None: + autorefresh.stop() + autorefresh = None + + autorefresh = octoprint.util.RepeatedTimer( + self._settings.getInt(["serial", "autorefreshInterval"]), + refresh_serial_list, + run_first=True, + condition=autorefresh_active, + on_finish=autorefresh_stopped, + ) + + self._logger.info("Starting autorefresh of serial port list") + autorefresh.start() + + run_autorefresh() + eventManager.subscribe( + octoprint.events.Events.DISCONNECTED, lambda e, p: run_autorefresh() + ) + # start up watchdogs try: watched = self._settings.getBaseFolder("watched") diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 664c30918..60b7a2258 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -220,6 +220,10 @@ $(function () { self.requestData(); }; + self.onEventConnectionsAutorefreshed = function () { + self.requestData(); + }; + self.onStartup = function () { var connectionTab = $("#connection"); connectionTab.on("show", function () { From 4b7085e3266c3e361dc18d2168145633017c4652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2022 16:59:16 +0100 Subject: [PATCH 3/6] =?UTF-8?q?=F0=9F=90=9B=20Fix=20missing=20timeout=20fo?= =?UTF-8?q?r=20blacklist=20fetch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4539 --- src/octoprint/schema/config/server.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/octoprint/schema/config/server.py b/src/octoprint/schema/config/server.py index 5124abf6b..bc1ab82fe 100644 --- a/src/octoprint/schema/config/server.py +++ b/src/octoprint/schema/config/server.py @@ -102,6 +102,9 @@ class PluginBlacklistConfig(BaseModel): ttl: int = CONST_15MIN """Time to live of the cached blacklist, in seconds (default: 15 minutes).""" + timeout: float = 3.1 + """Timeout for fetching the blacklist, in seconds (default: 3.1 seconds).""" + @with_attrs_docs class DiskspaceConfig(BaseModel): From faf35693a67253505792d175a411b67fb91a119b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2022 16:59:45 +0100 Subject: [PATCH 4/6] =?UTF-8?q?=F0=9F=A5=85=20Add=20some=20more=20missing?= =?UTF-8?q?=20timeouts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugins/softwareupdate/version_checks/jsondata.py | 2 +- src/octoprint/util/net.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py b/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py index be724a984..3a7d051a7 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py @@ -21,7 +21,7 @@ def get_latest(target, check, online=True, *args, **kwargs): raise ConfigurationInvalid("jsondata version check needs jsondata set") try: - with requests.get(url) as r: + with requests.get(url, timeout=(3.05, 30)) as r: data = r.json() except Exception as exc: raise NetworkError(cause=exc) diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py index 0e266103c..fa776b0ec 100644 --- a/src/octoprint/util/net.py +++ b/src/octoprint/util/net.py @@ -258,7 +258,7 @@ def resolve_host(host): def download_file(url, folder, max_length=None): - with requests.get(url, stream=True) as r: + with requests.get(url, stream=True, timeout=(3.05, 30)) as r: r.raise_for_status() filename = None From 6765ce74624ae5eebd4ebe5d1a7801ee029c5c90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2022 17:00:21 +0100 Subject: [PATCH 5/6] =?UTF-8?q?=F0=9F=A7=91=E2=80=8D=F0=9F=92=BB=20Add=20t?= =?UTF-8?q?hread=20name=20to=20autorefresh=20worker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/server/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 9bd7f6583..8a1ef9454 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1193,6 +1193,7 @@ class Server: condition=autorefresh_active, on_finish=autorefresh_stopped, ) + autorefresh.name = "Serial autorefresh worker" self._logger.info("Starting autorefresh of serial port list") autorefresh.start() From 61e6a6f389132ba5f97eab7c8b96508b675fd9d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 17 Nov 2022 18:19:13 +0100 Subject: [PATCH 6/6] =?UTF-8?q?=F0=9F=A5=85=20backup:=20Ensure=20only=20on?= =?UTF-8?q?e=20backup=20runs=20at=20a=20time?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4347 --- src/octoprint/plugins/backup/__init__.py | 835 ++++++++++++----------- 1 file changed, 423 insertions(+), 412 deletions(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 431c6e687..998b4ba2a 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -63,10 +63,8 @@ class BackupPlugin( _pip_caller = None - # noinspection PyMissingConstructor - def __init__(self): - self._in_progress = [] - self._in_progress_lock = threading.RLock() + _backup_in_progress = threading.Lock() + _restore_in_progress = threading.Lock() # Additional permissions hook @@ -134,7 +132,7 @@ class BackupPlugin( unknown_plugins = self._get_unknown_plugins() return flask.jsonify( backups=backups, - backup_in_progress=len(self._in_progress) > 0, + backup_in_progress=self._backup_in_progress.locked(), unknown_plugins=unknown_plugins, restore_supported=self._restore_supported(self._settings), max_upload_size=MAX_UPLOAD_SIZE, @@ -509,22 +507,25 @@ class BackupPlugin( if path is not None: datafolder, filename = os.path.split(os.path.abspath(path)) else: - filename = self._build_backup_filename(settings=settings) + filename = None datafolder = os.path.join(settings.getBaseFolder("data"), "backup") if not os.path.isdir(datafolder): os.makedirs(datafolder) - click.echo(f"Creating backup at {filename}, please wait...") - self._create_backup( - filename, + def on_backup_start(name, temporary_path, exclude): + click.echo(f"Creating backup at {name}, please wait...") + + path = self._create_backup( + name=filename, exclude=exclude, settings=settings, plugin_manager=cli_group.plugin_manager, datafolder=datafolder, + on_backup_start=on_backup_start, ) click.echo("Done.") - click.echo(f"Backup located at {os.path.join(datafolder, filename)}") + click.echo(f"Backup located at {path}") @click.command("restore") @click.argument("path") @@ -662,25 +663,16 @@ class BackupPlugin( ##~~ helpers def _start_backup(self, exclude, filename=None): - if filename is None: - filename = self._build_backup_filename(settings=self._settings) - def on_backup_start(name, temporary_path, exclude): self._logger.info( "Creating backup zip at {} (excluded: {})...".format( temporary_path, ",".join(exclude) if len(exclude) else "-" ) ) - - with self._in_progress_lock: - self._in_progress.append(name) - self._send_client_message("backup_started", payload={"name": name}) + self._send_client_message("backup_started", payload={"name": name}) def on_backup_done(name, final_path, exclude): - with self._in_progress_lock: - self._in_progress.remove(name) - self._send_client_message("backup_done", payload={"name": name}) - + self._send_client_message("backup_done", payload={"name": name}) self._logger.info("... done creating backup zip.") self._event_bus.fire( @@ -689,13 +681,6 @@ class BackupPlugin( ) def on_backup_error(name, exc_info): - with self._in_progress_lock: - try: - self._in_progress.remove(name) - except ValueError: - # we'll ignore that - pass - self._send_client_message( "backup_error", payload={"name": name, "error": f"{exc_info[1]}"} ) @@ -703,8 +688,8 @@ class BackupPlugin( thread = threading.Thread( target=self._create_backup, - args=(filename,), kwargs={ + "name": filename, "exclude": exclude, "settings": self._settings, "plugin_manager": self._plugin_manager, @@ -917,7 +902,7 @@ class BackupPlugin( @classmethod def _create_backup( cls, - name, + name=None, exclude=None, settings=None, plugin_manager=None, @@ -936,197 +921,207 @@ class BackupPlugin( "watched", ) - try: - if exclude is None: - exclude = [] - if not isinstance(exclude, list): - exclude = list(exclude) + with cls._backup_in_progress: - if "timelapse" in exclude: - exclude.append("timelapse_tmp") + if name is None: + name = cls._build_backup_filename(settings) - current_excludes = list(exclude) - additional_excludes = list() - plugin_data = settings.global_get_basefolder("data") - for plugin, hook in plugin_manager.get_hooks( - "octoprint.plugin.backup.additional_excludes" - ).items(): - try: - additional = hook(current_excludes) - if isinstance(additional, list): - if "." in additional: - current_excludes.append(os.path.join("data", plugin)) - additional_excludes.append(os.path.join(plugin_data, plugin)) - else: - current_excludes += map( - lambda x: os.path.join("data", plugin, x), additional - ) - additional_excludes += map( - lambda x: os.path.join(plugin_data, plugin, x), additional - ) - except Exception: - logger.exception( - f"Error while retrieving additional excludes " - f"from plugin {name}", - extra={"plugin": plugin}, - ) - - configfile = settings._configfile - basedir = settings._basedir - - temporary_path = os.path.join(datafolder, f".{name}") - final_path = os.path.join(datafolder, name) - - own_folder = datafolder - defaults = [os.path.join(basedir, "config.yaml"),] + [ - os.path.join(basedir, folder) - for folder in default_settings["folder"].keys() - ] - - # check how many bytes we are about to backup - size = os.stat(configfile).st_size - for folder in default_settings["folder"].keys(): - if folder in exclude or folder in exclude_by_default: - continue - size += cls._get_disk_size( - settings.global_get_basefolder(folder), - ignored=[ - own_folder, - ], - ) - size += cls._get_disk_size( - basedir, - ignored=defaults - + [ - own_folder, - ], - ) - - # since we can't know the compression ratio beforehand, we assume we need the same amount of space - if not cls._free_space(os.path.dirname(temporary_path), size): - raise InsufficientSpace() - - compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED - - backup_error = False try: + if exclude is None: + exclude = [] + if not isinstance(exclude, list): + exclude = list(exclude) + + if "timelapse" in exclude: + exclude.append("timelapse_tmp") + + current_excludes = list(exclude) + additional_excludes = list() + plugin_data = settings.global_get_basefolder("data") for plugin, hook in plugin_manager.get_hooks( - "octoprint.plugin.backup.before_backup" + "octoprint.plugin.backup.additional_excludes" ).items(): try: - hook() + additional = hook(current_excludes) + if isinstance(additional, list): + if "." in additional: + current_excludes.append(os.path.join("data", plugin)) + additional_excludes.append( + os.path.join(plugin_data, plugin) + ) + else: + current_excludes += map( + lambda x: os.path.join("data", plugin, x), additional + ) + additional_excludes += map( + lambda x: os.path.join(plugin_data, plugin, x), + additional, + ) except Exception: logger.exception( - f"Error while running before_backup hook from plugin {plugin}", + f"Error while retrieving additional excludes " + f"from plugin {plugin}", extra={"plugin": plugin}, ) - if callable(on_backup_start): - on_backup_start(name, temporary_path, exclude) + configfile = settings._configfile + basedir = settings._basedir - with zipfile.ZipFile( - temporary_path, mode="w", compression=compression, allowZip64=True - ) as zip: + temporary_path = os.path.join(datafolder, f".{name}") + final_path = os.path.join(datafolder, name) - def add_to_zip(source, target, ignored=None): - if ignored is None: - ignored = [] + own_folder = datafolder + defaults = [os.path.join(basedir, "config.yaml"),] + [ + os.path.join(basedir, folder) + for folder in default_settings["folder"].keys() + ] - if source in ignored: - return - - if os.path.isdir(source): - for entry in os.scandir(source): - add_to_zip( - entry.path, - os.path.join(target, entry.name), - ignored=ignored, - ) - elif os.path.isfile(source): - zip.write(source, arcname=target) - - # add metadata - metadata = { - "version": get_octoprint_version_string(), - "excludes": exclude, - } - zip.writestr("metadata.json", json.dumps(metadata)) - - # backup current config file - add_to_zip( - configfile, - "basedir/config.yaml", + # check how many bytes we are about to backup + size = os.stat(configfile).st_size + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + size += cls._get_disk_size( + settings.global_get_basefolder(folder), ignored=[ own_folder, ], ) + size += cls._get_disk_size( + basedir, + ignored=defaults + + [ + own_folder, + ], + ) - # backup configured folder paths - for folder in default_settings["folder"].keys(): - if folder in exclude or folder in exclude_by_default: - continue + # since we can't know the compression ratio beforehand, we assume we need the same amount of space + if not cls._free_space(os.path.dirname(temporary_path), size): + raise InsufficientSpace() + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED + + backup_error = False + try: + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.before_backup" + ).items(): + try: + hook() + except Exception: + logger.exception( + f"Error while running before_backup hook from plugin {plugin}", + extra={"plugin": plugin}, + ) + + if callable(on_backup_start): + on_backup_start(name, temporary_path, exclude) + + with zipfile.ZipFile( + temporary_path, mode="w", compression=compression, allowZip64=True + ) as zip: + + def add_to_zip(source, target, ignored=None): + if ignored is None: + ignored = [] + + if source in ignored: + return + + if os.path.isdir(source): + for entry in os.scandir(source): + add_to_zip( + entry.path, + os.path.join(target, entry.name), + ignored=ignored, + ) + elif os.path.isfile(source): + zip.write(source, arcname=target) + + # add metadata + metadata = { + "version": get_octoprint_version_string(), + "excludes": exclude, + } + zip.writestr("metadata.json", json.dumps(metadata)) + + # backup current config file add_to_zip( - settings.global_get_basefolder(folder), - "basedir/" + folder.replace("_", "/"), + configfile, + "basedir/config.yaml", ignored=[ own_folder, + ], + ) + + # backup configured folder paths + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + + add_to_zip( + settings.global_get_basefolder(folder), + "basedir/" + folder.replace("_", "/"), + ignored=[ + own_folder, + ] + + additional_excludes, + ) + + # backup anything else that might be lying around in our basedir + add_to_zip( + basedir, + "basedir", + ignored=defaults + + [ + own_folder, ] + additional_excludes, ) - # backup anything else that might be lying around in our basedir - add_to_zip( - basedir, - "basedir", - ignored=defaults - + [ - own_folder, - ] - + additional_excludes, - ) - - # add list of installed plugins - helpers = plugin_manager.get_helpers( - "pluginmanager", "generate_plugins_json" - ) - if helpers and "generate_plugins_json" in helpers: - plugins = helpers["generate_plugins_json"]( - settings=settings, plugin_manager=plugin_manager + # add list of installed plugins + helpers = plugin_manager.get_helpers( + "pluginmanager", "generate_plugins_json" ) + if helpers and "generate_plugins_json" in helpers: + plugins = helpers["generate_plugins_json"]( + settings=settings, plugin_manager=plugin_manager + ) - if len(plugins): - zip.writestr("plugin_list.json", json.dumps(plugins)) + if len(plugins): + zip.writestr("plugin_list.json", json.dumps(plugins)) - shutil.move(temporary_path, final_path) + shutil.move(temporary_path, final_path) - if callable(on_backup_done): - on_backup_done(name, final_path, exclude) + if callable(on_backup_done): + on_backup_done(name, final_path, exclude) - except Exception: - backup_error = True - raise - finally: - for plugin, hook in plugin_manager.get_hooks( - "octoprint.plugin.backup.after_backup" - ).items(): - try: - hook(error=backup_error) - except Exception: - logger.exception( - f"Error while running after_backup hook from plugin {plugin}", - extra={"plugin": plugin}, - ) + return final_path - except Exception as exc: # noqa: F841 - # TODO py3: use the exception, not sys.exc_info() - if callable(on_backup_error): - exc_info = sys.exc_info() - try: - on_backup_error(name, exc_info) + except Exception: + backup_error = True + raise finally: - del exc_info - raise + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.after_backup" + ).items(): + try: + hook(error=backup_error) + except Exception: + logger.exception( + f"Error while running after_backup hook from plugin {plugin}", + extra={"plugin": plugin}, + ) + + except Exception as exc: # noqa: F841 + # TODO py3: use the exception, not sys.exc_info() + if callable(on_backup_error): + exc_info = sys.exc_info() + try: + on_backup_error(name, exc_info) + finally: + del exc_info + raise @classmethod def _restore_backup( @@ -1166,277 +1161,293 @@ class BackupPlugin( plugin_repo = cls._get_plugin_repository_data(repo_url) - restore_error = False - try: - for plugin, hook in plugin_manager.get_hooks( - "octoprint.plugin.backup.before_restore" - ).items(): - try: - hook() - except Exception: - logger.exception( - f"Error while running before_restore hook from plugin {plugin}", - extra={"plugin": plugin}, - ) - - if callable(on_restore_start): - on_restore_start(path) - + with cls._restore_in_progress: + restore_error = False try: - - with zipfile.ZipFile(path, "r") as zip: - # read metadata + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.before_restore" + ).items(): try: - metadata_zipinfo = zip.getinfo("metadata.json") - except KeyError: - if callable(on_invalid_backup): - on_invalid_backup( - "Not an OctoPrint backup, lacks metadata.json" - ) - if callable(on_restore_failed): - on_restore_failed(path) - return False + hook() + except Exception: + logger.exception( + f"Error while running before_restore hook from plugin {plugin}", + extra={"plugin": plugin}, + ) - metadata_bytes = zip.read(metadata_zipinfo) - metadata = json.loads(metadata_bytes) + if callable(on_restore_start): + on_restore_start(path) - backup_version = get_comparable_version(metadata["version"], cut=1) - if backup_version > get_octoprint_version(cut=1): - if callable(on_invalid_backup): - on_invalid_backup( - "Backup is from a newer version of OctoPrint and cannot be applied" - ) - if callable(on_restore_failed): - on_restore_failed(path) - return False + try: - # unzip to temporary folder - temp = tempfile.mkdtemp() - try: - if callable(on_log_progress): - on_log_progress(f"Unpacking backup to {temp}...") - - abstemp = os.path.abspath(temp) - dirs = {} - for member in zip.infolist(): - abspath = os.path.abspath(os.path.join(temp, member.filename)) - if abspath.startswith(abstemp): - date_time = time.mktime(member.date_time + (0, 0, -1)) - - zip.extract(member, temp) - - if os.path.isdir(abspath): - dirs[abspath] = date_time - else: - os.utime(abspath, (date_time, date_time)) - - # set time on folders - for abspath, date_time in dirs.items(): - os.utime(abspath, (date_time, date_time)) - - # sanity check - configfile = os.path.join(temp, "basedir", "config.yaml") - if not os.path.exists(configfile): + with zipfile.ZipFile(path, "r") as zip: + # read metadata + try: + metadata_zipinfo = zip.getinfo("metadata.json") + except KeyError: if callable(on_invalid_backup): - on_invalid_backup("Backup lacks config.yaml") + on_invalid_backup( + "Not an OctoPrint backup, lacks metadata.json" + ) if callable(on_restore_failed): on_restore_failed(path) return False - configdata = yaml.load_from_file(path=configfile) + metadata_bytes = zip.read(metadata_zipinfo) + metadata = json.loads(metadata_bytes) - userfile = os.path.join(temp, "basedir", "users.yaml") - if not os.path.exists(userfile): + backup_version = get_comparable_version( + metadata["version"], cut=1 + ) + if backup_version > get_octoprint_version(cut=1): if callable(on_invalid_backup): - on_invalid_backup("Backup lacks users.yaml") + on_invalid_backup( + "Backup is from a newer version of OctoPrint and cannot be applied" + ) if callable(on_restore_failed): on_restore_failed(path) return False - if callable(on_log_progress): - on_log_progress("Unpacked") - - # install available plugins - plugins = [] - plugin_list_file = os.path.join(temp, "plugin_list.json") - if os.path.exists(plugin_list_file): - with open(os.path.join(temp, "plugin_list.json"), "rb") as f: - plugins = json.load(f) - - known_plugins = [] - unknown_plugins = [] - if plugins: - if plugin_repo: - for plugin in plugins: - if plugin["key"] in plugin_manager.plugins: - # already installed - continue - - if plugin["key"] in plugin_repo: - # not installed, can be installed from repository url - known_plugins.append(plugin_repo[plugin["key"]]) - else: - # not installed, not installable - unknown_plugins.append(plugin) - - else: - # no repo, all plugins are not installable - unknown_plugins = plugins - - if callable(on_log_progress): - if known_plugins: - on_log_progress( - "Known and installable plugins: {}".format( - ", ".join( - map(lambda x: x["id"], known_plugins) - ) - ) - ) - if unknown_plugins: - on_log_progress( - "Unknown plugins: {}".format( - ", ".join( - map(lambda x: x["key"], unknown_plugins) - ) - ) - ) - - if callable(on_install_plugins): - on_install_plugins(known_plugins) - - if callable(on_report_unknown_plugins): - on_report_unknown_plugins(unknown_plugins) - - # move config data - basedir_backup = basedir + ".bck" - basedir_extracted = os.path.join(temp, "basedir") - - if callable(on_log_progress): - on_log_progress(f"Renaming {basedir} to {basedir_backup}...") - shutil.move(basedir, basedir_backup) - + # unzip to temporary folder + temp = tempfile.mkdtemp() try: if callable(on_log_progress): - on_log_progress( - f"Moving {basedir_extracted} to {basedir}..." + on_log_progress(f"Unpacking backup to {temp}...") + + abstemp = os.path.abspath(temp) + dirs = {} + for member in zip.infolist(): + abspath = os.path.abspath( + os.path.join(temp, member.filename) ) - shutil.move(basedir_extracted, basedir) - except Exception: - if callable(on_log_error): - on_log_error( - "Error while restoring config data", - exc_info=sys.exc_info(), - ) - on_log_error("Rolling back old config data") + if abspath.startswith(abstemp): + date_time = time.mktime(member.date_time + (0, 0, -1)) - shutil.move(basedir_backup, basedir) + zip.extract(member, temp) - if callable(on_restore_failed): - on_restore_failed(path) - return False + if os.path.isdir(abspath): + dirs[abspath] = date_time + else: + os.utime(abspath, (date_time, date_time)) + + # set time on folders + for abspath, date_time in dirs.items(): + os.utime(abspath, (date_time, date_time)) + + # sanity check + configfile = os.path.join(temp, "basedir", "config.yaml") + if not os.path.exists(configfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks config.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + configdata = yaml.load_from_file(path=configfile) + + userfile = os.path.join(temp, "basedir", "users.yaml") + if not os.path.exists(userfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks users.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False - if unknown_plugins: if callable(on_log_progress): - on_log_progress("Writing info file about unknown plugins") + on_log_progress("Unpacked") - if not os.path.isdir(datafolder): - os.makedirs(datafolder) + # install available plugins + plugins = [] + plugin_list_file = os.path.join(temp, "plugin_list.json") + if os.path.exists(plugin_list_file): + with open( + os.path.join(temp, "plugin_list.json"), "rb" + ) as f: + plugins = json.load(f) + + known_plugins = [] + unknown_plugins = [] + if plugins: + if plugin_repo: + for plugin in plugins: + if plugin["key"] in plugin_manager.plugins: + # already installed + continue + + if plugin["key"] in plugin_repo: + # not installed, can be installed from repository url + known_plugins.append( + plugin_repo[plugin["key"]] + ) + else: + # not installed, not installable + unknown_plugins.append(plugin) + + else: + # no repo, all plugins are not installable + unknown_plugins = plugins + + if callable(on_log_progress): + if known_plugins: + on_log_progress( + "Known and installable plugins: {}".format( + ", ".join( + map(lambda x: x["id"], known_plugins) + ) + ) + ) + if unknown_plugins: + on_log_progress( + "Unknown plugins: {}".format( + ", ".join( + map( + lambda x: x["key"], + unknown_plugins, + ) + ) + ) + ) + + if callable(on_install_plugins): + on_install_plugins(known_plugins) + + if callable(on_report_unknown_plugins): + on_report_unknown_plugins(unknown_plugins) + + # move config data + basedir_backup = basedir + ".bck" + basedir_extracted = os.path.join(temp, "basedir") + + if callable(on_log_progress): + on_log_progress( + f"Renaming {basedir} to {basedir_backup}..." + ) + shutil.move(basedir, basedir_backup) - unknown_plugins_path = os.path.join( - datafolder, UNKNOWN_PLUGINS_FILE - ) try: - with open(unknown_plugins_path, mode="wb") as f: - f.write(to_bytes(json.dumps(unknown_plugins))) + if callable(on_log_progress): + on_log_progress( + f"Moving {basedir_extracted} to {basedir}..." + ) + shutil.move(basedir_extracted, basedir) except Exception: if callable(on_log_error): on_log_error( - "Could not persist list of unknown plugins to {}".format( - unknown_plugins_path - ), + "Error while restoring config data", exc_info=sys.exc_info(), ) + on_log_error("Rolling back old config data") - finally: - for plugin, hook in plugin_manager.get_hooks( - "octoprint.plugin.backup.before_restore" - ).items(): - try: - hook(error=restore_error) - except Exception: - logger.exception( - f"Error while running after_restore hook from plugin {plugin}", - extra={"plugin": plugin}, + shutil.move(basedir_backup, basedir) + + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if unknown_plugins: + if callable(on_log_progress): + on_log_progress( + "Writing info file about unknown plugins" + ) + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + unknown_plugins_path = os.path.join( + datafolder, UNKNOWN_PLUGINS_FILE ) + try: + with open(unknown_plugins_path, mode="wb") as f: + f.write(to_bytes(json.dumps(unknown_plugins))) + except Exception: + if callable(on_log_error): + on_log_error( + "Could not persist list of unknown plugins to {}".format( + unknown_plugins_path + ), + exc_info=sys.exc_info(), + ) - if callable(on_log_progress): - on_log_progress("Removing temporary unpacked folder") - shutil.rmtree(temp) + finally: + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.before_restore" + ).items(): + try: + hook(error=restore_error) + except Exception: + logger.exception( + f"Error while running after_restore hook from plugin {plugin}", + extra={"plugin": plugin}, + ) + + if callable(on_log_progress): + on_log_progress("Removing temporary unpacked folder") + shutil.rmtree(temp) + + except Exception: + restore_error = True + exc_info = sys.exc_info() + try: + if callable(on_log_error): + on_log_error("Error while running restore", exc_info=exc_info) + if callable(on_restore_failed): + on_restore_failed(path) + finally: + del exc_info + return False - except Exception: - restore_error = True - exc_info = sys.exc_info() - try: - if callable(on_log_error): - on_log_error("Error while running restore", exc_info=exc_info) - if callable(on_restore_failed): - on_restore_failed(path) finally: - del exc_info - return False + # remove zip + if callable(on_log_progress): + on_log_progress("Removing temporary zip") + os.remove(path) finally: - # remove zip + for plugin, hook in plugin_manager.get_hooks( + "octoprint.plugin.backup.after_restore" + ).items(): + try: + hook(error=restore_error) + except Exception: + logger.exception( + f"Error while running after_restore hook from plugin {plugin}", + extra={"plugin": plugin}, + ) + + # restart server + if not restart_command: + restart_command = ( + configdata.get("server", {}) + .get("commands", {}) + .get("serverRestartCommand") + ) + + if restart_command: + import sarge + if callable(on_log_progress): - on_log_progress("Removing temporary zip") - os.remove(path) + on_log_progress("Restarting...") + if callable(on_restore_done): + on_restore_done(path) - finally: - for plugin, hook in plugin_manager.get_hooks( - "octoprint.plugin.backup.after_restore" - ).items(): try: - hook(error=restore_error) + sarge.run(restart_command, close_fds=True, async_=True) except Exception: - logger.exception( - f"Error while running after_restore hook from plugin {plugin}", - extra={"plugin": plugin}, - ) + if callable(on_log_error): + on_log_error( + f"Error while restarting via command {restart_command}", + exc_info=sys.exc_info(), + ) + on_log_error("Please restart OctoPrint manually") + return False - # restart server - if not restart_command: - restart_command = ( - configdata.get("server", {}) - .get("commands", {}) - .get("serverRestartCommand") - ) - - if restart_command: - import sarge - - if callable(on_log_progress): - on_log_progress("Restarting...") - if callable(on_restore_done): - on_restore_done(path) - - try: - sarge.run(restart_command, close_fds=True, async_=True) - except Exception: + else: + if callable(on_restore_done): + on_restore_done(path) if callable(on_log_error): on_log_error( - f"Error while restarting via command {restart_command}", - exc_info=sys.exc_info(), + "No restart command configured. Please restart OctoPrint manually." ) - on_log_error("Please restart OctoPrint manually") - return False - - else: - if callable(on_restore_done): - on_restore_done(path) - if callable(on_log_error): - on_log_error( - "No restart command configured. Please restart OctoPrint manually." - ) return True