diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f0e72cdc..10b6ee08c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,64 @@ # OctoPrint Changelog +## 1.3.0rc2 (2016-11-24) + +### Features + + * OctoPrint will now track the current print head position on pause and cancel and provide it as new template variables ``pause_position``/``cancel_position`` for the relevant GCODE scripts. This will allow more intelligent pause codes that park the print head at a rest position during pause and move it back to the exact position it was before the pause on resume ([Example](https://gist.github.com/foosel/1c09e269b1c0bb7a471c20eef50c8d3e)). Note that this is NOT enabled by default and for now will necessitate adjusting the pause and resume GCODE scripts yourself since position tracking with multiple extruders or when printing from SD is currently not fool proof thanks to firmware limitations regarding reliable tracking of the various ``E`` values and the currently selected tool ``T``. In order to fully implement this feature, the following improvements were also done: + * New ``PositionUpdated`` event when OctoPrint receives a response to an ``M114`` position query. + * Extended ``PrintPaused`` and ``PrintCancelled`` events with position data from ``M114`` position query on print interruption/end. + * Added (optional) firmware auto detection. If enabled (which it is by default), OctoPrint will now send an ``M115`` to the printer on initial connection in order to try to figure out what kind of firmware it is. For FIRMWARE_NAME values containing "repetier" (case insensitive), all Repetier-specific flags will be set on the comm layer. For FIRMWARE_NAME values containing "reprapfirmware" (also case insensitive), all RepRapFirmware-specific flags will be set on the comm layer. For now no other handling will be performed. + * Added safe mode flag ``--safe`` and config setting ``startOnceInSafeMode`` that disables all third party plugins when active. The config setting will automatically be removed from `config.yaml` after the server has started through successfully. + * Added ``octoprint config`` CLI that allows easier manipulation of config.yaml entries from the command line. Example: ``octoprint config set --bool server.startOnceInSafeMode true`` + +### Improvements + + * [#1422](https://github.com/foosel/OctoPrint/issues/1422) - Added option for post roll for timed timelapse to duplicate last frame instead of capturing new frames. That makes for a faster render at the cost of a still frame at the end of the rendered video. See also [#1553](https://github.com/foosel/OctoPrint/pull/1553). + * [#1551](https://github.com/foosel/OctoPrint/issues/1551) - Allow to define a custom bounding box for valid printer head movements in the printer profile, to make print dimension check more flexible. + * [#1583](https://github.com/foosel/OctoPrint/pull/1583) - Strip invalid `pip` arguments from `pip uninstall` commands, if provided by the user as additional pip arguments. + * [#1593](https://github.com/foosel/OctoPrint/issues/1593) - Automatically migrate old manual system commands for restarting OctoPrint and rebooting or shutting down the server to the new system wide configuration settings. Make a backup copy of the old `config.yaml` before doing so in case a manual rollback is required. + * Support ``M114`` responses without whitespace between coordinates (protocol consistency - who needs it?). + * Don't focus files in the file list after deleting a file - made the list too jumpy. + * Better error resilience against errors in UI components. + * `M600` is now marked as a long running command by default. + * Plugin Manager: Allow closing of all notifications and close them automatically on detected server disconnect. No need to keep a "Restart needed" message around if a restart is in progress. + * Software Update: "busy" spinner on check buttons while already checking for updates. + * Software Update: Prevent update notification when wizard is open. + * Plugin Manager / Software Update: The "There's a new version of pip" message during plugin installs and software updates is no longer displayed like an error. + * Plugin Manager / Software Update: The "busy" dialog can no longer be closed accidentally. + +### Bug fixes + + * [#1148](https://github.com/foosel/OctoPrint/issues/1148) - Fixed retraction z hop setting for Z-triggered timelapses. Was not correctly propagated to the backend and hence not taking effect. + * [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Invalidate ``/api/settings`` cache on change of the user's login state (include user roles into ETag calculation). + * [#1586](https://github.com/foosel/OctoPrint/issues/1586) - Fixed incompatibility of update script and command line helper with non-ASCII output from called commands. + * [#1588](https://github.com/foosel/OctoPrint/issues/1588) - Fixed feedback controls again. + * Invalidate ``/api/settings`` cache on change of the currently enabled plugins (by including plugin names into ETag calculation) and/or on change of the current effective config. + * Invalidate ``/api/timelapse`` cache on change of the current timelapse configuration. + * Fixed an issue causing the version number not to be properly extracted from ``sdist`` tarballs generated under Windows. + * Get rid of double scroll bar in printer profile editor. + * Fixed tracking of current byte position in file being streamed from disk. Turns out that ``self._handle.tell`` lied to us thanks to line buffering. + * Fixed select & print not working anymore for SD files thanks to a timing issue. + * Fixed ``PrintFailed`` event payload (was still missing new folder relevant data). + * Fixed premature parse stop on ``M114`` and ``M115`` responses with ``ok``-prefix. + * Make sure `?l10n` request parameter gets also propagated to API calls as `X-Locale` header in case of locale sensitive API responses. + * Fix language mixture due to cached template configs including localized strings; cache per locale. + * Only insert divider in system menu after core commands if there are custom commands. + * Fix update of webcam stream URL not being applied due to caching. + * Fixed a rare race condition causing the new "The settings changed, reload?" popup to show up even when the settings change originated in the same client instance. + * Fixed a bunch of missing translations. + * Pinned Tornado version to 4.0.2. Former version requirement was able to pull in a beta version causing issues with websockets due to a bug in `permessage-deflate` handling. The Tornado requirement needs an update, but we'll leave it at 4.0.2 for 1.3.0 since we'll need to do some migration work for compatibility with anything newer. Potentially related to [#1523](https://github.com/foosel/OctoPrint/issues/1523). + +### Changes from `maintenance` not yet released as part of a stable release + +#### Bug fixes + + * [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first. + * [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses + * Fix issue with settings restriction causing internal settings defaults to be changed. + +([Commits](https://github.com/foosel/OctoPrint/compare/1.3.0rc1...1.3.0rc2)) + ## 1.3.0rc1 (2016-10-19) ### New Features @@ -104,6 +163,24 @@ ([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.3.0rc1)) +## 1.2.18rc1 (2016-11-22) + +### Improvements + + * Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate. + * Limited Cura profile importer to `.ini` files and clarified the supported versions + * Add support for the `R` parameter for `M109` and `M190` + +### Bug fixes + + * [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default + * [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer + * [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first. + * [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses + * Fix issue with settings restriction causing internal settings defaults to be changed. + +([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17...1.2.18)) + ## 1.2.17 (2016-11-08) ### Improvements diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 7d85c2dd5..15b831e09 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -33,27 +33,22 @@ thanks to everyone who contributed! * Gary Deen * Gary N McKinney * George Robles - * Gregor Lütolf * J. Eckert * Jason Galarneau - * Joe Korzeniewski * Josh Daniels * Joshua David Gregory * Kaile Riser * Kale Stedman * Kazuhiro Ogura - * Korneel Bullens * Lamin Kivelä * M Khorakiwala * Makespace Madrid - * Mark Lane * Mark Qvist * Mark Walker * Masayoshi Mitsui * Michael Aumock * Michael McDargh Sr * Miles Flavel - * Nikolai Langer * Noe Ruiz * Patrick McGinnis * Peter Grace @@ -68,10 +63,11 @@ thanks to everyone who contributed! * Shane Ekerbicer * Simon Hallam * Stefan Krister + * Stephane Schittly * Steven Pearson * Sven Mueller * Terrance Shaw * Thomas Hatley * Trent Shumay -and 968 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! +and 989 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! diff --git a/docs/events/index.rst b/docs/events/index.rst index 0b0139c90..802ed3856 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -308,6 +308,17 @@ PrintCancelled * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``position``: the print head position at the time of cancelling, if available + * ``position.x``: x coordinate, as reported back from the firmware through `M114` + * ``position.y``: y coordinate, as reported back from the firmware through `M114` + * ``position.z``: z coordinate, as reported back from the firmware through `M114` + * ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114` + * ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected + tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT + be accurate) + * ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the + feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will + NOT be accurate) .. deprecated:: 1.3.0 @@ -324,6 +335,17 @@ PrintPaused * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``position``: the print head position at the time of pausing, if available + * ``position.x``: x coordinate, as reported back from the firmware through `M114` + * ``position.y``: y coordinate, as reported back from the firmware through `M114` + * ``position.z``: z coordinate, as reported back from the firmware through `M114` + * ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114` + * ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected + tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT + be accurate) + * ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the + feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will + NOT be accurate) .. deprecated:: 1.3.0 @@ -352,37 +374,53 @@ GCODE processing ---------------- PowerOn - The GCode has turned on the printer power via M80 + An ``M80`` was sent to the printer through OctoPrint (not triggered when printing from SD!) PowerOff - The GCODE has turned on the printer power via M81 + An ``M81`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Home - The head has gone home via G28 + A ``G28`` was sent to the printer through OctoPrint (not triggered when printing from SD!) ZChange - The printer's Z-Height has changed (new layer) + The printer's Z-Height has changed (new layer) through a ``G0`` or ``G1`` that was sent to the printer through OctoPrint + (not triggered when printing from SD!) -Paused - The print has been paused +Dwell + A ``G4`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Waiting - The print is paused due to a gcode wait command + One of the following commands was sent to the printer through OctoPrint (not triggered when printing from SD!): + ``M0``, ``M1``, ``M226`` Cooling - The GCODE has enabled the platform cooler via M245 + An ``M245`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Alert - The GCODE has issued a user alert (beep) via M300 + An ``M300`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Conveyor - The GCODE has enabled the conveyor belt via M240 + An ``M240`` was sent to the printer through OctoPrint (not triggered when printing from SD!) Eject - The GCODE has enabled the part ejector via M40 + An ``M40`` was sent to the printer through OctoPrint (not triggered when printing from SD!) EStop - The GCODE has issued a panic stop via M112 + An ``M112`` was sent to the printer through OctoPrint (not triggered when printing from SD!) + +PositionUpdate + The response to an ``M114`` was received by OctoPrint. The payload contains the current position information + parsed from the response and (in the case of the selected tool ``t`` and the current feedrate ``f``) tracked + by OctoPrint. + + Payload: + + * ``x``: x coordinate, parsed from response + * ``y``: y coordinate, parsed from response + * ``z``: z coordinate, parsed from response + * ``e``: e coordinate, parsed from response + * ``t``: last tool selected *through OctoPrint* + * ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint* Timelapses ---------- diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index 86b7d8c22..579edbdfc 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -60,9 +60,36 @@ All GCODE scripts have access to the following template variables through the te * ``printer_profile``: The currently selected Printer Profile, including information such as the extruder count, the build volume size, the filament diameter etc. + * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!) * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` and ``script.name`` respectively. +There are a couple of additional template variables available for the following specific scripts: + + * ``afterPrintPaused`` and ``beforePrintResumed`` + * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists + of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool + ``t`` taken from commands sent through OctoPrint. + * ``afterPrintCancelled`` + * ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled. + Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and + current tool ``t`` taken from commands sent through OctoPrint. + +.. warning:: + + Note that current firmware implementations only report back one ``E`` value, the current extrusion value for the current + extruder. Retrieving all ``E`` values by cycling through all extruders on pause and cancel is something OctoPrint + currently does NOT do since it would simply take too long. That means that if you want to write a ``beforePrintResumed`` + script that basically resets everything back to the point when the printer was paused *and* you are running with + multiple extruders, you'll have to find some other way to have your ``E`` values set correctly for all your available + extruders - the data available in ``pause_position`` will *not* suffice. Additionally, most firmwares don't report + the currently selected tool in the ``M114`` response, meaning that the only way OctoPrint can keep track of that is + by tracking it itself. Same goes for the current feed rate ``F``. So if you are printing from SD, this data will be + *wrong*. This is also the reason why OctoPrint currently doesn't bundle a more sophisticated pause and resume script + that would actually move the print head out of the way and pause and back to the original position on resume - it + might cause issues for the multitude of users out there with multi-extruder setups or for people printing from the + printer's SD, thanks to the lack of information the firmware provides. + The :ref:`predefined GCODE scripts ` are also called with the following additional template variables: diff --git a/docs/jsclientlib/base.rst b/docs/jsclientlib/base.rst index e59cca695..65a56340c 100644 --- a/docs/jsclientlib/base.rst +++ b/docs/jsclientlib/base.rst @@ -14,6 +14,10 @@ ``OctoPrint.options.baseurl`` The base URL of the OctoPrint API + ``OctoPrint.options.locale`` + The locale to set in ``X-Locale`` headers on API requests. Useful for API + endpoints that might return localized content. + .. js:data:: OctoPrint.plugins Registration of client library components provided by plugins. diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 389fd2245..ebf1ffbd8 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -18,10 +18,6 @@ __revision__ = versions.get('full-revisionid', versions.get('full', None)) del versions del get_versions -#~~ sane logging defaults - -log.basicConfig() - #~~ try to ensure a sound SSL environment urllib3_ssl = True @@ -61,10 +57,21 @@ class FatalStartupError(BaseException): def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, logging_config=None, debug=False, verbosity=0, uncaught_logger=None, - uncaught_handler=None, after_settings=None, after_logging=None): + uncaught_handler=None, safe_mode=False, after_preinit_logging=None, + after_settings=None, after_logging=None, after_safe_mode=None): + kwargs = dict() + + logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler) + kwargs["logger"] = logger + kwargs["recorder"] = recorder + + if callable(after_preinit_logging): + after_preinit_logging(**kwargs) + settings = init_settings(basedir, configfile) + kwargs["settings"] = settings if callable(after_settings): - after_settings(settings) + after_settings(**kwargs) logger = init_logging(settings, use_logging_file=use_logging_file, @@ -74,11 +81,20 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, verbosity=verbosity, uncaught_logger=uncaught_logger, uncaught_handler=uncaught_handler) - if callable(after_logging): - after_logging(logger) + kwargs["logger"] = logger - plugin_manager = init_pluginsystem(settings) - return settings, logger, plugin_manager + if callable(after_logging): + after_logging(**kwargs) + + settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"]) + safe_mode = safe_mode or settings_safe_mode + kwargs["safe_mode"] = safe_mode + + if callable(after_safe_mode): + after_safe_mode(**kwargs) + + plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode) + return settings, logger, safe_mode, plugin_manager def init_settings(basedir, configfile): @@ -94,6 +110,45 @@ def init_settings(basedir, configfile): raise FatalStartupError(message) +def preinit_logging(debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): + config = { + "version": 1, + "formatters": { + "simple": { + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + } + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": "DEBUG", + "formatter": "simple", + "stream": "ext://sys.stdout" + } + }, + "loggers": { + "octoprint": { + "level": "DEBUG" if debug else "INFO" + }, + "octoprint.util": { + "level": "INFO" + } + }, + "root": { + "level": "WARN", + "handlers": ["console"] + } + } + + logger = set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + + from octoprint.logging.handlers import RecordingLogHandler + recorder = RecordingLogHandler(level=log.DEBUG) + log.getLogger().addHandler(recorder) + + return logger, recorder + + def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): """Sets up logging.""" @@ -182,6 +237,11 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con else: config = default_config + # configure logging globally + return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler) + + +def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler): # configure logging globally import logging.config as logconfig logconfig.dictConfig(config) @@ -207,19 +267,45 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con if uncaught_handler is None: def exception_logger(exc_type, exc_value, exc_tb): logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + uncaught_handler = exception_logger sys.excepthook = uncaught_handler return logger -def init_pluginsystem(settings): +def init_pluginsystem(settings, safe_mode=False): """Initializes the plugin manager based on the settings.""" - from octoprint.plugin import plugin_manager - pm = plugin_manager(init=True, settings=settings) + import os logger = log.getLogger(__name__) + + plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True), + settings.getBaseFolder("plugins")] + plugin_entry_points = ["octoprint.plugin"] + plugin_disabled_list = settings.get(["plugins", "_disabled"]) + + plugin_validators = [] + if safe_mode: + def validator(phase, plugin_info): + if phase == "after_load": + setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled) + setattr(plugin_info, "safe_mode_enabled", False) + elif phase == "before_enable": + if not plugin_info.bundled: + setattr(plugin_info, "safe_mode_enabled", True) + return False + return True + plugin_validators.append(validator) + + from octoprint.plugin import plugin_manager + pm = plugin_manager(init=True, + plugin_folders=plugin_folders, + plugin_entry_points=plugin_entry_points, + plugin_disabled_list=plugin_disabled_list, + plugin_validators=plugin_validators) + settings_overlays = dict() disabled_from_overlays = dict() diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 43923eff9..826ebbc0f 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -13,10 +13,11 @@ import octoprint class OctoPrintContext(object): """Custom context wrapping the standard options.""" - def __init__(self, configfile=None, basedir=None, verbosity=0): + def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False): self.configfile = configfile self.basedir = basedir self.verbosity = verbosity + self.safe_mode = safe_mode pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True) """Decorator to pass in the :class:`OctoPrintContext` instance.""" @@ -95,6 +96,8 @@ def standard_options(hidden=False): help="Specify the config file to use."), factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Increase logging verbosity"), + factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Enable safe mode; disables all third party plugins") ] return bulk_options(options) @@ -120,9 +123,10 @@ from .server import server_commands from .plugins import plugin_commands from .dev import dev_commands from .client import client_commands +from .config import config_commands @click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection, - sources=[server_commands, plugin_commands, dev_commands, client_commands]) + sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands]) @standard_options() @legacy_options @click.version_option(version=octoprint.__version__) diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py new file mode 100644 index 000000000..de0250cd6 --- /dev/null +++ b/src/octoprint/cli/config.py @@ -0,0 +1,221 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import click +import logging + +from octoprint import init_settings, FatalStartupError +from octoprint.cli import pass_octoprint_ctx, standard_options, bulk_options + +import yaml +import json +import pprint + +def _to_settings_path(path): + if not isinstance(path, (list, tuple)): + path = filter(lambda x: x, map(lambda x: x.strip(), path.split("."))) + return path + +def _set_helper(settings, path, value, data_type=None): + path = _to_settings_path(path) + + method = settings.set + if data_type is not None: + name = None + if data_type == bool: + name = "setBoolean" + elif data_type == float: + name = "setFloat" + elif data_type == int: + name = "setInt" + + if name is not None: + method = getattr(settings, name) + + method(path, value) + settings.save() + +#~~ "octoprint config" commands + +@click.group() +def config_commands(): + pass + +@config_commands.group(name="config") +@pass_octoprint_ctx +@click.pass_context +def config(ctx, obj): + """Basic config manipulation.""" + logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN) + try: + obj.settings = init_settings(obj.basedir, obj.configfile) + except FatalStartupError as e: + click.echo(e.message, err=True) + click.echo("There was a fatal error initializing the client.", err=True) + ctx.exit(-1) + + +@config.command(name="set") +@standard_options(hidden=True) +@click.argument("path", type=click.STRING) +@click.argument("value", type=click.STRING) +@click.option("--bool", "as_bool", is_flag=True, + help="Interpret value as bool") +@click.option("--float", "as_float", is_flag=True, + help="Interpret value as float") +@click.option("--int", "as_int", is_flag=True, + help="Interpret value as int") +@click.option("--json", "as_json", is_flag=True, + help="Parse value from json") +@pass_octoprint_ctx +@click.pass_context +def set_command(ctx, obj, path, value, as_bool, as_float, as_int, as_json): + """Sets a config path to the provided value.""" + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) + + data_type = None + if as_bool: + data_type = bool + elif as_float: + data_type = float + elif as_int: + data_type = int + + _set_helper(obj.settings, path, value, data_type=data_type) + + +@config.command(name="remove") +@standard_options(hidden=True) +@click.argument("path", type=click.STRING) +@pass_octoprint_ctx +def remove_command(obj, path): + """Removes a config path.""" + _set_helper(obj.settings, path, None) + + +@config.command(name="append_value") +@standard_options(hidden=True) +@click.argument("path", type=click.STRING) +@click.argument("value", type=click.STRING) +@click.option("--json", "as_json", is_flag=True) +@pass_octoprint_ctx +@click.pass_context +def append_value_command(ctx, obj, path, value, as_json=False): + """Appends value to list behind config path.""" + path = _to_settings_path(path) + + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) + + current = obj.settings.get(path) + if current is None: + current = [] + if not isinstance(current, list): + click.echo("Cannot append to non-list value at given path", err=True) + ctx.exit(-1) + + current.append(value) + _set_helper(obj.settings, path, current) + + +@config.command(name="insert_value") +@standard_options(hidden=True) +@click.argument("path", type=click.STRING) +@click.argument("index", type=click.INT) +@click.argument("value", type=click.STRING) +@click.option("--json", "as_json", is_flag=True) +@pass_octoprint_ctx +@click.pass_context +def insert_value_command(ctx, obj, path, index, value, as_json=False): + """Inserts value at index of list behind config key.""" + path = _to_settings_path(path) + + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) + + current = obj.settings.get(path) + if current is None: + current = [] + if not isinstance(current, list): + click.echo("Cannot insert into non-list value at given path", err=True) + ctx.exit(-1) + + current.insert(index, value) + _set_helper(obj.settings, path, current) + + +@config.command(name="remove_value") +@standard_options(hidden=True) +@click.argument("path", type=click.STRING) +@click.argument("value", type=click.STRING) +@click.option("--json", "as_json", is_flag=True) +@pass_octoprint_ctx +@click.pass_context +def remove_value_command(ctx, obj, path, value, as_json=False): + """Removes value from list at config path.""" + path = _to_settings_path(path) + + if as_json: + try: + value = json.loads(value) + except Exception as e: + click.echo(e.message, err=True) + ctx.exit(-1) + + current = obj.settings.get(path) + if current is None: + current = [] + if not isinstance(current, list): + click.echo("Cannot remove value from non-list value at given path", err=True) + ctx.exit(-1) + + if not value in current: + click.echo("Value is not contained in list at given path") + ctx.exit() + + current.remove(value) + _set_helper(obj.settings, path, current) + + +@config.command(name="get") +@click.argument("path", type=click.STRING) +@click.option("--json", "as_json", is_flag=True, + help="Output value formatted as JSON") +@click.option("--yaml", "as_yaml", is_flag=True, + help="Output value formatted as YAML") +@click.option("--raw", "as_raw", is_flag=True, + help="Output value as raw string representation") +@standard_options(hidden=True) +@pass_octoprint_ctx +def get_command(obj, path, as_json=False, as_yaml=False, as_raw=False): + """Retrieves value from config path.""" + path = _to_settings_path(path) + value = obj.settings.get(path, merged=True) + + if as_json: + output = json.dumps(value) + elif as_yaml: + output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True) + elif as_raw: + output = value + else: + output = pprint.pformat(value) + + click.echo(output) diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index e28c3ee65..44d60952b 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -51,7 +51,7 @@ class OctoPrintPluginCommands(click.MultiCommand): from octoprint import init_settings, init_pluginsystem, FatalStartupError try: self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile) - self.plugin_manager = init_pluginsystem(self.settings) + self.plugin_manager = init_pluginsystem(self.settings, safe_mode=ctx.obj.safe_mode) except FatalStartupError as e: click.echo(e.message, err=True) click.echo("There was a fatal error initializing the settings or the plugin system.", err=True) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 3fb45f2c9..2ea6fc4b0 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -11,13 +11,26 @@ import sys from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options -def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, octoprint_daemon = None): +def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None): """Initializes the environment and starts up the server.""" from octoprint import init_platform, __display_version__, FatalStartupError - def log_startup(_): - logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__)) + def log_startup(recorder=None, safe_mode=None, **kwargs): + logger = logging.getLogger("octoprint.server") + logger.info("Starting OctoPrint {}".format(__display_version__)) + if safe_mode: + logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") + + if recorder and len(recorder): + logger.info("--- Logged during platform initialization: ---") + + from octoprint.logging.handlers import CombinedLogHandler + handler = CombinedLogHandler(*logging.getLogger().handlers) + recorder.setTarget(handler) + recorder.flush() + + logger.info("----------------------------------------------") from octoprint import urllib3_ssl if not urllib3_ssl: @@ -30,13 +43,14 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl") try: - settings, _, plugin_manager = init_platform(basedir, - configfile, - logging_file=logging_config, - debug=debug, - verbosity=verbosity, - uncaught_logger=__name__, - after_logging=log_startup) + settings, _, safe_mode, plugin_manager = init_platform(basedir, + configfile, + logging_file=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=__name__, + safe_mode=safe_mode, + after_safe_mode=log_startup) except FatalStartupError as e: click.echo(e.message, err=True) click.echo("There was a fatal error starting up OctoPrint.", err=True) @@ -47,6 +61,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi host=host, port=port, debug=debug, + safe_mode=safe_mode, allow_root=allow_root, octoprint_daemon=octoprint_daemon) octoprint_server.run() @@ -62,7 +77,7 @@ server_options = bulk_options([ help="Specify the config file to use for configuring logging."), click.option("--iknowwhatimdoing", "allow_root", is_flag=True, help="Allow OctoPrint to run as user root."), - click.option("--debug", is_flag=True, help="Enable debug mode"), + click.option("--debug", is_flag=True, help="Enable debug mode.") ]) """Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" @@ -82,7 +97,7 @@ def server_commands(obj): def serve_command(obj, host, port, logging, allow_root, debug): """Starts the OctoPrint server.""" run_server(obj.basedir, obj.configfile, host, port, debug, - allow_root, logging, obj.verbosity) + allow_root, logging, obj.verbosity, obj.safe_mode) @server_commands.command(name="daemon") @@ -111,7 +126,7 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c from octoprint.daemon import Daemon class OctoPrintDaemon(Daemon): - def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity): + def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode): Daemon.__init__(self, pidfile) self._basedir = basedir @@ -122,12 +137,16 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c self._allow_root = allow_root self._logging_config = logging_config self._verbosity = verbosity + self._safe_mode = safe_mode def run(self): - run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity, self) + run_server(self._basedir, self._configfile, self._host, self._port, self._debug, + self._allow_root, self._logging_config, self._verbosity, self._safe_mode, + octoprint_daemon=self) octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile, - host, port, debug, allow_root, logging, octoprint_ctx.verbosity) + host, port, debug, allow_root, logging, octoprint_ctx.verbosity, + octoprint_ctx.safe_mode) if command == "start": octoprint_daemon.start() diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index fb6134293..fc2d5e430 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -81,3 +81,56 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler): self.cleanupFiles() if not self.delay: self.stream = self._open() + +class RecordingLogHandler(logging.Handler): + def __init__(self, target=None, level=logging.NOTSET): + logging.Handler.__init__(self, level=level) + self._buffer = [] + self._target = target + + def emit(self, record): + self._buffer.append(record) + + def setTarget(self, target): + self._target = target + + def flush(self): + if not self._target: + return + + self.acquire() + try: + for record in self._buffer: + self._target.handle(record) + self._buffer = [] + finally: + self.release() + + def close(self): + self.flush() + self.acquire() + try: + self._buffer = [] + finally: + self.release() + + def __len__(self): + return len(self._buffer) + + +class CombinedLogHandler(logging.Handler): + def __init__(self, *handlers): + logging.Handler.__init__(self) + self._handlers = handlers + + def setHandlers(self, *handlers): + self._handlers = handlers + + def handle(self, record): + self.acquire() + try: + if self._handlers: + for handler in self._handlers: + handler.handle(record) + finally: + self.release() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index a8736c4c8..31367e542 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -42,9 +42,10 @@ def _validate_plugin(phase, plugin_info): if not "octoprint.accesscontrol.appkey" in hooks: hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks) + return True def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None, - plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None): + plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -87,14 +88,6 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en else: if init: - if settings is None: - settings = s() - - if plugin_folders is None: - plugin_folders = ( - settings.getBaseFolder("plugins"), - (os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True) - ) if plugin_types is None: plugin_types = [StartupPlugin, ShutdownPlugin, @@ -109,22 +102,17 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en ProgressPlugin, WizardPlugin, UiPlugin] - if plugin_entry_points is None: - plugin_entry_points = "octoprint.plugin" - if plugin_disabled_list is None: - plugin_disabled_list = settings.get(["plugins", "_disabled"]) + if plugin_restart_needing_hooks is None: - plugin_restart_needing_hooks = [ - "octoprint.server.http" - ] + plugin_restart_needing_hooks = ["octoprint.server.http"] + if plugin_obsolete_hooks is None: - plugin_obsolete_hooks = [ - "octoprint.comm.protocol.gcode" - ] + plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] + if plugin_validators is None: - plugin_validators = [ - _validate_plugin - ] + plugin_validators = [_validate_plugin] + else: + plugin_validators.append(_validate_plugin) _instance = PluginManager(plugin_folders, plugin_types, @@ -145,7 +133,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr Arguments: plugin_key (string): The plugin identifier for which to create the settings instance. - defaults (dict): The default settings for the plugin. + defaults (dict): The default settings for the plugin, if different from get_settings_defaults. get_preprocessors (dict): The getter preprocessors for the plugin. set_preprocessors (dict): The setter preprocessors for the plugin. settings (octoprint.settings.Settings): The settings instance to use. @@ -180,13 +168,12 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): return None try: - defaults = instance.get_settings_defaults() get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() except: - logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key)) + logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key)) return None - return plugin_settings(plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) + return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None): @@ -315,11 +302,12 @@ class PluginSettings(object): self.settings = settings self.plugin_key = plugin_key - if defaults is None: - defaults = dict() - self.defaults = dict(plugins=dict()) - self.defaults["plugins"][plugin_key] = defaults - self.defaults["plugins"][plugin_key]["_config_version"] = None + if defaults is not None: + self.defaults = dict(plugins=dict()) + self.defaults["plugins"][plugin_key] = defaults + self.defaults["plugins"][plugin_key]["_config_version"] = None + else: + self.defaults = None if get_preprocessors is None: get_preprocessors = dict() @@ -345,14 +333,14 @@ class PluginSettings(object): return result def add_getter_kwargs(kwargs): - if not "defaults" in kwargs: + if not "defaults" in kwargs and self.defaults is not None: kwargs.update(defaults=self.defaults) if not "preprocessors" in kwargs: kwargs.update(preprocessors=self.get_preprocessors) return kwargs def add_setter_kwargs(kwargs): - if not "defaults" in kwargs: + if not "defaults" in kwargs and self.defaults is not None: kwargs.update(defaults=self.defaults) if not "preprocessors" in kwargs: kwargs.update(preprocessors=self.set_preprocessors) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index c95f13266..61ba0ff7a 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -149,6 +149,8 @@ class PluginInfo(object): self._license = license def validate(self, phase, additional_validators=None): + result = True + if phase == "before_load": # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ if hasattr(self.instance, self.__class__.attr_init): @@ -183,7 +185,9 @@ class PluginInfo(object): if additional_validators is not None: for validator in additional_validators: - validator(phase, self) + result = result and validator(phase, self) + + return result def __str__(self): if self.version: @@ -448,6 +452,12 @@ class PluginManager(object): if logging_prefix is None: logging_prefix = "" + if plugin_folders is None: + plugin_folders = [] + if plugin_types is None: + plugin_types = [] + if plugin_entry_points is None: + plugin_entry_points = [] if plugin_disabled_list is None: plugin_disabled_list = [] @@ -740,7 +750,9 @@ class PluginManager(object): plugin = self.plugins[name] try: - plugin.validate("before_load", additional_validators=self.plugin_validators) + if not plugin.validate("before_load", additional_validators=self.plugin_validators): + return + plugin.load() plugin.validate("after_load", additional_validators=self.plugin_validators) self.on_plugin_loaded(name, plugin) @@ -802,6 +814,9 @@ class PluginManager(object): raise PluginCantEnable(name, "Dependency on obsolete hooks detected, full functionality cannot be guaranteed") try: + if not plugin.validate("before_enable", additional_validators=self.plugin_validators): + return False + plugin.enable() self._activate_plugin(name, plugin) except PluginLifecycleException as e: diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index de8bb8e00..6b05c7903 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1368,14 +1368,17 @@ class SettingsPlugin(OctoPrintPlugin): to retrieve the data in the correct format. The default implementation will also replace any paths that have been restricted by your plugin through - :func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with ``None`` values where necessary. + :func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with either the provided + default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an + empty list (as fallback for restricted lists) or ``None`` values where necessary. Make sure to do your own restriction if you decide to fully overload this method. :return: the current settings of the plugin, as a dictionary """ from flask_login import current_user + import copy - data = self._settings.get_all_data() + data = copy.deepcopy(self._settings.get_all_data(merged=True)) if self.config_version_key in data: del data[self.config_version_key] @@ -1397,8 +1400,25 @@ class SettingsPlugin(OctoPrintPlugin): node = node[entry] key = path[-1] + default_value_available = False + default_value = None + if isinstance(key, (list, tuple)): + # key, default_value tuple + key, default_value = key + default_value_available = True + if key in node: - node[key] = None + if default_value_available: + if callable(default_value): + default_value = default_value() + node[key] = default_value + else: + if isinstance(node[key], dict): + node[key] = dict() + elif isinstance(node[key], (list, tuple)): + node[key] = [] + else: + node[key] = None conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous, admin=lambda: current_user is not None and not current_user.is_anonymous and current_user.is_admin, diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js index 19a2c32dc..1c37e2666 100644 --- a/src/octoprint/plugins/corewizard/static/js/corewizard.js +++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js @@ -71,7 +71,7 @@ $(function() { }); }; - self.onWizardTabChange = function(current, next) { + self.onBeforeWizardTabChange = function(next, current) { if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) { return true; } diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_printerprofile_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_printerprofile_wizard.jinja2 index 2b82ad357..b787defab 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_printerprofile_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_printerprofile_wizard.jinja2 @@ -13,19 +13,19 @@ to OctoPrint, you can also configure additional printer profiles under Settings
- {% include '_snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %} + {% include 'snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
- {% include '_snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %} + {% include 'snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
- {% include '_snippets/settings/printerprofiles/profileEditorAxes.jinja2' %} + {% include 'snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
- {% include '_snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %} + {% include 'snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_servercommands_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_servercommands_wizard.jinja2 index 509070d72..18233a461 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_servercommands_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_servercommands_wizard.jinja2 @@ -8,12 +8,12 @@

{{ _('OctoPrint related commands') }}

- {% include "_snippets/settings/server/serverCommandServerRestart.jinja2" %} + {% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}

{{ _('System related commands') }}

- {% include "_snippets/settings/server/serverCommandSystemRestart.jinja2" %} - {% include "_snippets/settings/server/serverCommandSystemShutdown.jinja2" %} + {% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %} + {% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_webcam_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_webcam_wizard.jinja2 index aa5a8cf71..b1fc6f3aa 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_webcam_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_webcam_wizard.jinja2 @@ -26,8 +26,8 @@

{% endtrans %}
- {% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %} - {% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %} + {% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %} + {% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}

{{ _('Timelapse Recordings') }}

@@ -38,5 +38,5 @@

{% endtrans %}
- {% include "_snippets/settings/webcam/ffmpegPath.jinja2" %} + {% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
diff --git a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 index 2bba70fdc..d5726f2d5 100644 --- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 +++ b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 @@ -8,13 +8,13 @@ {% endtrans %}

- {% include "_snippets/settings/cura/enginePath.jinja2" %} - {% include "_snippets/settings/cura/engineLog.jinja2" %} + {% include "snippets/settings/cura/enginePath.jinja2" %} + {% include "snippets/settings/cura/engineLog.jinja2" %}

{{ _('Profiles') }}

-{% include "_snippets/settings/cura/profiles.jinja2" %} +{% include "snippets/settings/cura/profiles.jinja2" %} @@ -22,4 +22,4 @@ {% trans %}For more information on configuration and usage please see the Plugin's homepage.{% endtrans %} -{% include "_snippets/settings/cura/profileImporter.jinja2" %} +{% include "snippets/settings/cura/profileImporter.jinja2" %} diff --git a/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 b/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 index 6bae2e185..55f4f7725 100644 --- a/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 +++ b/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 @@ -7,7 +7,7 @@
- {% include "_snippets/settings/cura/enginePath.jinja2" %} + {% include "snippets/settings/cura/enginePath.jinja2" %}
@@ -15,10 +15,11 @@

{{ _('Set up a slicing profile') }}

{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine - yet. You should do this now.{% endtrans %}

+ yet. If you plan on slicing from within OctoPrint then you should do this now. + Otherwise just skip this step.{% endtrans %}

- {% include "_snippets/settings/cura/profiles.jinja2" %} + {% include "snippets/settings/cura/profiles.jinja2" %}
diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/enginePath.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 similarity index 100% rename from src/octoprint/plugins/cura/templates/_snippets/settings/cura/profiles.jinja2 rename to src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 996946c68..d0d93272c 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -34,6 +34,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") + pip_inapplicable_arguments = dict(uninstall=["--user"]) + def __init__(self): self._pending_enable = set() self._pending_disable = set() @@ -180,6 +182,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if not admin_permission.can(): return make_response("Insufficient rights", 403) + from octoprint.server import safe_mode + refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues if refresh_repository: self._repository_available = self._refresh_repository() @@ -200,7 +204,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, virtual_env=self._pip_caller.virtual_env, additional_args=self._settings.get(["pip_args"]), python=sys.executable - )) + ), + safe_mode=safe_mode) def etag(): import hashlib @@ -208,6 +213,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, hash.update(repr(self._get_plugins())) hash.update(str(self._repository_available)) hash.update(repr(self._repository_plugins)) + hash.update(repr(safe_mode)) return hash.hexdigest() def condition(): @@ -450,7 +456,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable)) - needs_restart_api = needs_restart and not pending + safe_mode_victim = getattr(plugin, "safe_mode_victim", False) + needs_restart_api = (needs_restart or safe_mode_victim) and not pending needs_refresh_api = needs_refresh and not pending try: @@ -482,8 +489,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") additional_args = self._settings.get(["pip_args"]) - if additional_args: - args.append(additional_args) + + if additional_args is not None: + + inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list()) + for inapplicable_argument in inapplicable_arguments: + additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args) + + if additional_args: + args.append(additional_args) return self._pip_caller.execute(*args) @@ -514,12 +528,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._settings.global_set(["plugins", "_disabled"], disabled_list) self._settings.save(force=True) - if not needs_restart: + if not needs_restart and not getattr(plugin, "safe_mode_victim", False): self._plugin_manager.enable_plugin(plugin.key) else: if plugin.key in self._pending_disable: self._pending_disable.remove(plugin.key) - elif not plugin.enabled and plugin.key not in self._pending_enable: + elif (not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) def _mark_plugin_disabled(self, plugin, needs_restart=False): @@ -529,12 +543,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._settings.global_set(["plugins", "_disabled"], disabled_list) self._settings.save(force=True) - if not needs_restart: + if not needs_restart and not getattr(plugin, "safe_mode_victim", False): self._plugin_manager.disable_plugin(plugin.key) else: if plugin.key in self._pending_enable: self._pending_enable.remove(plugin.key) - elif plugin.enabled and plugin.key not in self._pending_disable: + elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) def _fetch_repository_from_disk(self): @@ -688,8 +702,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, bundled=plugin.bundled, managable=plugin.managable, enabled=plugin.enabled, - pending_enable=(not plugin.enabled and plugin.key in self._pending_enable), - pending_disable=(plugin.enabled and plugin.key in self._pending_disable), + safe_mode_victim=getattr(plugin, "safe_mode_victim", False), + safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False), + pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable), + pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable), pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")), pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")), origin=plugin.origin.type diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 7b6ac5202..2301e1dfe 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -155,6 +155,8 @@ $(function() { self.pipAdditionalArgs = ko.observable(); self.pipPython = ko.observable(); + self.safeMode = ko.observable(); + self.pipUseUserString = ko.pureComputed(function() { return self.pipUseUser() ? "yes" : "no"; }); @@ -186,7 +188,8 @@ $(function() { }); self.enableToggle = function(data) { - return self.enableManagement() && data.key != 'pluginmanager'; + var command = self._getToggleCommand(data); + return self.enableManagement() && (command == "disable" || !data.safe_mode_victim || data.safe_mode_enabled) && data.key != 'pluginmanager'; }; self.enableUninstall = function(data) { @@ -199,7 +202,7 @@ $(function() { }; self.enableRepoInstall = function(data) { - return self.enableManagement() && self.pipAvailable() && self.isCompatible(data); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data); }; self.invalidUrl = ko.pureComputed(function() { @@ -209,7 +212,7 @@ $(function() { self.enableUrlInstall = ko.pureComputed(function() { var url = self.installUrl(); - return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl(); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl(); }); self.invalidArchive = ko.pureComputed(function() { @@ -219,7 +222,7 @@ $(function() { self.enableArchiveInstall = ko.pureComputed(function() { var name = self.uploadFilename(); - return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive(); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && name !== undefined && name.trim() != "" && !self.invalidArchive(); }); self.uploadElement.fileupload({ @@ -246,7 +249,7 @@ $(function() { done: function(e, data) { self._markDone(); self.uploadButton.unbind("click"); - self.uploadFilename(""); + self.uploadFilename(undefined); }, fail: function(e, data) { new PNotify({ @@ -257,7 +260,7 @@ $(function() { }); self._markDone(); self.uploadButton.unbind("click"); - self.uploadFilename(""); + self.uploadFilename(undefined); } }); @@ -278,6 +281,8 @@ $(function() { self._fromPluginsResponse(data.plugins); self._fromRepositoryResponse(data.repository); self._fromPipResponse(data.pip); + + self.safeMode(data.safe_mode || false); }; self._fromPluginsResponse = function(data) { @@ -347,6 +352,7 @@ $(function() { }; if (self._getToggleCommand(data) == "enable") { + if (data.safe_mode_victim && !data.safe_mode_enabled) return; OctoPrint.plugins.pluginmanager.enable(data.key) .done(onSuccess) .fail(onError); @@ -547,7 +553,7 @@ $(function() { title: titleSuccess, text: textRestart, buttons: { - closer: false, + closer: true, sticker: false }, callbacks: { @@ -600,7 +606,7 @@ $(function() { }] }, buttons: { - closer: false, + closer: true, sticker: false }, callbacks: { @@ -640,8 +646,9 @@ $(function() { self.loglines.removeAll(); self.loglines.push({line: line, stream: "message"}); + self._scrollWorkingOutputToEnd(); - self.workingDialog.modal("show"); + self.workingDialog.modal({keyboard: false, backdrop: "static", show: true}); }; self._markDone = function() { @@ -655,7 +662,8 @@ $(function() { }; self._getToggleCommand = function(data) { - return ((!data.enabled || data.pending_disable) && !data.pending_enable) ? "enable" : "disable"; + var disable = (data.enabled || data.pending_enable || (data.safe_mode_victim && data.safe_mode_enabled)) && !data.pending_disable; + return disable ? "disable" : "enable"; }; self.toggleButtonCss = function(data) { @@ -666,7 +674,16 @@ $(function() { }; self.toggleButtonTitle = function(data) { - return self._getToggleCommand(data) == "enable" ? gettext("Enable Plugin") : gettext("Disable Plugin"); + var command = self._getToggleCommand(data); + if (command == "enable") { + if (data.safe_mode_victim && !data.safe_mode_enabled) { + return gettext("Disabled due to active safe mode"); + } else { + return gettext("Enable Plugin"); + } + } else { + return gettext("Disable Plugin"); + } }; self.onBeforeBinding = function() { @@ -682,6 +699,10 @@ $(function() { }; self.onUserLoggedOut = function() { + self._closeAllNotifications(); + }; + + self._closeAllNotifications = function() { if (self.notifications) { _.each(self.notifications, function(notification) { notification.remove(); @@ -689,6 +710,11 @@ $(function() { } }; + self.onServerDisconnect = function() { + self._closeAllNotifications(); + return true; + }; + self.onStartup = function() { self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog"); self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output"); @@ -721,7 +747,7 @@ $(function() { if (messageType == "loglines" && self.working()) { _.each(data.loglines, function(line) { - self.loglines.push(line); + self.loglines.push(self._preprocessLine(line)); }); self._scrollWorkingOutputToEnd(); } else if (messageType == "result") { @@ -836,6 +862,14 @@ $(function() { self.requestData(); } }; + + self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./; + self._preprocessLine = function(line) { + if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) { + line.stream = "stdout"; + } + return line; + } } // view model class, parameters for constructor, container to bind to diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 0c9c721df..8f01183c0 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -13,8 +13,16 @@ {% endtrans %}
{% endmacro %} +{% macro pluginmanager_safemode() %} +
{% trans %} + Safe mode is currently active. All third party plugins are disabled and cannot be + enabled. Installation of plugin packages is disabled. +{% endtrans %}
+{% endmacro %} + {{ pluginmanager_printing() }} {{ pluginmanager_nopip() }} +{{ pluginmanager_safemode() }}
@@ -32,7 +40,7 @@ -
()
+
()
 
{{ _('Homepage') }} @@ -80,7 +88,6 @@