diff --git a/.versioneer-lookup b/.versioneer-lookup index 1f56523dd..1e8c5e63d 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.10rc5 # so is regressionfix/... diff --git a/AUTHORS.md b/AUTHORS.md index 1eb57f8b8..c35aca85e 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -95,6 +95,7 @@ date of first contribution): * [Brad Fisher](https://github.com/bradcfisher) * [Aldo Hoeben](https://github.com/fieldofview) * [Henning Groß](https://github.com/hgross) + * [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/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/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: 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 diff --git a/setup.py b/setup.py index 39672f3b5..a66affe45 100644 --- a/setup.py +++ b/setup.py @@ -13,48 +13,52 @@ 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 = [ - "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.6", # avoid broken 2018.11.6. 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/__init__.py b/src/octoprint/__init__.py index 48cf8f25c..73a994f49 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) @@ -141,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): diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index 3dd81998d..b794f4798 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 RuntimeError("Sorry, OctoPrint does not yet support Python 3") + if __name__ == "__main__": import octoprint octoprint.main() 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/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 2c7704668..160f85070 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), diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 38a09533d..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 -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 = ("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/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index 0adf55ba0..13a631d89 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)) @@ -18,6 +20,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs): try: 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/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 577999f98..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() @@ -60,9 +62,11 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, ping=15*60, events=dict(startup=True, printjob=True, + commerror=True, plugin=True, update=True, printer=True, + printer_safety_check=True, throttled=True)) def get_settings_restricted_paths(self): @@ -89,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 @@ -115,8 +119,12 @@ 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,): + self._track_commerror_event(event, payload) elif event in (Events.CONNECTED,): self._printer_connection_parameters = dict(port=payload["port"], baudrate=payload["baudrate"]) @@ -158,9 +166,16 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, self._settings.save() def _track_ping(self): - self._track("ping") + if not self._settings.get_boolean([b"enabled"]): + return + + 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"]): + return + if not self._settings.get_boolean(["events", "startup"]): return @@ -181,12 +196,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 @@ -200,6 +221,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 @@ -209,6 +233,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 @@ -228,7 +255,36 @@ 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([b"enabled"]): + return + + 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([b"enabled"]): + return + if not self._settings.get_boolean(["events", "printjob"]): return @@ -255,6 +311,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" @@ -274,6 +334,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 @@ -284,6 +347,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 217bc26c6..570038309 100644 --- a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 +++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 @@ -28,9 +28,15 @@ + + 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: diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index c751b59dd..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 @@ -190,6 +191,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() @@ -242,6 +247,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 @@ -650,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 @@ -727,6 +738,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/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) }) 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/server/util/flask.py b/src/octoprint/server/util/flask.py index 51ca17048..85784564d 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): diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index e3f4e18ed..79a5d910b 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 @@ -323,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 @@ -1309,15 +1310,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 @@ -1334,7 +1345,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 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 }); } 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/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("
")); 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
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):