From 9e6d5c9d5d46b04f0caa0458b8fb669c7fd0f00c Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sat, 5 Dec 2020 12:49:11 +0000 Subject: [PATCH 1/6] :sparkles: Export backup creation as a helper --- src/octoprint/plugins/backup/__init__.py | 127 +++++++++++++---------- 1 file changed, 74 insertions(+), 53 deletions(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index c9d85d444..b3ccb84e2 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -168,63 +168,12 @@ class BackupPlugin( @no_firstrun_access @Permissions.PLUGIN_BACKUP_ACCESS.require(403) def create_backup(self): - backup_file = self._build_backup_filename(settings=self._settings) data = flask.request.json exclude = data.get("exclude", []) + backup_file = 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}) - - 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._logger.info("... done creating backup zip.") - - self._event_bus.fire( - Events.PLUGIN_BACKUP_BACKUP_CREATED, - {"name": name, "path": final_path, "excludes": exclude}, - ) - - 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": "{}".format(exc_info[1])} - ) - self._logger.error("Error while creating backup zip", exc_info=exc_info) - - thread = threading.Thread( - target=self._create_backup, - args=(backup_file,), - kwargs={ - "exclude": exclude, - "settings": self._settings, - "plugin_manager": self._plugin_manager, - "logger": self._logger, - "datafolder": self.get_plugin_data_folder(), - "on_backup_start": on_backup_start, - "on_backup_done": on_backup_done, - "on_backup_error": on_backup_error, - }, - ) - thread.daemon = True - thread.start() + self._start_backup(exclude, backup_file) response = flask.jsonify(started=True, name=backup_file) response.status_code = 201 @@ -454,6 +403,18 @@ class BackupPlugin( # max upload size of 1GB for the restore endpoint return [("POST", r"/restore", 1024 * 1024 * 1024)] + # Exported plugin helpers + def create_backup_helper(self, exclude=None, backup_file=None): + """ + Trigger a backup from a plugin or other internal call + Args: + exclude (list): Identifiers of data folders to exclude + """ + if exclude is None or not (type(exclude) == list): + exclude = [] + + self._start_backup(exclude, backup_file=None) + ##~~ CLI hook def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): @@ -638,6 +599,63 @@ class BackupPlugin( ##~~ helpers + def _start_backup(self, exclude, backup_file=None): + if backup_file is None: + backup_file = 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}) + + 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._logger.info("... done creating backup zip.") + + self._event_bus.fire( + Events.PLUGIN_BACKUP_BACKUP_CREATED, + {"name": name, "path": final_path, "excludes": exclude}, + ) + + 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": "{}".format(exc_info[1])} + ) + self._logger.error("Error while creating backup zip", exc_info=exc_info) + + thread = threading.Thread( + target=self._create_backup, + args=(backup_file,), + kwargs={ + "exclude": exclude, + "settings": self._settings, + "plugin_manager": self._plugin_manager, + "logger": self._logger, + "datafolder": self.get_plugin_data_folder(), + "on_backup_start": on_backup_start, + "on_backup_done": on_backup_done, + "on_backup_error": on_backup_error, + }, + ) + thread.daemon = True + thread.start() + def _get_backups(self): backups = [] for entry in scandir(self.get_plugin_data_folder()): @@ -1331,3 +1349,6 @@ __plugin_hooks__ = { "octoprint.events.register_custom_events": _register_custom_events, "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook, } +__plugin_helpers__ = { + "create_backup": __plugin_implementation__.create_backup_helper, +} From 8241d07190e1f8d28e504445524eeea517c87341 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sat, 5 Dec 2020 12:59:05 +0000 Subject: [PATCH 2/6] :bug: Fix backup name passing & return name to caller Very similar to API response --- src/octoprint/plugins/backup/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index b3ccb84e2..0b6765caa 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -413,7 +413,8 @@ class BackupPlugin( if exclude is None or not (type(exclude) == list): exclude = [] - self._start_backup(exclude, backup_file=None) + self._start_backup(exclude, backup_file=backup_file) + return backup_file ##~~ CLI hook From 280baee3a0f299366daa303ab23a1379405ebd0d Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sat, 5 Dec 2020 18:22:14 +0000 Subject: [PATCH 3/6] :sparkles: Backup deletion helper --- src/octoprint/plugins/backup/__init__.py | 37 ++++++++++++++++-------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 0b6765caa..9a30632f2 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -183,18 +183,8 @@ class BackupPlugin( @no_firstrun_access @Permissions.PLUGIN_BACKUP_ACCESS.require(403) def delete_backup(self, filename): - backup_folder = self.get_plugin_data_folder() - full_path = os.path.realpath(os.path.join(backup_folder, filename)) - if ( - full_path.startswith(backup_folder) - and os.path.exists(full_path) - and not is_hidden_path(full_path) - ): - try: - os.remove(full_path) - except Exception: - self._logger.exception("Could not delete {}".format(filename)) - raise + self._delete_backup(filename) + return NO_CONTENT @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) @@ -416,6 +406,9 @@ class BackupPlugin( self._start_backup(exclude, backup_file=backup_file) return backup_file + def delete_backup_helper(self, backup_file): + self._delete_backup(backup_file) + ##~~ CLI hook def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): @@ -657,6 +650,25 @@ class BackupPlugin( thread.daemon = True thread.start() + def _delete_backup(self, filename): + """ + Delete the backup specified + Args: + filename (str): Name of backup to delete + """ + backup_folder = self.get_plugin_data_folder() + full_path = os.path.realpath(os.path.join(backup_folder, filename)) + if ( + full_path.startswith(backup_folder) + and os.path.exists(full_path) + and not is_hidden_path(full_path) + ): + try: + os.remove(full_path) + except Exception: + self._logger.exception("Could not delete {}".format(filename)) + raise + def _get_backups(self): backups = [] for entry in scandir(self.get_plugin_data_folder()): @@ -1352,4 +1364,5 @@ __plugin_hooks__ = { } __plugin_helpers__ = { "create_backup": __plugin_implementation__.create_backup_helper, + "delete_backup": __plugin_implementation__.delete_backup_helper, } From 3cf798120a0546fcf937d79a037ac1edc33b50d4 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sun, 27 Dec 2020 16:13:31 +0000 Subject: [PATCH 4/6] :recycle: Rename backup_file to filename For consistency, all methods should now use filename rather than backup_file, since that was not clear if it should be a file object or name. https://github.com/OctoPrint/OctoPrint/pull/3866#pullrequestreview-549218212 --- src/octoprint/plugins/backup/__init__.py | 36 +++++++++++------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 9a30632f2..94639b8e5 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -171,11 +171,11 @@ class BackupPlugin( data = flask.request.json exclude = data.get("exclude", []) - backup_file = self._build_backup_filename(settings=self._settings) + filename = self._build_backup_filename(settings=self._settings) - self._start_backup(exclude, backup_file) + self._start_backup(exclude, filename) - response = flask.jsonify(started=True, name=backup_file) + response = flask.jsonify(started=True, name=filename) response.status_code = 201 return response @@ -394,7 +394,7 @@ class BackupPlugin( return [("POST", r"/restore", 1024 * 1024 * 1024)] # Exported plugin helpers - def create_backup_helper(self, exclude=None, backup_file=None): + def create_backup_helper(self, exclude=None, filename=None): """ Trigger a backup from a plugin or other internal call Args: @@ -403,11 +403,11 @@ class BackupPlugin( if exclude is None or not (type(exclude) == list): exclude = [] - self._start_backup(exclude, backup_file=backup_file) - return backup_file + self._start_backup(exclude, filename=filename) + return filename - def delete_backup_helper(self, backup_file): - self._delete_backup(backup_file) + def delete_backup_helper(self, filename): + self._delete_backup(filename) ##~~ CLI hook @@ -437,26 +437,24 @@ class BackupPlugin( ) if path is not None: - datafolder, backup_file = os.path.split(os.path.abspath(path)) + datafolder, filename = os.path.split(os.path.abspath(path)) else: - backup_file = self._build_backup_filename(settings=settings) + filename = self._build_backup_filename(settings=settings) datafolder = os.path.join(settings.getBaseFolder("data"), "backup") if not os.path.isdir(datafolder): os.makedirs(datafolder) - click.echo("Creating backup at {}, please wait...".format(backup_file)) + click.echo("Creating backup at {}, please wait...".format(filename)) self._create_backup( - backup_file, + filename, exclude=exclude, settings=settings, plugin_manager=cli_group.plugin_manager, datafolder=datafolder, ) click.echo("Done.") - click.echo( - "Backup located at {}".format(os.path.join(datafolder, backup_file)) - ) + click.echo("Backup located at {}".format(os.path.join(datafolder, filename))) @click.command("restore") @click.argument("path") @@ -593,9 +591,9 @@ class BackupPlugin( ##~~ helpers - def _start_backup(self, exclude, backup_file=None): - if backup_file is None: - backup_file = self._build_backup_filename(settings=self._settings) + 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( @@ -635,7 +633,7 @@ class BackupPlugin( thread = threading.Thread( target=self._create_backup, - args=(backup_file,), + args=(filename,), kwargs={ "exclude": exclude, "settings": self._settings, From 74c2ce205460ff9fdd9f506c525ccefa2831b724 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sun, 27 Dec 2020 16:18:23 +0000 Subject: [PATCH 5/6] :bug: Use isinstance instead of type https://github.com/OctoPrint/OctoPrint/pull/3866#pullrequestreview-549218212 'Better use isinstance(exclude, list) here, or we rule out anything that inherits from list.' This is also consistent with the method further down the call, at https://github.com/OctoPrint/OctoPrint/blob/280baee3a0f299366daa303ab23a1379405ebd0d/src/octoprint/plugins/backup/__init__.py#L876-L879 --- src/octoprint/plugins/backup/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 94639b8e5..76fbb506d 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -400,8 +400,10 @@ class BackupPlugin( Args: exclude (list): Identifiers of data folders to exclude """ - if exclude is None or not (type(exclude) == list): + if exclude is None: exclude = [] + if not isinstance(exclude, list): + exclude = list(exclude) self._start_backup(exclude, filename=filename) return filename From 3f8f1e598a1d96318c5595e75e6807ec23d09e17 Mon Sep 17 00:00:00 2001 From: cp2004 <31997505+cp2004@users.noreply.github.com> Date: Sun, 27 Dec 2020 17:21:31 +0000 Subject: [PATCH 6/6] :pencil: Document new backup plugin options See https://github.com/OctoPrint/OctoPrint/pull/3866#pullrequestreview-549218212 'These helpers should be documented in the docs for the backup plugin.' They are now documented :) --- docs/bundledplugins/backup.rst | 24 ++++++++++ src/octoprint/plugins/backup/__init__.py | 60 ++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst index e11c149c4..24be587e1 100644 --- a/docs/bundledplugins/backup.rst +++ b/docs/bundledplugins/backup.rst @@ -177,6 +177,30 @@ 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-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. + +.. _sec-bundledplugins-backup-helpers-create_backup: + +create_backup ++++++++++++++ + +.. autofunction:: octoprint.plugins.backup.BackupPlugin.create_backup_helper + + +.. _sec-bundledplugins-backup-helpers-delete_backup: + +delete_backup ++++++++++++++ + +.. autofunction:: octoprint.plugins.backup.BackupPlugin.delete_backup_helper + + .. _sec-bundledplugins-backup-sourcecode: Source code diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 76fbb506d..366e03883 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -396,9 +396,32 @@ class BackupPlugin( # Exported plugin helpers def create_backup_helper(self, exclude=None, filename=None): """ - Trigger a backup from a plugin or other internal call - Args: - exclude (list): Identifiers of data folders to exclude + .. versionadded:: 1.6.0 + + Create a backup from a plugin or other internal call + + This helper is exported as ``create_backup`` and can be used from the plugin + manager's ``get_helpers`` method. + + **Example** + + The following code snippet can be used from within a plugin, and will create a backup + excluding two folders (``timelapse`` and ``uploads``) + + .. code-block:: python + + helpers = self._plugin_manager.get_helpers("backup", "create_backup") + + if helpers and "create_backup" in helpers: + helpers["create_backup"](exclude=["timelapse", "uploads"]) + + By using the ``if helpers [...]`` clause, plugins can fall back to other methods + when they are running under versions where these helpers did not exist. + + + :param list exclude: Names of data folders to exclude, defaults to None + :param str filename: Name of backup to be created, if None (default) the backup + name will be auto-generated. This should use a ``.zip`` extension. """ if exclude is None: exclude = [] @@ -406,9 +429,38 @@ class BackupPlugin( exclude = list(exclude) self._start_backup(exclude, filename=filename) - return filename def delete_backup_helper(self, filename): + """ + .. versionadded:: 1.6.0 + + Delete the specified backup from a plugin or other internal call + + This helper is exported as ``delete_backup`` and can be used through the plugin + manager's ``get_helpers`` method. + + **Example** + The following code snippet can be used from within a plugin, and will attempt to + delete the backup named ``ExampleBackup.zip``. + + .. code-block:: python + + helpers = self._plugin_manager.get_helpers("backup", "delete_backup") + + if helpers and "delete_backup" in helpers: + helpers["delete_backup"]("ExampleBackup.zip") + + By using the ``if helpers [...]`` clause, plugins can fall back to other methods + when they are running under versions where these helpers did not exist. + + .. warning:: + + This method will fail silently if the backup does not exist, and so + it is recommended that you make sure the name comes from a verified source, + for example the name from the events or other helpers. + + :param str filename: The name of the backup to delete + """ self._delete_backup(filename) ##~~ CLI hook