From 0ba987e126901ea23af282d4525621610eebf3c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 6 Nov 2018 12:31:53 +0100 Subject: [PATCH 01/27] maintenance is now 1.3.11.dev --- .versioneer-lookup | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.versioneer-lookup b/.versioneer-lookup index 8edce3e2c..7fd9ad046 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,11 +18,11 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.9 +# maintenance is currently the branch for preparation of maintenance release 1.3.11 # so are any fix/... and improve/... branches -maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev +maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev +fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev +improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev # staging/maintenance is currently the branch for preparation of 1.3.10rc2 # so is regressionfix/... From dae0264a5816eae5f3fac8658a75784f06eb65a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 8 Nov 2018 17:41:27 +0100 Subject: [PATCH 02/27] Add time & reason for failure to PrintFailed event --- docs/events/index.rst | 2 ++ src/octoprint/printer/standard.py | 10 +++++++++- src/octoprint/util/comm.py | 2 +- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/events/index.rst b/docs/events/index.rst index a97e7e385..f2875c25d 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -338,6 +338,8 @@ PrintFailed * ``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`` + * ``time``: the elapsed time of the print when it failed, in seconds (float) + * ``reason``: the reason the print failed, either ``cancelled`` or ``error`` .. deprecated:: 1.3.0 diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 80cae7aa5..a3c589048 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -973,6 +973,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): payload = self._payload_for_print_job_event() if payload: payload["time"] = self._comm.getPrintTime() + payload["reason"] = "error" def finalize(): self._fileManager.log_print(payload["origin"], @@ -1103,8 +1104,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - def on_comm_print_job_failed(self): + def on_comm_print_job_failed(self, reason=None): payload = self._payload_for_print_job_event() + + if reason: + payload["reason"] = reason + else: + payload["reason"] = "unknown" + if payload: eventManager().fire(Events.PRINT_FAILED, payload) @@ -1122,6 +1129,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None) if payload: payload["time"] = self._comm.getPrintTime() + payload["reason"] = "cancelled" eventManager().fire(Events.PRINT_CANCELLED, payload) if not suppress_script: diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index f6bd0e754..99cb3c073 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -3600,7 +3600,7 @@ class MachineComPrintCallback(object): def on_comm_print_job_started(self, suppress_script=False): pass - def on_comm_print_job_failed(self): + def on_comm_print_job_failed(self, reason=None): pass def on_comm_print_job_done(self, suppress_script=False): From b7e373c40f05e85df170d578bb7b8cf7b9c1e087 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 8 Nov 2018 17:41:45 +0100 Subject: [PATCH 03/27] tracking: add time & reason for failure to print_failed --- src/octoprint/plugins/tracking/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 108b275e5..0d5290de0 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -216,6 +216,12 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, args[b"elapsed"] = elapsed track_event = "print_done" elif event == Events.PRINT_FAILED: + try: + elapsed = int(payload.get(b"time")) + except ValueError: + elapsed = "unknown" + args[b"elapsed"] = elapsed + args[b"reason"] = payload.get(b"reason", "unknown") track_event = "print_failed" elif event == Events.PRINT_CANCELLED: track_event = "print_cancelled" From a939130748602a3e0f9f600274b55c48fb3b7ed2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 8 Nov 2018 18:39:03 +0100 Subject: [PATCH 04/27] Better description for Error event --- docs/events/index.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/events/index.rst b/docs/events/index.rst index f2875c25d..288f8d82f 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -141,7 +141,8 @@ Disconnected The server has disconnected from the printer Error - An error has occurred in the printer communication. + An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or + on the connection. Payload: From 4548be34f03069a5fbc5f74298c09c2d3c96a0ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 12 Nov 2018 11:40:21 +0100 Subject: [PATCH 05/27] Always trigger SettingsUpdated event on new save So far it was only triggered when saving via the REST API, causing some issues here and there. --- src/octoprint/server/api/settings.py | 6 ------ src/octoprint/settings.py | 7 +++++++ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 4da866326..ad6b46868 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -548,9 +548,3 @@ def _saveSettings(data): logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name)) s.save() - - payload = dict( - config_hash=s.config_hash, - effective_hash=s.effective_hash - ) - eventManager().fire(Events.SETTINGS_UPDATED, payload=payload) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 3ff933ab5..df8f56e9a 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1334,7 +1334,14 @@ class Settings(object): self._logger.exception("Error while saving config.yaml!") raise else: + from octoprint.events import eventManager, Events + self.load() + + payload = dict(config_hash=self.config_hash, + effective_hash=self.effective_hash) + eventManager().fire(Events.SETTINGS_UPDATED, payload=payload) + return True ##~~ Internal getter From 91b524813c9c06bd1e8a31a3989840434f2571a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 9 Nov 2018 18:19:28 +0100 Subject: [PATCH 06/27] Minimum python version is now 2.7.9 --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index a11d0c6e8..e7ea506b3 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,7 @@ import octoprint_setuptools #----------------------------------------------------------------------------------------------------------------------- # Supported python versions -PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11 +PYTHON_REQUIRES = ">=2.7.9,<3" # Requirements for our application INSTALL_REQUIRES = [ From 8e464f59aca3a44dc51ca6efbb6177ec74ff0ae5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 9 Nov 2018 18:28:35 +0100 Subject: [PATCH 07/27] Reapply "Updated several dependencies to current version" This reverts commit e14c00f135bf2a955e54ac3f0a2928d8440055d2. --- setup.py | 68 ++++++++++++++++-------------- src/octoprint/server/__init__.py | 1 + src/octoprint/server/util/flask.py | 26 ++++++++++++ 3 files changed, 63 insertions(+), 32 deletions(-) diff --git a/setup.py b/setup.py index e7ea506b3..a66affe45 100644 --- a/setup.py +++ b/setup.py @@ -17,44 +17,48 @@ PYTHON_REQUIRES = ">=2.7.9,<3" # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.10.1,<0.11", - "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't - # guarantee backwards compatibility for plugins and such with that - # version, hence we need to pin to a lower version for now. See #1697 - "regex==2018.11.3", # Current version as of 2018-11-06 is broken. See #2874 - "werkzeug>=0.8.3,<0.9", - "tornado==4.5.3", - #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a - # vendored one - "PyYAML>=3.10,<3.11", - "Flask-Login>=0.2.11,<0.3", - "Flask-Principal>=0.3.5,<0.4", - "Flask-Babel>=0.9,<0.10", - "Flask-Assets>=0.10,<0.11", - "markdown>=2.6.9,<2.7", + # the following dependencies are non trivial to update since later versions introduce backwards incompatible + # changes that might affect plugins, or due to other observed problems + + "flask>=0.10.1,<0.11", # newer versions require newer Jinja versions + "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't + # guarantee backwards compatibility for plugins and such with that + # version, hence we need to pin to a lower version for now. See #1697 + "tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585 + "Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3 + "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + + # anything below this should be checked on releases for new versions + + "Flask-Principal>=0.4,<0.5", + "Flask-Babel>=0.12,<0.13", + "Flask-Assets>=0.12,<0.13", + "werkzeug>=0.14.1,<0.15", + "PyYAML>=3.13,<4", + "markdown>=3.0,<3.1", "pyserial>=3.4,<3.5", "netaddr>=0.7.19,<0.8", - "watchdog>=0.8.3,<0.9", + "watchdog>=0.9.0,<0.10", "sarge==0.1.5post0", - "netifaces>=0.10.6,<0.11", - "pylru>=1.0.9,<1.1", - "rsa>=3.2.3,<3.3", + "netifaces>=0.10.7,<0.11", + "pylru>=1.1,<1.2", + "rsa>=4.0,<5", "pkginfo>=1.4.2,<1.5", - "requests>=2.18.4,<3", - "semantic_version>=2.4.2,<2.5", - "psutil>=5.4.6,<5.5", - "Click>=6.2,<6.3", + "requests>=2.20.0,<3", + "semantic_version>=2.6,<2.7", + "psutil>=5.4.8,<5.5", + "Click>=7,<8", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", "chainmap>=1.0.2,<1.1", - "future>=0.15.2,<0.16", - "scandir>=1.3,<1.4", - "websocket-client>=0.40.0,<0.41", - "python-dateutil>=2.6.1,<2.7", + "future>=0.17,<0.18", + "scandir>=1.9,<1.10", + "websocket-client>=0.53,<0.54", + "python-dateutil>=2.7.5,<2.8", "wrapt>=1.10.11,<1.11", - "futures>=3.1.1,<3.2", - "emoji>=0.4.5,<0.5", - "monotonic>=1.3,<1.4", + "futures>=3.2,<3.3", + "emoji>=0.5.1,<0.6", + "monotonic>=1.5,<1.6", "frozendict>=1.2,<1.3" ] @@ -67,7 +71,7 @@ EXTRA_REQUIRES = dict( develop=[ # Testing dependencies "mock>=2.0.0,<3", - "nose>=1.3.0,<1.4", + "nose>=1.3.7,<1.4", "ddt", # Documentation dependencies @@ -79,7 +83,7 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.4,<1.7" + "cookiecutter>=1.6,<1.7" ] ) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index c751b59dd..9c7926bc9 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -242,6 +242,7 @@ class Server(object): # monkey patch a bunch of stuff util.tornado.fix_json_encode() + util.flask.fix_flask_jsonify() util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")]) # setup app diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index cdec02307..60d119508 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -251,6 +251,32 @@ def fix_flask_login_remote_address(): flask_login._get_remote_addr = fixed_get_remote_addr +def fix_flask_jsonify(): + def fixed_jsonify(*args, **kwargs): + """Backported from https://github.com/pallets/flask/blob/7e714bd28b6e96d82b2848b48cf8ff48b517b09b/flask/json/__init__.py#L257""" + from flask.json import current_app, dumps + + indent = None + separators = (',', ':') + + if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug: + indent = 2 + separators = (', ', ': ') + + if args and kwargs: + raise TypeError('jsonify() behavior undefined when passed both args and kwargs') + elif len(args) == 1: # single args are passed directly to dumps() + data = args[0] + else: + data = args or kwargs + + return current_app.response_class( + dumps(data, indent=indent, separators=separators) + '\n', + mimetype='application/json' + ) + + flask.jsonify = fixed_jsonify + #~~ WSGI environment wrapper for reverse proxying class ReverseProxiedEnvironment(object): From 170804d4df22cfdeebbbdfa1095c7c111b134b53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 22 Nov 2018 13:47:02 +0100 Subject: [PATCH 08/27] Create a backup of working config.yaml after startup --- src/octoprint/plugins/softwareupdate/util.py | 5 ++++- src/octoprint/server/__init__.py | 3 +++ src/octoprint/settings.py | 18 ++++++++++++++---- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index 0adf55ba0..69fbc566c 100644 --- a/src/octoprint/plugins/softwareupdate/util.py +++ b/src/octoprint/plugins/softwareupdate/util.py @@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from .exceptions import ScriptError +import logging + def execute(command, cwd=None, evaluate_returncode=True, **kwargs): do_async = kwargs.get("do_async", kwargs.get("async", False)) @@ -16,8 +18,9 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs): p = None try: - p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async) + p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=do_async) except: + logging.getLogger(__name__).exception("Error while executing command: {}".format(command)) returncode = p.returncode if p is not None else None stdout = p.stdout.text if p is not None and p.stdout is not None else "" stderr = p.stderr.text if p is not None and p.stderr is not None else "" diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 9c7926bc9..fd7e3ecdc 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -711,6 +711,9 @@ class Server(object): self._settings.setBoolean(["server", "startOnceInSafeMode"], False) self._settings.save() + # make a backup of the current config + self._settings.backup(ext="backup") + # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index df8f56e9a..aa1f6339a 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1309,15 +1309,25 @@ class Settings(object): return True return False - def backup(self, suffix, path=None): + def backup(self, suffix=None, path=None, ext=None, hidden=False): import shutil if path is None: path = os.path.dirname(self._configfile) - basename = os.path.basename(self._configfile) - name, ext = os.path.splitext(basename) - backup = os.path.join(path, "{}.{}{}".format(name, suffix, ext)) + basename = os.path.basename(self._configfile) + name, default_ext = os.path.splitext(basename) + + if ext is None: + ext = default_ext + + if suffix is None and ext == default_ext: + raise ValueError("Need a suffix or a different extension") + + if suffix is None: + suffix = "" + + backup = os.path.join(path, "{}{}.{}{}".format("." if hidden else "", name, suffix, ext)) shutil.copy(self._configfile, backup) return backup From 037e92c44786bd13b00c5ab2c63b776192a86c08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 22 Nov 2018 15:52:18 +0100 Subject: [PATCH 09/27] Recognize incomplete startups and set safe mode flag --- src/octoprint/__init__.py | 5 +++-- src/octoprint/cli/server.py | 13 +++++++++++-- src/octoprint/server/__init__.py | 15 ++++++++++++--- src/octoprint/settings.py | 1 + src/octoprint/static/js/app/dataupdater.js | 19 ++++++++++++++++++- 5 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 31566ff46..60d11a1b1 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -103,8 +103,9 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, if callable(after_logging): after_logging(**kwargs) - settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"]) - safe_mode = safe_mode or settings_safe_mode + settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None + settings_incomplete_startup_safemode = "incomplete_startup" if settings.getBoolean(["server", "incompleteStartup"]) else None + safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode kwargs["safe_mode"] = safe_mode if callable(after_safe_mode): after_safe_mode(**kwargs) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index dc9ff6cbf..e536b84d4 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -26,6 +26,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi logger.info("Starting OctoPrint {}".format(__display_version__)) if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") + if safe_mode == "flag": + reason = "command line flag" + elif safe_mode == "settings": + reason = "setting in config.yaml" + elif safe_mode == "incomplete_startup": + reason = "problem during last startup" + else: + reason = "unknown" + logger.info("Reason for safe mode: {}".format(reason)) if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) @@ -179,7 +188,7 @@ def serve_command(ctx, **kwargs): basedir = get_value("basedir") configfile = get_value("configfile") verbosity = get_value("verbosity") - safe_mode = get_value("safe_mode") + safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") run_server(basedir, configfile, host, port, debug, @@ -217,7 +226,7 @@ if sys.platform != "win32" and sys.platform != "darwin": basedir = get_value("basedir") configfile = get_value("configfile") verbosity = get_value("verbosity") - safe_mode = get_value("safe_mode") + safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") if pid is None: diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index fd7e3ecdc..e59effb5a 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -190,6 +190,10 @@ class Server(object): if self._settings is None: self._settings = settings() + + self._settings.setBoolean(["server", "incompleteStartup"], True) + self._settings.save() + if self._plugin_manager is None: self._plugin_manager = octoprint.plugin.plugin_manager() @@ -711,9 +715,6 @@ class Server(object): self._settings.setBoolean(["server", "startOnceInSafeMode"], False) self._settings.save() - # make a backup of the current config - self._settings.backup(ext="backup") - # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll @@ -731,6 +732,14 @@ class Server(object): implementation.on_after_startup() pluginLifecycleManager.add_callback("enabled", call_on_after_startup) + # if there was a rogue plugin we wouldn't even have made it here, so remove startup triggered safe mode + # flag again... + self._settings.setBoolean(["server", "incompleteStartup"], False) + self._settings.save() + + # make a backup of the current config + self._settings.backup(ext="backup") + # when we are through with that we also run our preemptive cache if settings().getBoolean(["devel", "cache", "preemptive"]): self._execute_preemptive_flask_caching(preemptiveCache) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index aa1f6339a..e6570d744 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -155,6 +155,7 @@ default_settings = { "port": 5000, "firstRun": True, "startOnceInSafeMode": False, + "incompleteStartup": False, "seenWizards": {}, "secretKey": None, "heartbeat": 15 * 60, # 15 min diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 098eb0aa7..b3f14af90 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -154,10 +154,27 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { if (data["safe_mode"]) { // safe mode is active, let's inform the user log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled."); + log.info("Reason for safe mode: " + data["safe_mode"]); + + var reason = gettext("Unknown"); + switch (data["safe_mode"]) { + case "flag": { + reason = gettext("Command line flag"); + break; + } + case "settings": { + reason = gettext("Setting in config.yaml"); + break; + } + case "incomplete_startup": { + reason = gettext("Problem during last startup"); + break; + } + } self._safeModePopup = new PNotify({ title: gettext("Safe mode is active"), - text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."), + text: _.sprintf(gettext("

The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled.

Reason: %(reason)s

"), {reason: reason}), hide: false }); } From fa9472d4aa13177bf8836444ea2d76386b939350 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 22 Nov 2018 15:54:02 +0100 Subject: [PATCH 10/27] Fix SWU restart command again Accidentally committed something I only changed for a test. Oops. --- src/octoprint/plugins/softwareupdate/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index 69fbc566c..13a631d89 100644 --- a/src/octoprint/plugins/softwareupdate/util.py +++ b/src/octoprint/plugins/softwareupdate/util.py @@ -18,7 +18,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs): p = None try: - p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=do_async) + p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async) except: logging.getLogger(__name__).exception("Error while executing command: {}".format(command)) returncode = p.returncode if p is not None else None From 9a90093dda728129230b5339c989a9d531377be5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 26 Nov 2018 14:08:00 +0100 Subject: [PATCH 11/27] tracking: file path instead of just name in print events Closes #2908 --- src/octoprint/plugins/tracking/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index ab57f5c50..38a748ccb 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -233,7 +233,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, return sha = hashlib.sha1() - sha.update(payload.get("name")) + sha.update(payload.get("path")) sha.update(self._settings.get([b"unique_id"])) track_event = None From 2f69a843529bf81ac665e09b112ca3c0fa59aa12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 26 Nov 2018 15:33:37 +0100 Subject: [PATCH 12/27] Use max of comm & temp timeout as serial timeout That way we avoid issues if the user has set a longer temperature reporting interval than (busy) communication timeout. See #2905 --- src/octoprint/util/comm.py | 44 ++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 99cb3c073..a9be8f29c 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1499,8 +1499,7 @@ class MachineCom(object): self._changeState(self.STATE_CONNECTING) #Start monitoring the serial port. - self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + self._timeout = self._ok_timeout = self._get_new_communication_timeout() startSeen = False supportRepetierTargetTemp = settings().getBoolean(["serial", "repetierTargetTemp"]) @@ -1520,7 +1519,7 @@ class MachineCom(object): if line.strip() is not "": self._consecutive_timeouts = 0 - self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + self._timeout = self._get_new_communication_timeout() if self._dwelling_until and now > self._dwelling_until: self._dwelling_until = False @@ -1534,7 +1533,7 @@ class MachineCom(object): ##~~ busy protocol handling if line.startswith("echo:busy:") or line.startswith("busy:"): # reset the ok timeout, the regular comm timeout has already been reset - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + self._ok_timeout = self._get_new_communication_timeout() # make sure the printer sends busy in a small enough interval to match our timeout if not self._busy_protocol_detected and self._capability_support.get(self.CAPABILITY_BUSY_PROTOCOL, @@ -1545,14 +1544,13 @@ class MachineCom(object): self._logger.info(to_log) self._busy_protocol_detected = True - new_communication_timeout = self._timeout_intervals.get("communicationBusy", 2) - busy_interval = max(int(new_communication_timeout) - 1, 1) + busy_interval = max(int(self._timeout_intervals.get("communicationBusy", 2)) - 1, 1) def busyIntervalSet(): self._logger.info("Telling the printer to set the busy interval to our " "\"communicationBusy\" timeout - 1s = {}s".format(busy_interval)) self._busy_protocol_support = True - self._serial.timeout = new_communication_timeout + self._serial.timeout = self._get_communication_timeout_interval() self._set_busy_protocol_interval(interval=busy_interval, callback=busyIntervalSet) @@ -1668,7 +1666,7 @@ class MachineCom(object): # Both variants can only happen if we are not currently blocked by a dwelling command self._handle_timeout() - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + self._ok_timeout = self._get_new_communication_timeout() # timeout only considered handled if the printer is printing and it was a comm timeout, not an ok # timeout @@ -2060,7 +2058,7 @@ class MachineCom(object): self._resend_ok_timer.cancel() self._resend_ok_timer = None - self._ok_timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + self._ok_timeout = self._get_new_communication_timeout() self._clear_to_send.set() # reset long running commands, persisted current tools and heatup counters on ok @@ -2298,7 +2296,7 @@ class MachineCom(object): on_sent=callback) def _onConnected(self): - self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"]) + self._serial.timeout = self._get_communication_timeout_interval() self._temperature_timer = RepeatedTimer(self._get_temperature_timer_interval, self._poll_temperature, run_first=True) self._temperature_timer.start() @@ -2371,6 +2369,25 @@ class MachineCom(object): interval = 1.0 return interval + def _get_communication_timeout_interval(self): + # communication timeout + if self._busy_protocol_support: + comm_timeout = self._timeout_intervals.get("communicationBusy", 2.0) + else: + comm_timeout = self._timeout_intervals.get("communication", 30.0) + + # temperature interval + if self._temperature_autoreporting: + temperature_timeout = self._timeout_intervals.get("temperatureAutoreport", 2.0) + else: + temperature_timeout = self._get_temperature_timer_interval() + + # use the max of both, add a second to temperature to avoid race conditions + return max(comm_timeout, temperature_timeout + 1) + + def _get_new_communication_timeout(self): + return time.time() + self._get_communication_timeout_interval() + def _send_from_command_queue(self): # We loop here to make sure that if we do NOT send the first command # from the queue, we'll send the second (if there is one). We do not @@ -3537,7 +3554,7 @@ class MachineCom(object): elif s_match: _timeout = float(s_match.group("value")) - self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_support else "communication", self._timeout_intervals) + _timeout + self._timeout = self._get_new_communication_timeout() + _timeout self._dwelling_until = time.time() + _timeout def _validate_tool(self, tool): @@ -4055,11 +4072,6 @@ class SendQueue(PrependableQueue): return self._resend_queue.qsize() + self._send_queue.qsize() -def get_new_timeout(type, intervals): - now = time.time() - return now + intervals.get(type, 0.0) - - _temp_command_regex = re.compile("^M(?P104|109|140|190)(\s+T(?P\d+)|\s+S(?P[-+]?\d*\.?\d*))+") def apply_temperature_offsets(line, offsets, current_tool=None): From f4f7c87640fdc94fa4d1be8a017c696e5324e45a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 6 Dec 2018 11:44:55 +0100 Subject: [PATCH 13/27] Always show actual received from printer instead of off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regardless how cold the temperature is, display it in the table. Some people otherwise seem to think that OctoPrint "can't handle" temperatures below 10°C and will blame it for MINTEMP errors triggered in the firmware. --- src/octoprint/static/js/app/helpers.js | 8 ++++---- src/octoprint/static/js/app/viewmodels/temperature.js | 11 +++++++++-- src/octoprint/templates/tabs/temperature.jinja2 | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 7df9e46af..3087f6dd1 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -574,15 +574,15 @@ function formatFilament(filament) { return _.sprintf(result, {length: filament["length"] / 1000, volume: filament["volume"]}); } -function cleanTemperature(temp) { +function cleanTemperature(temp, offThreshold) { if (temp === undefined || !_.isNumber(temp)) return "-"; - if (temp < 10) return gettext("off"); + if (offThreshold !== undefined && temp < offThreshold) return gettext("off"); return temp; } -function formatTemperature(temp, showF) { +function formatTemperature(temp, showF, offThreshold) { if (temp === undefined || !_.isNumber(temp)) return "-"; - if (temp < 10) return gettext("off"); + if (offThreshold !== undefined && temp < offThreshold) return gettext("off"); if (showF) { return _.sprintf("%.1f°C (%.1f°F)", temp, temp * 9 / 5 + 32); } else { diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js index af328424b..7c1e43b55 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -401,7 +401,7 @@ $(function() { } var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1], showFahrenheit) : "-"; - var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit) : "-"; + var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit, 1) : "-"; data.push({ label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp, @@ -703,7 +703,14 @@ $(function() { self._replaceLegendLabel = function(index, series, value, emph) { var showFahrenheit = self._shallShowFahrenheit(); - var temp = formatTemperature(value, showFahrenheit); + var temp; + if (index % 2 === 0) { + // actual series + temp = formatTemperature(value, showFahrenheit); + } else { + // target series + temp = formatTemperature(value, showFahrenheit, 1); + } if (emph) { temp = "" + temp + ""; } diff --git a/src/octoprint/templates/tabs/temperature.jinja2 b/src/octoprint/templates/tabs/temperature.jinja2 index fe521385a..7bdceffe2 100644 --- a/src/octoprint/templates/tabs/temperature.jinja2 +++ b/src/octoprint/templates/tabs/temperature.jinja2 @@ -25,7 +25,7 @@
- + °C
From bfd847f0a63658ab27b9f3e287c5361f11a670ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 12 Dec 2018 15:16:17 +0100 Subject: [PATCH 14/27] GCODE viewer: Bring back the layer count --- src/octoprint/static/js/app/viewmodels/gcode.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index 522659f97..f6254fe43 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -530,6 +530,7 @@ $(function() { output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm"); output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm")); output.push(gettext("Estimated total print time") + ": " + formatFuzzyPrintTime(model.printTime)); + output.push(gettext("Layers with extrusion") + ": " + model.layersPrinted.toFixed(0)); self.ui_modelInfo(output.join("
")); From ae36a3905acf55215c189719532dab78b4d1dc8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 12 Dec 2018 15:25:38 +0100 Subject: [PATCH 15/27] printer safety: Mark Malyan M200 fw 4.0+ as safe Implements #2947 --- src/octoprint/plugins/printer_safety_check/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 38a09533d..6970a9b16 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -43,8 +43,8 @@ ENDER3_RECEIVED_TEST = lambda line: line and ENDER3_AUTHOR in line.lower() # iMe on Micro3D IME_M115_TEST = lambda name, data: name and name.lower().startswith("ime") -# Malyan M200 aka Monoprice Select Mini -MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" +# Malyan M200 aka Monoprice Select Mini, versions less than 4.0 +MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < get_comparable_version("4.0") # Stock Micro3D MICRO3D_M115_TEST = lambda name, data: name and name.lower().startswith("micro3d") From 8cf5ca95892784fc650960f804eef6a07c1849eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 10 Dec 2018 12:13:11 +0100 Subject: [PATCH 16/27] tracking: Track firmware/communication errors --- src/octoprint/plugins/tracking/__init__.py | 30 +++++++++++++++++++ .../templates/tracking_settings.jinja2 | 3 ++ src/octoprint/printer/standard.py | 12 +------- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 577999f98..46c6978e4 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -60,6 +60,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, ping=15*60, events=dict(startup=True, printjob=True, + commerror=True, plugin=True, update=True, printer=True, @@ -117,6 +118,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._track_throttle_event(event, payload) elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): self._track_printjob_event(event, payload) + elif event in (Events.ERROR,): + self._track_commerror_event(event, payload) elif event in (Events.CONNECTED,): self._printer_connection_parameters = dict(port=payload["port"], baudrate=payload["baudrate"]) @@ -228,6 +231,29 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, if track_event is not None: self._track(track_event, **args) + def _track_commerror_event(self, event, payload): + if not self._settings.get_boolean(["events", "commerror"]): + return + + if not b"reason" in payload or not b"error" in payload: + return + + track_event = "commerror_{}".format(payload[b"reason"]) + args = dict(commerror_text=payload[b"error"]) + + if callable(self._helpers_get_throttle_state): + try: + throttle_state = self._helpers_get_throttle_state(run_now=True) + if throttle_state and (throttle_state.get(b"current_issue", False) or throttle_state.get(b"past_issue", False)): + args[b"throttled_now"] = throttle_state[b"current_issue"] + args[b"throttled_past"] = throttle_state[b"past_issue"] + args[b"throttled_mask"] = throttle_state[b"raw_value"] + except: + # ignored + pass + + self._track(track_event, **args) + def _track_printjob_event(self, event, payload): if not self._settings.get_boolean(["events", "printjob"]): return @@ -255,6 +281,10 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, elapsed = "unknown" args[b"elapsed"] = elapsed args[b"reason"] = payload.get(b"reason", "unknown") + + if b"error" in payload and self._settings.get_boolean(["events", "commerror"]): + args[b"commerror_text"] = payload[b"error"] + track_event = "print_failed" elif event == Events.PRINT_CANCELLED: track_event = "print_cancelled" diff --git a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 index 217bc26c6..292a898bd 100644 --- a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 +++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 @@ -31,6 +31,9 @@ + diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index a3c589048..e010b5176 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -974,6 +974,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if payload: payload["time"] = self._comm.getPrintTime() payload["reason"] = "error" + payload["error"] = self._comm.getErrorString() def finalize(): self._fileManager.log_print(payload["origin"], @@ -1104,17 +1105,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) - def on_comm_print_job_failed(self, reason=None): - payload = self._payload_for_print_job_event() - - if reason: - payload["reason"] = reason - else: - payload["reason"] = "unknown" - - if payload: - eventManager().fire(Events.PRINT_FAILED, payload) - def on_comm_print_job_cancelling(self, firmware_error=None): payload = self._payload_for_print_job_event() if payload: From 49b995b2345c5bc3b07b2f5e5e8e75f2ddd41079 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 12 Dec 2018 16:06:15 +0100 Subject: [PATCH 17/27] Set 10min idle timeout on tornado under windows Possible workaround for #2916 --- src/octoprint/server/__init__.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index e59effb5a..d6db68d8a 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -21,6 +21,7 @@ from builtins import bytes, range from past.builtins import basestring import os +import sys import logging import logging.config import atexit @@ -655,11 +656,16 @@ class Server(object): if not isinstance(trusted_downstream, list): self._logger.warn("server.reverseProxy.trustedDownstream is not a list, skipping") trusted_downstreams = [] - self._server = util.tornado.CustomHTTPServer(self._tornado_app, - max_body_sizes=max_body_sizes, - default_max_body_size=self._settings.getInt(["server", "maxSize"]), - xheaders=True, - trusted_downstream=trusted_downstream) + + server_kwargs = dict(max_body_sizes=max_body_sizes, + default_max_body_size=self._settings.getInt(["server", "maxSize"]), + xheaders=True, + trusted_downstream=trusted_downstream) + if sys.platform == "win32": + # set 10min idle timeout under windows to hopefully make #2916 less likely + server_kwargs.update(dict(idle_connection_timeout=600)) + + self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs) self._server.listen(self._port, address=self._host if self._host != "::" else None) # special case - tornado # only listens on v4 & v6 # if we use None as address From 5760b4b264637d33c3d036d889425c31e38e40a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 13 Dec 2018 13:13:02 +0100 Subject: [PATCH 18/27] tracking: check enabled state before preparing payload Otherwise if tracking is disabled we still do the work and then throw it away, which is kinda stupid. Also fixes potential issues with using things like the unique_id when it hasn't in fact been set due to disabled tracking. --- src/octoprint/plugins/tracking/__init__.py | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 46c6978e4..8691bfb30 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -161,9 +161,15 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._settings.save() def _track_ping(self): + if not self._settings.get_boolean([b"enabled"]): + return + self._track("ping") def _track_startup(self): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "startup"]): return @@ -184,12 +190,18 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._track("startup", **payload) def _track_shutdown(self): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "startup"]): return self._track("shutdown") def _track_plugin_event(self, event, payload): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "plugin"]): return @@ -203,6 +215,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) def _track_update_event(self, event, payload): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "update"]): return @@ -212,6 +227,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version")) def _track_throttle_event(self, event, payload): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "throttled"]): return @@ -232,6 +250,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._track(track_event, **args) def _track_commerror_event(self, event, payload): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "commerror"]): return @@ -255,6 +276,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._track(track_event, **args) def _track_printjob_event(self, event, payload): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "printjob"]): return @@ -304,6 +328,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._track(track_event, **args) def _track_printer_event(self, event, payload): + if not self._settings.get_boolean([b"enabled"]): + return + if not self._settings.get_boolean(["events", "printer"]): return From f6dd13af7af135d1ff97fe7d576f8754ebcadd80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 13 Dec 2018 15:24:24 +0100 Subject: [PATCH 19/27] tracking: add printer safety warnings to tracking We want to get an idea how many people are running unsafe firmware. --- .../plugins/printer_safety_check/__init__.py | 29 +++++++++++-------- src/octoprint/plugins/tracking/__init__.py | 14 +++++++++ .../templates/tracking_settings.jinja2 | 3 ++ 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 6970a9b16..01b118ced 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -25,35 +25,35 @@ Learn more at https://faq.octoprint.org/warning-{warning_type} """ # Anet A8 -ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_") +ANETA8_M115_TEST = ("aneta8", lambda name, data: name and name.lower().startswith("anet_a8_")) # Anycubic MEGA ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower() ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower() -ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower()) +ANYCUBIC_RECEIVED_TEST = ("anycubic", lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower())) # Creality CR-10s CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower() -CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower() +CR10S_RECEIVED_TEST = ("cr10s", lambda line: line and CR10S_AUTHOR in line.lower()) # Creality Ender 3 ENDER3_AUTHOR = " | Author: (Ender3)".lower() -ENDER3_RECEIVED_TEST = lambda line: line and ENDER3_AUTHOR in line.lower() +ENDER3_RECEIVED_TEST = ("ender3", lambda line: line and ENDER3_AUTHOR in line.lower()) # iMe on Micro3D -IME_M115_TEST = lambda name, data: name and name.lower().startswith("ime") +IME_M115_TEST = ("ime", lambda name, data: name and name.lower().startswith("ime")) # Malyan M200 aka Monoprice Select Mini, versions less than 4.0 -MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < get_comparable_version("4.0") +MALYANM200_M115_TEST = ("malyan_m200", lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < get_comparable_version("4.0")) # Stock Micro3D -MICRO3D_M115_TEST = lambda name, data: name and name.lower().startswith("micro3d") +MICRO3D_M115_TEST = ("micro3d", lambda name, data: name and name.lower().startswith("micro3d")) # Any Repetier versions < 0.92 -REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92") +REPETIER_BEFORE_092_M115_TEST = ("repetier_before_092", lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")) # THERMAL_PROTECTION capability reported as disabled -THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled +THERMAL_PROTECTION_CAP_TEST = ("capability", lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled) SAFETY_CHECKS = { "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, IME_M115_TEST, MALYANM200_M115_TEST, MICRO3D_M115_TEST, @@ -147,9 +147,14 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, if not checks or not message: continue - if any(x(*args, **kwargs) for x in checks): - self._register_warning(warning_type, message) - changes = True + for check_name, check in checks: + if check(*args, **kwargs): + self._register_warning(warning_type, message) + self._event_bus.fire("plugin_printer_safety_check_warning", dict(check_type=check_type, + check_name=check_name, + warning_type=warning_type)) + changes = True + break if changes: self._ping_clients() diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 8691bfb30..cdae60ce7 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -64,6 +64,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, plugin=True, update=True, printer=True, + printer_safety_check=True, throttled=True)) def get_settings_restricted_paths(self): @@ -116,6 +117,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, elif event in ("plugin_pi_support_throttle_state",): self._throttle_state = payload self._track_throttle_event(event, payload) + elif event in ("plugin_printer_safety_check_warning",): + self._track_printer_safety_event(event, payload) elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): self._track_printjob_event(event, payload) elif event in (Events.ERROR,): @@ -341,6 +344,17 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, args["printer_baudrate"] = self._printer_connection_parameters["baudrate"] self._track("printer_connected", **args) + def _track_printer_safety_event(self, event, payload): + if not self._settings.get_boolean([b"enabled"]): + return + + if not self._settings.get_boolean(["events", "printer_safety_check"]): + return + + self._track("printer_safety_warning", + printer_safety_warning_type=payload.get(b"warning_type", "unknown"), + printer_safety_check_name=payload.get(b"check_name", "unknown")) + def _track(self, event, **kwargs): if not self._settings.get_boolean([b"enabled"]): return diff --git a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 index 292a898bd..570038309 100644 --- a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 +++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 @@ -28,6 +28,9 @@ + From bf5bc14c8722a4e712cec0dfa2531a5005ed8650 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 13 Dec 2018 16:29:22 +0100 Subject: [PATCH 20/27] backup: fix needed space calculation It wasn't taking excludes into account. Now its calculation mirrors the zip file creation. --- src/octoprint/plugins/backup/__init__.py | 34 +++++++++++++++++------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index b00f5faf2..1d36918d1 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -514,11 +514,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, thread.start() @classmethod - def _get_disk_size(cls, path): + def _get_disk_size(cls, path, ignored=None): + if ignored is None: + ignored = [] + + if path in ignored: + return 0 + total = 0 for entry in scandir(path): if entry.is_dir(): - total += cls._get_disk_size(entry.path) + total += cls._get_disk_size(entry.path, ignored=ignored) elif entry.is_file(): total += entry.stat().st_size return total @@ -595,6 +601,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, on_backup_start=None, on_backup_done=None, on_backup_error=None): + exclude_by_default = ("generated", "logs", "watched",) + try: if exclude is None: exclude = [] @@ -605,14 +613,23 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, temporary_path = os.path.join(datafolder, ".{}".format(name)) final_path = os.path.join(datafolder, name) - size = cls._get_disk_size(basedir) - if not cls._free_space(os.path.dirname(temporary_path), size): - raise InsufficientSpace() - own_folder = datafolder defaults = [os.path.join(basedir, "config.yaml"),] + \ [os.path.join(basedir, folder) for folder in default_settings["folder"].keys()] + # check how much many bytes we are about to backup + size = os.stat(configfile).st_size + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + size += cls._get_disk_size(settings.global_get_basefolder(folder), + ignored=[own_folder,]) + size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,]) + + # since we can't know the compression ratio beforehand, we assume we need the same amount of space + if not cls._free_space(os.path.dirname(temporary_path), size): + raise InsufficientSpace() + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED if callable(on_backup_start): @@ -642,10 +659,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, # backup configured folder paths for folder in default_settings["folder"].keys(): - if folder in exclude: - continue - - if folder in ("generated", "logs", "watched",): + if folder in exclude or folder in exclude_by_default: continue add_to_zip(settings.global_get_basefolder(folder), From e30f1b9f82ceaf103bda8eb9ba7067652d092d9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 17 Dec 2018 12:29:19 +0100 Subject: [PATCH 21/27] Add "::1/128" to localNetworks for auto login See BillyBlaze/OctoPrint-TouchUI#266 --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 19a599e49..79a5d910b 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -324,7 +324,7 @@ default_settings = { "userManager": "octoprint.users.FilebasedUserManager", "userfile": None, "autologinLocal": False, - "localNetworks": ["127.0.0.0/8"], + "localNetworks": ["127.0.0.0/8", "::1/128"], "autologinAs": None, "trustBasicAuthentication": False, "checkBasicAuthenticationPassword": True From 99225244f1cccf8b5472f42eeb4f6b0542f91933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 17 Dec 2018 14:20:42 +0100 Subject: [PATCH 22/27] Add full version string to API --- docs/api/version.rst | 6 ++++-- src/octoprint/server/api/__init__.py | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/api/version.rst b/docs/api/version.rst index 47b0c56e0..9716139c4 100644 --- a/docs/api/version.rst +++ b/docs/api/version.rst @@ -7,7 +7,8 @@ Version information .. http:get:: /api/version Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing - the API version, ``server`` containing the server version. + the API version, ``server`` containing the server version, ``text`` containing the server version including + the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance). **Example Request** @@ -26,7 +27,8 @@ Version information { "api": "0.1", - "server": "1.1.0" + "server": "1.3.10", + "text": "OctoPrint 1.3.10" } :statuscode 200: No error diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index ed4cc7cee..c084dc18e 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -177,7 +177,8 @@ def apiPrinterState(): def apiVersion(): return jsonify({ "server": octoprint.server.VERSION, - "api": VERSION + "api": VERSION, + "text": "OctoPrint {}".format(octoprint.server.DISPLAY_VERSION) }) From a23d92158b485de5ef4c4531a041c6ca23ffdee2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 17 Dec 2018 17:47:22 +0100 Subject: [PATCH 23/27] tracking: Track uptime of OctoPrint in ping event That will give us an idea if the current hypothesis that quite a number of people are shutting down their instance at night is correct or not, which in turn will inform future startup optimizations. --- src/octoprint/plugins/tracking/__init__.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index cdae60ce7..cf1b79ab5 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -21,7 +21,7 @@ except ImportError: # noinspection PyCompatibility import concurrent.futures -from octoprint.util import RepeatedTimer +from octoprint.util import RepeatedTimer, monotonic_time from octoprint.util.version import get_octoprint_version_string from octoprint.events import Events @@ -48,6 +48,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._record_next_firmware_info = False + self._startup_time = monotonic_time() + def initialize(self): self._init_tracking() @@ -91,7 +93,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, def on_after_startup(self): ping = self._settings.get_int(["ping"]) if ping: - self._ping_worker = RepeatedTimer(ping, self._track_ping) + self._ping_worker = RepeatedTimer(ping, self._track_ping, run_first=True) self._ping_worker.start() # cautiously look for the get_throttled helper from pi_support @@ -167,7 +169,8 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, if not self._settings.get_boolean([b"enabled"]): return - self._track("ping") + uptime = int(monotonic_time() - self._startup_time) + self._track("ping", octoprint_uptime=uptime) def _track_startup(self): if not self._settings.get_boolean([b"enabled"]): From 27338385746ca9de735d4e18e6ce0f2dadae2259 Mon Sep 17 00:00:00 2001 From: Jubaleth Date: Mon, 17 Dec 2018 18:22:36 +0100 Subject: [PATCH 24/27] Corrected plugin manager failure exception message --- AUTHORS.md | 1 + src/octoprint/__init__.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/AUTHORS.md b/AUTHORS.md index d7cf88fea..e8fa8db9f 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -94,6 +94,7 @@ date of first contribution): * [Gaston Dombiak](https://github.com/gdombiak) * [Brad Fisher](https://github.com/bradcfisher) * [Aldo Hoeben](https://github.com/fieldofview) + * [Jubaleth](https://github.com/jubaleth) 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/src/octoprint/__init__.py b/src/octoprint/__init__.py index c3d3e1591..73a994f49 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -142,7 +142,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, ignore_blacklist=ignore_blacklist, connectivity_checker=connectivity_checker) except Exception as ex: - raise FatalStartupError("Could not initialize settings manager", cause=ex) + raise FatalStartupError("Could not initialize plugin manager", cause=ex) kwargs["plugin_manager"] = plugin_manager if callable(after_plugin_manager): From 52c7321c78c8a81b6b557d67fe5af44b8b32df4c Mon Sep 17 00:00:00 2001 From: Connor Wolf Date: Sun, 11 Nov 2018 07:32:48 +0100 Subject: [PATCH 25/27] Handle unsupported version at runtime. If you have an ancient setuptools, 4a36ddb3aa77b8d1b1a64c197607fa652705856c won't successfully prevent installing. These changes will at least give a sane error, rather then just barfing on random syntax errors due to the `unicode` type not being present in py3k. Cherry picked from 2f20f2d --- src/octoprint/__main__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index 3dd81998d..9b1a759fc 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -2,6 +2,10 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function +import sys +if sys.version_info[0] >= 3: + raise Exception("Octoprint does not support Python 3") + if __name__ == "__main__": import octoprint octoprint.main() From 4e9437114b0070bbf5415dda7c532098f336eab4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 19 Dec 2018 13:35:18 +0100 Subject: [PATCH 26/27] Change wording & exception type --- src/octoprint/__main__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index 9b1a759fc..b794f4798 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -4,7 +4,7 @@ from __future__ import absolute_import, division, print_function import sys if sys.version_info[0] >= 3: - raise Exception("Octoprint does not support Python 3") + raise RuntimeError("Sorry, OctoPrint does not yet support Python 3") if __name__ == "__main__": import octoprint From d452051c0a93034408bbefad4bd00a84b6ec3699 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 19 Dec 2018 14:47:52 +0100 Subject: [PATCH 27/27] Add systemd file As discussed in #1716 --- scripts/README.md | 17 +++++++++++++++++ scripts/octoprint.service | 12 ++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 scripts/README.md create mode 100644 scripts/octoprint.service diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 000000000..8fbc44621 --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,17 @@ +# init/systemd files for OctoPrint. + +Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different +setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly. + +## init + +``` +octoprint.default => /etc/default/octoprint +octoprint.init => /etc/init.d/octoprint +``` + +## systemd + +``` +octoprint.service => /etc/systemd/service/octoprint.service +``` diff --git a/scripts/octoprint.service b/scripts/octoprint.service new file mode 100644 index 000000000..e71e07b53 --- /dev/null +++ b/scripts/octoprint.service @@ -0,0 +1,12 @@ +[Unit] +Description=The snappy web interface for your 3D printer +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=pi +ExecStart=/home/pi/OctoPrint/venv/bin/octoprint + +[Install] +WantedBy=multi-user.target