diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..ed3f1c77a --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,25 @@ +docs: + - "docs/*" + - "docs/**/*" + - "README.md" + +meta: + - "CODE_OF_CONDUCT.md" + - "CONTRIBUTING.md" + - "SECURITY.md" + - ".github/CODEOWNERS" + - ".github/FUNDING.yml" + - ".github/ISSUE_TEMPLATE/*" + - ".github/PULL_REQUEST_TEMPLATE.md" + +ci/cd: + - ".github/fixtures/**/*" + - ".github/workflows/*" + - ".github/labeler.yml" + +docker: + - ".github/workflows/trigger_docker.yml" + +tests: + - "tests/*" + - "tests/**/*" diff --git a/.github/pr-validation.yml b/.github/pr-validation.yml new file mode 100644 index 000000000..b6644f25c --- /dev/null +++ b/.github/pr-validation.yml @@ -0,0 +1,14 @@ +approve_label: "approved" +problem_label: "needs some work" + +allowed_targets: ["maintenance", "devel", "staging/maintenance", "staging/devel"] +forbidden_sources: + ["master", "maintenance", "devel", "staging/maintenance", "staging/devel"] + +labels: + docs: + additional_allowed_targets: ["master"] + meta: + additional_allowed_targets: ["master"] + ci/cd: + additional_allowed_targets: ["master"] diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_automation.yml similarity index 97% rename from .github/workflows/issue_labeler.yml rename to .github/workflows/issue_automation.yml index 5b6e026e7..f3024d73f 100644 --- a/.github/workflows/issue_labeler.yml +++ b/.github/workflows/issue_automation.yml @@ -1,10 +1,10 @@ -name: "Issue Labeler" +name: "Issue Automation" on: issues: types: [opened, edited, closed, reopened] jobs: - label-opened-and-edited: + label: runs-on: ubuntu-latest steps: - uses: actions/github-script@v2 diff --git a/.github/workflows/pr_automation.yml b/.github/workflows/pr_automation.yml new file mode 100644 index 000000000..e770708a0 --- /dev/null +++ b/.github/workflows/pr_automation.yml @@ -0,0 +1,20 @@ +name: "Pull Request Automation" +on: + pull_request_target: + types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"] + +jobs: + label: + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v3 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" + + validate: + runs-on: ubuntu-latest + needs: label + steps: + - uses: OctoPrint/actions/pr-validation@main + with: + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/trigger_docker.yml b/.github/workflows/trigger_docker.yml index 0b4553545..1a86bb0c6 100644 --- a/.github/workflows/trigger_docker.yml +++ b/.github/workflows/trigger_docker.yml @@ -19,7 +19,7 @@ jobs: with: token: ${{ secrets.DOCKER_ACCESS_TOKEN }} repository: ${{ github.repository_owner }}/octoprint-docker - event-type: ${{ github.event_name }} + event-type: ${{ github.event.action }} client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}' dispatch_canary: @@ -32,7 +32,7 @@ jobs: token: ${{ secrets.DOCKER_ACCESS_TOKEN }} repository: ${{ github.repository_owner }}/octoprint-docker event-type: "canary" - client-payload: '{"tag_name": "${{ github.sha }}"}' + client-payload: '{"tag_name": "maintenance"}' dispatch_bleeding: runs-on: ubuntu-latest @@ -44,4 +44,4 @@ jobs: token: ${{ secrets.DOCKER_ACCESS_TOKEN }} repository: ${{ github.repository_owner }}/octoprint-docker event-type: "bleeding" - client-payload: '{"tag_name": "${{ github.sha }}"}' + client-payload: '{"tag_name": "devel"}' diff --git a/AUTHORS.md b/AUTHORS.md index a50ec706b..f7477841b 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -130,6 +130,9 @@ date of first contribution): * [Sophist](https://github.com/Sophist-UK) * [Manuel McLure](https://github.com/ManuelMcLure) * ["j7126"](https://github.com/j7126) + * ["coliss86"](https://github.com/coliss86) + * ["MichaIng"](https://github.com/MichaIng) + * ["jasonbcox"](https://github.com/jasonbcox) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/docs/bundledplugins/action_command_notification.rst b/docs/bundledplugins/action_command_notification.rst index fb3b50277..d2b5a005c 100644 --- a/docs/bundledplugins/action_command_notification.rst +++ b/docs/bundledplugins/action_command_notification.rst @@ -10,7 +10,7 @@ The OctoPrint Action Command Notification Support Plugin comes bundled with Octo It allows firmware to trigger notifications users with the ``PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW`` permission using :ref:`action commands ` about relevant events. These notifications will be shown in the sidebar and if configured also as popup messages. The notifications in the sidebar panel can also be cleared -by users with the ``PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR` permission. +by users with the ``PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR`` permission. .. _fig-bundledplugins-action_command_notification-example: .. figure:: ../images/bundledplugins-action_command_notification-example.png diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst index 9064e3392..6dd70358c 100644 --- a/docs/bundledplugins/backup.rst +++ b/docs/bundledplugins/backup.rst @@ -171,6 +171,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/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 7b8a949eb..56a0a5fce 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -30,7 +30,7 @@ Use the following settings to enable access control: userManager: octoprint.access.users.FilebasedUserManager # The YAML user file to use. If left out defaults to users.yaml in the default configuration folder. - userFile: /path/to/users.yaml + userfile: /path/to/users.yaml # If set to true, will automatically log on clients originating from any of the networks defined in # "localNetworks" as the user defined in "autologinAs". Defaults to false. diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index 9647d31f9..23bf90b75 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -3,7 +3,7 @@ Access Control ============== -.. versionchanged:: 1.4.0 +.. versionchanged:: 1.5.0 OctoPrint's bundled access control feature allows granular permission control over which users or user groups are allowed to access which parts of OctoPrint. @@ -17,8 +17,17 @@ users out of the box. thus also cannot limit access to it. If an anonymous user correctly guesses the webcam URL, they will thus be able to see it. -If read-only access for anonymous users is enabled, anonymous users will have -read-only access to the following parts of the UI: +Upon first start a configuration wizard is provided which allows configuration +of the first administrator account to be used for OctoPrint. After initial setup, +you can then create more users and groups under Settings > Access Control for +customisation of the granular permission system. + +The predefined "Guests" group can be used to configure default permissions of anonymous +users, that is those who have not logged in. By default, no permissions are granted to +these users. + +A predefined "Read-only Access" group with no users is configured which by default grants +read-only access to the following parts of the UI to any users assigned to this group: * printer state * available gcode files and stats (upload is disabled) @@ -30,29 +39,195 @@ read-only access to the following parts of the UI: * any components provided through plugins which are enabled for anonymous users -Logged in users without admin flag will be allowed to access everything besides the -Settings and System Commands, which are admin-only. +Another predefined "Operator" group is the default group for newly created users and +by default gives access to all aspects of OctoPrint that involve regular printer +operation. It matches the old "user" role from OctoPrint prior to 1.4.0. -If Access Control is disabled, everything is directly accessible. **That also -includes all administrative functionality as well as full control over the -printer**, and without the need for an :ref:`API key `! - -Upon first start a configuration wizard is provided which allows configuration -of the first administrator account or alternatively disabling Access Control -(which is **NOT** recommended for systems that are directly accessible via the -internet or other untrusted networks!). +Finally, the predefined "Admins" group gives full admin access to the platform. You should +be careful of who you put into that. It matches the old "admin" role from OctoPrint prior +to 1.4.0. .. hint:: If you plan to have your OctoPrint instance accessible over the internet, - **always enable Access Control** and ideally **don't make it accessible to + **please use additional security measures** and ideally **don't make it accessible to everyone over the internet but instead use a VPN** or at the very least - HTTP basic authentication on a layer above OctoPrint. + HTTP basic authentication on a layer above OctoPrint. Unless you are using a VPN + **please do not** enable any permissions for the Guest group or the auto-login feature + described below. A physical device that includes heaters and stepper motors really should not be publicly reachable by everyone with an internet connection, even with access control enabled. +.. _sec-features-access_control-autologin: + +Autologin +--------- + +While access control cannot be disabled as of OctoPrint 1.5+, the Autologin feature can +be used to bypass authentication for hosts on the network(s) that you trust. + +Starting with OctoPrint 1.5.0, OctoPrint makes enabled access control mandatory. This +might be an inconvience for some who run OctoPrint in an isolated setup where a login is +not required to ensure security, at a benefit for a huge number of users out there who +continue to underestimate or simply ignore the risk of keeping their OctoPrint instance +unsecured and then happily exposing it on the public internet. + +That being said, even as far back as OctoPrint 1.0.0 (released in 2013) there has existed +a way to have OctoPrint automatically log you in, if you connect from a trusted local +network address. This functionality has not been exposed on the UI, and for now also won't +be (to make it a bit harder to once again create an insecure setup for those who simply +won't listen to common sense), but it's easy to set up with a bit of configuration +editing. + +When set up properly, it will make sure to automatically log you in as a configured user +whenever you connect from a device on your local network. To get back pretty much the same +behaviour as with disabled access control, you'll only need to create a single (admin) +account and then set up autologin for it. + + +.. warning:: + + **Do not do this if you cannot trust EVERYONE on your local network.** And that really + means mean everyone. If you ignore this and then someone takes over your OctoPrint + instance, installs malware on it and makes your printer print an endless stream of + benchies, that's on you. + +.. _sec-features-access_control-autologin-gather_config_info: + +Gather configuration information +................................ + +You can configure Autologin via a plugin (the easy way), or manually (the hard way), but +in either case you will need to specify which user should be automatically logged in, and +which hosts are permitted access this way. + +**Improperly setting this subnet option can lead to the compromise of your system, or even +your entire network. Proceed with extreme caution.** + +The subnet to use is usually the IP address range of your LAN, which sounds scary but +actually isn't. Just `figure out your PC's IP address and subnet mask `_ +and then combine both with a / in between. + +On OctoPi (or another Linux distribution) you can use the follwing command: + +.. code-block:: + + ip route | grep -P 'eth0|wlan0' | awk '{print $1}' + +Or, for IPv6, use this: + +.. code-block:: + + ip -6 route | grep -P 'eth0|wlan0' | awk '{print $1}' + +This will be what you set as the subnet in the plugin, or where it says +```` below on the manual configuration instructions. + +Example: Your PC has an IP address of ``192.168.23.42`` and a subnet mask of +``255.255.255.0``. Your address range is ``192.168.23.42/255.255.255.0``. + +.. _sec-features-access_control-autologin-plugin: + +The easy way: Using the OctoPrint-AutoLoginConfig plugin +........................................................ + +The easist way to configure AutoLogin is to install the +`OctoPrint-AutoLoginConfig plugin `_ +via the plugin manager. + +Open its settings and follow the instructions on the screen. + +.. _sec-features-access_control-autologin-manual: + +The hard way: Manual editing of config.yaml +........................................... + +Preparation +*********** + +First of all, read :ref:`the YAML primer `. You +will have to edit OctoPrint's main configuration file, and thus should make sure +you understand at least roughly how things work and that you should keep your +hands off the Tab key. If you don't, you might break your config file, and +while the steps include making a backup, this still can be easily avoided by +learning about the DOs and DONTs first. + +Then, take a look at :ref:`the docs on config.yaml ` +on where to find that central configuration file of OctoPrint. + +Configuration +************* + +Ready? Let's do some editing then. I'll outline what to do and where first, and then +further down there's also a dedicated list of steps for OctoPi specifically. + +1. Shutdown OctoPrint +2. Make a backup of your config.yaml +3. Open it in a text editor (e.g. nano). Right at the very top it'll say something like + this: + + .. code-block:: yaml + + accessControl: + salt: aabbccddee1234523452345 + + Edit this, adding lines so it looks like this (making absolutely sure not to touch the + salt line): + + .. code-block:: yaml + accessControl: + salt: aabbccddee1234523452345 + autologinLocal: true + autologinAs: "" + localNetworks: + - "127.0.0.0/8" + - "" + +4. Restart OctoPrint, check that everything works. + +This will automatically log you in as the user you specified whenver you connect to +OctoPrint from an address in the address range (e.g. a device on your local network). + +OctoPi specific steps +********************* + +If you are running OctoPi you will have to SSH into your Raspberry Pi. Then issue +the following commands: + +1. ``sudo service octoprint stop`` +2. ``cp ~/.octoprint/config.yaml ~/.octoprint/config.yaml.back`` +3. ``nano ~/.octoprint/config.yaml, make the edits as described above`` +4. ``sudo service octoprint start`` + +If something went wrong, you can restore the config backup with + +.. code-block:: + + cp ~/.octoprint/config.yaml.back ~/.octoprint/config.yaml + + +If you are using a VPN and your setup ABSOLUTELY REQUIRES disabling internal OctoPrint access controls +...................................................................................................... + +.. warning:: + + You probably shouldn't do this, EVER. There are usually other options. Don't even + THINK about it, unless you have a VPN layer for security. Only consider proceeding + with this configuration after exhausting ALL other possibilities, and even then, you + should think long and hard about whether this is a good idea. You almost certainly + don't need or want to do this. + +While access controls can no longer be disabled in OctoPrint 1.5+, this can be +approximated by an Autologin configuration that automatically logs in all users, that is +by using subnets that match all possible IP addresses. By specifying the ``0.0.0.0/0`` +subnet (for IPv4) and ``::/0`` for IPv6 in the AutoLogin configuration, you can achieve +this. This configuration is permitted, but highly, highly discouraged. + +Please don't do this. You will almost certainly regret it. You alone are responsible for +your actions. + .. _sec-features-access_control-hooks: Available Extension Hooks @@ -71,42 +246,7 @@ See :ref:`here `. .. _sec-features-access_control-hooks-loginui: -octoprint.plugin.loginui.theming -................................ +octoprint.theming.login +....................... -See :ref:`here `. - -.. _sec-features-access_control-rerunning_wizard: - -Rerunning the wizard --------------------- - -In case Access Control was disabled in the configuration wizard, it is -possible to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun`` -in the ``server`` section and ``enabled`` in the ``accessControl`` section to -``true``: - -.. code-block:: yaml - - accessControl: - enabled: true - # ... - server: - firstRun: true - -Then restart the server and connect to the web interface - the wizard should -be shown again. - -.. note:: - - If user accounts were created prior to disabling Access Control and those - user accounts are not to be used any more, remove ``.octoprint/users.yaml``. - If you don't remove this file, the above changes won't lead to the - configuration being shown again, instead Access Control will just be - enabled using the already existing login data. This is to prevent you from - resetting access control by accident. - -.. rubric:: Footnotes - -.. [#f1] For Linux that will be ``~/.octoprint/config.yaml``, for Windows it will be ``%APPDATA%/OctoPrint/config.yaml`` and for - Mac ``~/Library/Application Support/OctoPrint/config.yaml`` +See :ref:`here `. diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 5863c034b..eb52fbec4 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -1173,15 +1173,6 @@ octoprint.plugin.backup.additional_excludes See :ref:`here `. -.. _sec-plugins-hook-plugin-loginui-theming: - -octoprint.plugin.loginui.theming -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.4.0 - -See :ref:`here `. - .. _sec-plugins-hook-plugin-pluginmanager-reconnect: octoprint.plugin.pluginmanager.reconnect_hooks diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index dc8d9cace..91759647f 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -259,6 +259,10 @@ onUserSettingsShown() onUserSettingsHidden() Called when the user settings dialog is hidden. +onUserSettingsBeforeSave() + Called just before the user settings view model is sent to the server. This is useful, for example, if your plugin + needs to compute persisted settings from a custom view model. + onWizardDetails(response) Called with the response from the wizard detail API call initiated before opening the wizard dialog. Will contain the data from all :class:`~octoprint.plugin.WizardPlugin` implementations returned by their :meth:`~octoprint.plugin.WizardPlugin.get_wizard_details` diff --git a/scripts/octoprint.service b/scripts/octoprint.service index 14f5d7f4b..ae5405c34 100644 --- a/scripts/octoprint.service +++ b/scripts/octoprint.service @@ -6,7 +6,7 @@ Wants=network-online.target [Service] Environment="LC_ALL=C.UTF-8" Environment="LANG=C.UTF-8" -Type=simple +Type=exec User=pi ExecStart=/home/pi/OctoPrint/venv/bin/octoprint diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 index 0a9d041e5..c9f903f73 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 @@ -1,3 +1,3 @@ diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index 2e015853f..75720f39a 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -31,7 +31,7 @@ $(function () { 5 ); - self.unread = ko.observable(); + self.unread = ko.observable(false); self.hiddenChannels = []; self.channelNotifications = {}; diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 302e5e238..58eabd31d 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -162,65 +162,14 @@ 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", []) + 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 "-" - ) - ) + self._start_backup(exclude, filename) - 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() - - response = flask.jsonify(started=True, name=backup_file) + response = flask.jsonify(started=True, name=filename) response.status_code = 201 return response @@ -228,18 +177,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"]) @@ -448,6 +387,76 @@ 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, filename=None): + """ + .. 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 = [] + if not isinstance(exclude, list): + exclude = list(exclude) + + self._start_backup(exclude, filename=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 def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): @@ -476,26 +485,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") @@ -632,6 +639,82 @@ 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}) + + 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=(filename,), + 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 _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()): @@ -1325,3 +1408,7 @@ __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, + "delete_backup": __plugin_implementation__.delete_backup_helper, +} diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 index 6d8a71898..d8715540e 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 @@ -11,7 +11,7 @@ OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here. {% endtrans %}

-
+ {% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
@@ -21,7 +21,7 @@ trust and that has a high availability. {% endtrans %}

-
+ {% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %} {% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %} {% include "snippets/settings/server/serverOnlineCheckTestConnectivity.jinja2" %} @@ -34,7 +34,7 @@ side with the general connectivity check, leave the field empty. {% endtrans %}

- +
{% include "snippets/settings/server/serverOnlineCheckName.jinja2" %} {% include "snippets/settings/server/serverOnlineCheckTestResolution.jinja2" %} @@ -47,8 +47,12 @@ {% endtrans %}