From 1fdd0a7ee17da7fe737512d830c8fbd52a7855e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 4 Aug 2021 15:50:19 +0200 Subject: [PATCH 001/269] =?UTF-8?q?=F0=9F=94=96=20maintenance=20is=20now?= =?UTF-8?q?=201.8.0.dev?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .versioneer-lookup | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.versioneer-lookup b/.versioneer-lookup index 489ea1acb..22e03c712 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.7.0 +# maintenance is currently the branch for preparation of maintenance release 1.8.0 # so are any fix/... and improve/... branches -maintenance 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev -fix/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev -improve/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev +maintenance 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev +fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev +improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev # staging/bugfix is the branch for preparation of the 1.6.1 bugfix release # so are any bug/... branches From 9c072d6440269e46b754ff988fe10f4656cad39b Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 6 Sep 2021 15:03:51 -0400 Subject: [PATCH 002/269] Replace multiple globs with single regex The existing code lists the directory contents 7 times. This usually isn't a big deal, but I'm running Octoprint on a really slow ARM board, so this ends up taking 123ms (coming out to 17ms per call). We can speed this up a lot by only listing the files once, and searching through them. With this change, this function is fast enough that it doesn't show up in the profiler --- src/octoprint/util/comm.py | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 694d180a0..c4f0f5d6e 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -188,6 +188,25 @@ regex_firmware_splitter = re.compile(r"(^|\s+)([A-Z][A-Z0-9_]*):") regex_resend_linenumber = re.compile(r"(N|N:)?(?P%s)" % regex_int_pattern) """Regex to use for request line numbers in resend requests""" +regex_serial_devices = re.compile(r"^(?:ttyUSB|ttyACM|tty\.usb|cu\.|cuaU|ttyS|rfcomm).*") +"""Regex used to filter out valid tty devices""" + + +def _searchFiles(directory, pattern): + """ + Searches the directory for files matching the regex pattern + + We could use glob, but that might require multiple glob executions (and + multiple directory file listings), which can end up being slow on the + low-end devices we support. + """ + result = [] + with os.scandir(directory) as it: + for entry in it: + if pattern.match(entry.name): + result.append(entry.path) + return result + def serialList(): if os.name == "nt": @@ -204,15 +223,7 @@ def serialList(): pass else: - candidates = ( - glob.glob("/dev/ttyUSB*") - + glob.glob("/dev/ttyACM*") - + glob.glob("/dev/tty.usb*") - + glob.glob("/dev/cu.*") - + glob.glob("/dev/cuaU*") - + glob.glob("/dev/ttyS*") - + glob.glob("/dev/rfcomm*") - ) + candidates = _searchFiles("/dev", regex_serial_devices) # additional ports additionalPorts = settings().get(["serial", "additionalPorts"]) From 01855da9158495c1240ba28d5a81f9f26472c81e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Sep 2021 16:13:31 +0200 Subject: [PATCH 003/269] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Make=20py2=20compa?= =?UTF-8?q?tible=20&=20internalize=20search?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We only use the search in one single place, it's not part of an external API and three lines only. It makes sense to internalize it into serialList. Also, python 2 doesn't yet have os.scandir, so use the fallback implementation in that case. --- src/octoprint/util/comm.py | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index c4f0f5d6e..eb1e909f3 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -24,6 +24,11 @@ try: except ImportError: import Queue as queue +try: + from os import scandir +except ImportError: + from scandir import scandir + import logging from collections import deque @@ -192,22 +197,6 @@ regex_serial_devices = re.compile(r"^(?:ttyUSB|ttyACM|tty\.usb|cu\.|cuaU|ttyS|rf """Regex used to filter out valid tty devices""" -def _searchFiles(directory, pattern): - """ - Searches the directory for files matching the regex pattern - - We could use glob, but that might require multiple glob executions (and - multiple directory file listings), which can end up being slow on the - low-end devices we support. - """ - result = [] - with os.scandir(directory) as it: - for entry in it: - if pattern.match(entry.name): - result.append(entry.path) - return result - - def serialList(): if os.name == "nt": candidates = [] @@ -223,7 +212,11 @@ def serialList(): pass else: - candidates = _searchFiles("/dev", regex_serial_devices) + candidates = [] + with scandir("/dev") as it: + for entry in it: + if regex_serial_devices.match(entry.name): + candidates.append(entry.path) # additional ports additionalPorts = settings().get(["serial", "additionalPorts"]) From 0bd554428452f820b3aa1cd537a15cd0348c3645 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 8 Sep 2021 17:45:18 -0400 Subject: [PATCH 004/269] Add static files to .ignore This file is used by at least ripgrep and fd to know which files they should not look into when searching --- .ignore | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .ignore diff --git a/.ignore b/.ignore new file mode 100644 index 000000000..c4d12f75e --- /dev/null +++ b/.ignore @@ -0,0 +1,4 @@ +# ripgrep ignore file + +src/octoprint/static/vendor/ +src/octoprint/vendor/ From f3c0c29f692426511e23d17e39ba563eaab55d44 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 8 Sep 2021 18:55:30 -0400 Subject: [PATCH 005/269] Use C YAML loader when possible This is a lot faster: before _get_options: .339, .317, .220, .321, .315 after _get_options: .037, .106, .037, .145, .089 --- src/octoprint/__init__.py | 18 ++- src/octoprint/access/groups.py | 13 +-- src/octoprint/access/users.py | 106 ++++++++---------- src/octoprint/cli/analysis.py | 13 +-- src/octoprint/cli/client.py | 6 +- src/octoprint/cli/config.py | 10 +- src/octoprint/environment.py | 6 +- src/octoprint/filemanager/__init__.py | 14 +-- src/octoprint/filemanager/analysis.py | 5 +- src/octoprint/filemanager/storage.py | 33 +++--- src/octoprint/plugins/appkeys/__init__.py | 17 +-- src/octoprint/plugins/backup/__init__.py | 7 +- src/octoprint/plugins/logging/__init__.py | 13 +-- .../plugins/softwareupdate/__init__.py | 33 ++---- src/octoprint/printer/profile.py | 20 ++-- src/octoprint/server/api/languages.py | 8 +- src/octoprint/server/util/flask.py | 17 +-- src/octoprint/settings.py | 32 ++---- src/octoprint/util/yaml.py | 94 ++++++++++++++++ tests/filemanager/test_filemanager.py | 38 +++---- 20 files changed, 249 insertions(+), 254 deletions(-) create mode 100644 src/octoprint/util/yaml.py diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index c2e61d2b3..86940e08d 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -2,7 +2,6 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals -import io import logging as log import os import sys @@ -391,10 +390,9 @@ def init_logging( config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): - import yaml + from octoprint.util import yaml - with io.open(logging_file, "rt", encoding="utf-8") as f: - config_from_file = yaml.safe_load(f) + config_from_file = yaml.load_from_file(path=logging_file) # we merge that with the default config if config_from_file is not None and isinstance(config_from_file, dict): @@ -742,9 +740,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): import time import requests - import yaml - from octoprint.util import bom_aware_open from octoprint.util.version import is_octoprint_compatible, is_python_compatible logger = log.getLogger(__name__ + ".startup") @@ -810,8 +806,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if os.stat(path).st_mtime + ttl < time.time(): return None - with bom_aware_open(path, encoding="utf-8", mode="rt") as f: - result = yaml.safe_load(f) + from octoprint.util import yaml + + result = yaml.load_from_file(path=path) if isinstance(result, list): return result @@ -824,8 +821,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if cache is not None: try: - with bom_aware_open(cache, encoding="utf-8", mode="wt") as f: - yaml.safe_dump(result, f) + from octoprint.util import yaml + + yaml.save_to_file(result, path=cache) except Exception as e: logger.info( "Fetched plugin blacklist but couldn't write it to its cache file: %s", diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index f81b7cf06..a461cb299 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -5,18 +5,16 @@ __author__ = "Marc Hannappel " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os from functools import partial -import yaml from past.builtins import basestring from octoprint.access import ADMIN_GROUP, GUEST_GROUP, READONLY_GROUP, USER_GROUP from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.settings import settings -from octoprint.util import atomic_write +from octoprint.util import atomic_write, yaml from octoprint.vendor.flask_principal import Need, Permission GroupNeed = partial(Need, "group") @@ -232,8 +230,7 @@ class FilebasedGroupManager(GroupManager): def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: - with io.open(self._groupfile, "rt", encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._groupfile) if "groups" not in data: groups = data @@ -349,11 +346,7 @@ class FilebasedGroupManager(GroupManager): with atomic_write( self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666 ) as f: - import yaml - - yaml.safe_dump( - data, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(data, file=f, pretty=True) self._dirty = False self._load() diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 515c96c85..a19c4ce3b 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -5,7 +5,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import hashlib -import io import logging import os import uuid @@ -14,7 +13,6 @@ import uuid from builtins import bytes, range import wrapt -import yaml from flask_login import AnonymousUserMixin, UserMixin from past.builtins import basestring from werkzeug.local import LocalProxy @@ -24,7 +22,7 @@ from octoprint.access.permissions import OctoPrintPermission, Permissions from octoprint.settings import settings as s from octoprint.util import atomic_write, deprecated, generate_api_key from octoprint.util import get_fully_qualified_classname as fqcn -from octoprint.util import monotonic_time, to_bytes +from octoprint.util import monotonic_time, to_bytes, yaml class UserManager(GroupChangeListener, object): @@ -519,64 +517,60 @@ class FilebasedUserManager(UserManager): def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): - # noinspection PyBroadException - with io.open(self._userfile, "rt", encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._userfile) - if not data or not isinstance(data, dict): - self._logger.fatal( - "{} does not contain a valid map of users. Fix " - "the file, or remove it, then restart OctoPrint.".format( - self._userfile - ) + if not data or not isinstance(data, dict): + self._logger.fatal( + "{} does not contain a valid map of users. Fix " + "the file, or remove it, then restart OctoPrint.".format( + self._userfile ) - raise CorruptUserStorage() + ) + raise CorruptUserStorage() - for name, attributes in data.items(): - if not isinstance(attributes, dict): - continue + for name, attributes in data.items(): + if not isinstance(attributes, dict): + continue - permissions = [] - if "permissions" in attributes: - permissions = attributes["permissions"] + permissions = [] + if "permissions" in attributes: + permissions = attributes["permissions"] - if "groups" in attributes: - groups = set(attributes["groups"]) - else: - groups = {self._group_manager.user_group} + if "groups" in attributes: + groups = set(attributes["groups"]) + else: + groups = {self._group_manager.user_group} - # migrate from roles to permissions - if "roles" in attributes and "permissions" not in attributes: - self._logger.info( - "Migrating user {} to new granular permission system".format( - name - ) - ) - - groups |= set(self._migrate_roles_to_groups(attributes["roles"])) - self._dirty = True - - apikey = None - if "apikey" in attributes: - apikey = attributes["apikey"] - settings = {} - if "settings" in attributes: - settings = attributes["settings"] - - self._users[name] = User( - username=name, - passwordHash=attributes["password"], - active=attributes["active"], - permissions=self._to_permissions(*permissions), - groups=self._to_groups(*groups), - apikey=apikey, - settings=settings, + # migrate from roles to permissions + if "roles" in attributes and "permissions" not in attributes: + self._logger.info( + "Migrating user {} to new granular permission system".format(name) ) - for sessionid in self._sessionids_by_userid.get(name, set()): - if sessionid in self._session_users_by_session: - self._session_users_by_session[sessionid].update_user( - self._users[name] - ) + + groups |= set(self._migrate_roles_to_groups(attributes["roles"])) + self._dirty = True + + apikey = None + if "apikey" in attributes: + apikey = attributes["apikey"] + settings = {} + if "settings" in attributes: + settings = attributes["settings"] + + self._users[name] = User( + username=name, + passwordHash=attributes["password"], + active=attributes["active"], + permissions=self._to_permissions(*permissions), + groups=self._to_groups(*groups), + apikey=apikey, + settings=settings, + ) + for sessionid in self._sessionids_by_userid.get(name, set()): + if sessionid in self._session_users_by_session: + self._session_users_by_session[sessionid].update_user( + self._users[name] + ) if self._dirty: self._save() @@ -608,9 +602,7 @@ class FilebasedUserManager(UserManager): with atomic_write( self._userfile, mode="wt", permissions=0o600, max_permissions=0o666 ) as f: - yaml.safe_dump( - data, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(data, file=f, pretty=True) self._dirty = False self._load() diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index b2cf736de..aaaaf5762 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -8,6 +8,8 @@ import sys import click +from octoprint.util import yaml + click.disable_unicode_literals_warning = True # ~~ "octoprint util" commands @@ -97,8 +99,6 @@ def gcode_command( import time - import yaml - from octoprint.util import monotonic_time from octoprint.util.gcodeInterpreter import gcode @@ -156,14 +156,7 @@ def gcode_command( sys.exit(-1) click.echo("RESULTS:") - click.echo( - yaml.safe_dump( - interpreter.get_result(), - default_flow_style=False, - indent=2, - allow_unicode=True, - ) - ) + click.echo(yaml.dump(interpreter.get_result(), pretty=True)) if __name__ == "__main__": diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 9d9b3b00a..98d21d37d 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -13,6 +13,7 @@ from past.builtins import unicode import octoprint_client from octoprint import FatalStartupError, init_settings from octoprint.cli import bulk_options, get_ctx_obj_option +from octoprint.util import yaml click.disable_unicode_literals_warning = True @@ -170,10 +171,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): with io.open(file_path, "rt") as fp: data = json.load(fp) else: - import yaml - - with io.open(file_path, "rt") as fp: - data = yaml.safe_load(fp) + data = yaml.load_from_file(path=file_path) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index f07653c2c..c2b79994a 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -10,10 +10,10 @@ import logging import pprint import click -import yaml from octoprint import FatalStartupError, init_settings from octoprint.cli import get_ctx_obj_option, standard_options +from octoprint.util import yaml click.disable_unicode_literals_warning = True @@ -217,9 +217,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False): if as_json: output = json.dumps(value) elif as_yaml: - output = yaml.safe_dump( - value, default_flow_style=False, indent=2, allow_unicode=True - ) + output = yaml.dump(value, pretty=True) elif as_raw: output = value else: @@ -243,9 +241,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False): if as_json: output = json.dumps(value) elif as_yaml: - output = yaml.safe_dump( - value, default_flow_style=False, indent=2, allow_unicode=True - ) + output = yaml.dump(value, pretty=True) elif as_raw: output = value else: diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 7011ad4b0..944d5c840 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -11,9 +11,9 @@ import sys import threading import psutil -import yaml from octoprint.plugin import EnvironmentDetectionPlugin +from octoprint.util import yaml from octoprint.util.platform import get_os from octoprint.util.version import get_python_version_string @@ -168,9 +168,7 @@ class EnvironmentDetector(object): self.run_detection() environment = copy.deepcopy(self._cache) - dumped_environment = yaml.safe_dump( - environment, default_flow_style=False, indent=2, allow_unicode=True - ).strip() + dumped_environment = yaml.dump(environment, pretty=True).strip() environment_lines = "\n".join( map(lambda l: "| {}".format(l), dumped_environment.split("\n")) ) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 46cc59eac..9fc753936 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -5,7 +5,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os from collections import namedtuple @@ -16,6 +15,7 @@ import octoprint.plugin import octoprint.util from octoprint.events import Events, eventManager from octoprint.util import get_fully_qualified_classname as fqcn +from octoprint.util import yaml from .analysis import AnalysisQueue, QueueEntry # noqa: F401 from .destinations import FileDestinations # noqa: F401 @@ -941,8 +941,6 @@ class FileManager(object): def save_recovery_data(self, origin, path, pos): import time - import yaml - from octoprint.util import atomic_write data = { @@ -953,9 +951,7 @@ class FileManager(object): } try: with atomic_write(self._recovery_file, mode="wt", max_permissions=0o666) as f: - yaml.safe_dump( - data, stream=f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(data, file=f, pretty=True) except Exception: self._logger.exception( "Could not write recovery data to file {}".format(self._recovery_file) @@ -976,11 +972,9 @@ class FileManager(object): if not os.path.isfile(self._recovery_file): return None - import yaml - try: - with io.open(self._recovery_file, "rt", encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._recovery_file) + if not isinstance(data, dict) or not all( map(lambda x: x in data, ("origin", "path", "pos", "date")) ): diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 89a59816c..c589cd939 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -22,7 +22,7 @@ from octoprint.events import Events, eventManager from octoprint.settings import settings from octoprint.util import dict_merge from octoprint.util import get_fully_qualified_classname as fqcn -from octoprint.util import monotonic_time +from octoprint.util import monotonic_time, yaml from octoprint.util.platform import CLOSE_FDS EMPTY_RESULT = { @@ -414,7 +414,6 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): import sys import sarge - import yaml if self._current.analysis and all( map( @@ -508,7 +507,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): raise RuntimeError("No analysis result found") else: _, output = output.split("RESULTS:") - analysis = yaml.safe_load(output) + analysis = yaml.load_from_file(file=output) result["printingArea"] = analysis["printing_area"] result["dimensions"] = analysis["dimensions"] diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 7fd8f72e8..bc7e382ac 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -23,7 +23,14 @@ from contextlib import contextmanager from past.builtins import basestring import octoprint.filemanager -from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode +from octoprint.util import ( + atomic_write, + is_hidden_path, + time_this, + to_bytes, + to_unicode, + yaml, +) from octoprint.util.files import sanitize_filename @@ -515,10 +522,7 @@ class LocalFileStorage(StorageInterface): if os.path.exists(old_metadata_path): # load the old metadata file try: - with io.open(old_metadata_path, "rt", encoding="utf-8") as f: - import yaml - - self._old_metadata = yaml.safe_load(f) + self._old_metadata = yaml.load_from_file(path=old_metadata_path) except Exception: self._logger.exception("Error while loading old metadata file") @@ -1903,8 +1907,6 @@ class LocalFileStorage(StorageInterface): # we switched to json in 1.3.9 - if we still have yaml here, migrate it now import json - import yaml - with self._get_persisted_metadata_lock(path): metadata_path_yaml = os.path.join(path, ".metadata.yaml") metadata_path_json = os.path.join(path, ".metadata.json") @@ -1925,16 +1927,13 @@ class LocalFileStorage(StorageInterface): ) return - with io.open(metadata_path_yaml, "rt", encoding="utf-8") as f: - try: - metadata = yaml.safe_load(f) - except Exception: - self._logger.exception( - "Error while reading .metadata.yaml from {path}".format( - **locals() - ) - ) - return + try: + metadata = yaml.load_from_file(path=metadata_path_yaml) + except Exception: + self._logger.exception( + "Error while reading .metadata.yaml from {path}".format(**locals()) + ) + return if not isinstance(metadata, dict): # looks invalid, ignore it diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index f9b77d481..7e5e8a561 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -1,13 +1,11 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals -import io import os import threading from collections import defaultdict import flask -import yaml from flask_babel import gettext import octoprint.plugin @@ -16,7 +14,13 @@ from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT, admin_permission, current_user from octoprint.server.util.flask import no_firstrun_access, restricted_access from octoprint.settings import valid_boolean_trues -from octoprint.util import ResettableTimer, atomic_write, generate_api_key, monotonic_time +from octoprint.util import ( + ResettableTimer, + atomic_write, + generate_api_key, + monotonic_time, + yaml, +) CUTOFF_TIME = 10 * 60 # 10min POLL_TIMEOUT = 5 # 5 seconds @@ -441,10 +445,7 @@ class AppKeysPlugin( return try: - with io.open( - self._key_path, "rt", encoding="utf-8", errors="strict" - ) as f: - persisted = yaml.safe_load(f) + persisted = yaml.load_from_file(path=self._key_path) except Exception: self._logger.exception( "Could not load application keys from {}".format(self._key_path) @@ -469,7 +470,7 @@ class AppKeysPlugin( try: with atomic_write(self._key_path, mode="wt") as f: - yaml.safe_dump(to_persist, f, allow_unicode=True) + yaml.save_to_file(to_persist, file=f) except Exception: self._logger.exception( "Could not write application keys to {}".format(self._key_path) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index f8e324e68..3380f7d13 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -11,7 +11,7 @@ from octoprint.events import Events from octoprint.server import NO_CONTENT from octoprint.server.util.flask import no_firstrun_access from octoprint.settings import default_settings -from octoprint.util import is_hidden_path, to_bytes +from octoprint.util import is_hidden_path, to_bytes, yaml from octoprint.util.pip import create_pip_caller from octoprint.util.platform import is_os_compatible from octoprint.util.version import ( @@ -1197,10 +1197,7 @@ class BackupPlugin( on_restore_failed(path) return False - import yaml - - with io.open(configfile, "rt", encoding="utf-8") as f: - configdata = yaml.safe_load(f) + configdata = yaml.load_from_file(path=configfile) userfile = os.path.join(temp, "basedir", "users.yaml") if not os.path.exists(userfile): diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index a1c8b57cb..748c07680 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -4,10 +4,8 @@ from __future__ import absolute_import, division, print_function, unicode_litera __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os -import yaml from flask import abort, jsonify, request, url_for from flask_babel import gettext from werkzeug.exceptions import BadRequest @@ -19,7 +17,7 @@ from octoprint.access.permissions import Permissions from octoprint.server import NO_CONTENT from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado from octoprint.settings import settings -from octoprint.util import is_hidden_path +from octoprint.util import is_hidden_path, yaml try: from os import scandir @@ -188,10 +186,7 @@ class LoggingPlugin( config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): - import yaml - - with io.open(logging_file, "rt", encoding="utf-8") as f: - config_from_file = yaml.safe_load(f) + config_from_file = yaml.load_from_file(path=logging_file) return config_from_file def _get_logging_levels(self): @@ -241,9 +236,7 @@ class LoggingPlugin( with octoprint.util.atomic_write( self._get_logging_file(), mode="wt", max_permissions=0o666 ) as f: - yaml.safe_dump( - config, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(config, file=f, pretty=True) # set runtime logging levels now for logger, level in new_levels.items(): diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 0c332fd6c..23040eeae 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -10,7 +10,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy import hashlib -import io import logging import logging.handlers import os @@ -34,7 +33,7 @@ from octoprint.server.util.flask import ( no_firstrun_access, with_revalidation_checking, ) -from octoprint.util import dict_merge, get_formatted_size, to_unicode +from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml from octoprint.util.pip import create_pip_caller from octoprint.util.version import ( get_comparable_version, @@ -476,11 +475,8 @@ class SoftwareUpdatePlugin( if not os.path.isfile(self._version_cache_path): return - import yaml - try: - with io.open(self._version_cache_path, "rt", encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._version_cache_path) timestamp = os.stat(self._version_cache_path).st_mtime except Exception: self._logger.exception("Error while loading version cache from disk") @@ -517,8 +513,6 @@ class SoftwareUpdatePlugin( self._logger.exception("Error parsing in version cache data") def _save_version_cache(self): - import yaml - from octoprint._version import get_versions from octoprint.util import atomic_write @@ -528,13 +522,7 @@ class SoftwareUpdatePlugin( with atomic_write( self._version_cache_path, mode="wt", max_permissions=0o666 ) as file_obj: - yaml.safe_dump( - self._version_cache, - stream=file_obj, - default_flow_style=False, - indent=2, - allow_unicode=True, - ) + yaml.save_to_file(self._version_cache, file=file_obj, pretty=True) self._version_cache_dirty = False self._version_cache_timestamp = time.time() @@ -552,11 +540,8 @@ class SoftwareUpdatePlugin( if not os.path.isfile(self._update_log_path): return - import yaml - try: - with io.open(self._update_log_path, "rt", encoding="utf-8") as f: - data = yaml.safe_load(f) + data = yaml.load_from_file(path=self._update_log_path) except Exception: self._logger.exception("Error while loading update log from disk") else: @@ -588,20 +573,16 @@ class SoftwareUpdatePlugin( self._logger.info("Loaded update log from disk") def _save_update_log(self): - import yaml - from octoprint.util import atomic_write with self._update_log_mutex: with atomic_write( self._update_log_path, mode="wt", max_permissions=0o666 ) as file_obj: - yaml.safe_dump( + yaml.save_to_file( sorted(self._update_log, key=lambda x: x["datetime"]), - stream=file_obj, - default_flow_style=False, - indent=2, - allow_unicode=True, + file=file_obj, + pretty=True, ) self._update_log_dirty = False diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index 5ac323d13..03db920a7 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -147,7 +147,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy -import io import logging import os @@ -157,7 +156,13 @@ except ImportError: from scandir import scandir from octoprint.settings import settings -from octoprint.util import dict_contains_keys, dict_merge, dict_sanitize, is_hidden_path +from octoprint.util import ( + dict_contains_keys, + dict_merge, + dict_sanitize, + is_hidden_path, + yaml, +) class SaveError(Exception): @@ -507,10 +512,7 @@ class PrinterProfileManager(object): if not os.path.exists(path) or not os.path.isfile(path): return None - import yaml - - with io.open(path, "rt", encoding="utf-8") as f: - profile = yaml.safe_load(f) + profile = yaml.load_from_file(path=path) if profile is None or not isinstance(profile, dict): raise InvalidProfileError("Profile is None or not a dictionary") @@ -542,15 +544,11 @@ class PrinterProfileManager(object): "Profile %s already exists and not allowed to overwrite" % profile["id"] ) - import yaml - from octoprint.util import atomic_write try: with atomic_write(path, mode="wt", max_permissions=0o666) as f: - yaml.safe_dump( - profile, f, default_flow_style=False, indent=2, allow_unicode=True - ) + yaml.save_to_file(profile, file=f, pretty=True) except Exception as e: self._logger.exception( "Error while trying to save profile %s" % profile["id"] diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 46710b966..b3f6f1b5c 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -5,12 +5,13 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os import tarfile import zipfile +from octoprint.util import yaml + try: from os import scandir except ImportError: @@ -49,11 +50,8 @@ def getInstalledLanguagePacks(): meta_path = os.path.join(path, "meta.yaml") if os.path.isfile(meta_path): - import yaml - try: - with io.open(meta_path, "rt", encoding="utf-8") as f: - meta = yaml.safe_load(f) + meta = yaml.load_from_file(path=meta_path) except Exception: logging.getLogger(__name__).exception("Could not load %s", meta_path) pass diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index cf7434f0b..74c044990 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -34,7 +34,7 @@ import octoprint.server import octoprint.vendor.flask_principal as flask_principal from octoprint.events import Events, eventManager from octoprint.settings import settings -from octoprint.util import DefaultOrderedDict, deprecated +from octoprint.util import DefaultOrderedDict, deprecated, yaml from octoprint.util.json import JsonEncoding from octoprint.util.net import is_lan_address @@ -1023,13 +1023,10 @@ class PreemptiveCache(object): return all_data def get_all_data(self): - import yaml - cache_data = None with self._lock: try: - with io.open(self.cachefile, "rt") as f: - cache_data = yaml.safe_load(f) + cache_data = yaml.load_from_file(path=self.cachefile) except IOError as e: import errno @@ -1052,20 +1049,12 @@ class PreemptiveCache(object): return cache_data.get(root, list()) def set_all_data(self, data): - import yaml - from octoprint.util import atomic_write with self._lock: try: with atomic_write(self.cachefile, "wt", max_permissions=0o666) as handle: - yaml.safe_dump( - data, - handle, - default_flow_style=False, - indent=2, - allow_unicode=True, - ) + yaml.save_to_file(data, file=handle, pretty=True) except Exception: self._logger.exception("Error while writing {}".format(self.cachefile)) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 0991a752b..0ea890e49 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -31,11 +31,9 @@ import re import sys import time -import yaml -import yaml.parser - -# noinspection PyCompatibility +# noinspection PyCompatibilitys from past.builtins import basestring +from yaml import YAMLError try: from collections import ChainMap @@ -58,6 +56,7 @@ from octoprint.util import ( dict_merge, generate_api_key, is_hidden_path, + yaml, ) _APPNAME = "OctoPrint" @@ -956,9 +955,7 @@ class Settings(object): @property def effective_yaml(self): - import yaml - - return yaml.safe_dump(self.effective) + return yaml.dump(self.effective) @property def effective_hash(self): @@ -974,9 +971,7 @@ class Settings(object): @property def config_yaml(self): - import yaml - - return yaml.safe_dump(self._config) + return yaml.dump(self._config) @property def config_hash(self): @@ -1028,10 +1023,10 @@ class Settings(object): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): with io.open(self._configfile, "rt", encoding="utf-8", errors="replace") as f: try: - self._config = yaml.safe_load(f) + self._config = yaml.load_from_file(file=f) self._mtime = self.last_modified - except yaml.YAMLError as e: + except YAMLError as e: details = str(e) if hasattr(e, "problem_mark"): @@ -1097,8 +1092,7 @@ class Settings(object): if isinstance(overlay, basestring): if os.path.exists(overlay) and os.path.isfile(overlay): - with io.open(overlay, "rt", encoding="utf-8", errors="replace") as f: - config = yaml.safe_load(f) + config = yaml.load_from_file(path=overlay) elif isinstance(overlay, dict): config = overlay else: @@ -1119,7 +1113,7 @@ class Settings(object): assert isinstance(overlay, dict) if key is None: - overlay_yaml = yaml.safe_dump(overlay) + overlay_yaml = yaml.dump(overlay) import hashlib hash = hashlib.md5() @@ -1688,13 +1682,7 @@ class Settings(object): permissions=0o600, max_permissions=0o666, ) as configFile: - yaml.safe_dump( - self._config, - configFile, - default_flow_style=False, - indent=2, - allow_unicode=True, - ) + yaml.save_to_file(self._config, file=configFile) self._dirty = False except Exception: self._logger.exception("Error while saving config.yaml!") diff --git a/src/octoprint/util/yaml.py b/src/octoprint/util/yaml.py new file mode 100644 index 000000000..914c4cea3 --- /dev/null +++ b/src/octoprint/util/yaml.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import + +import io + +from octoprint.util import bom_aware_open + + +def load_from_file(file=None, path=None): + """ + Safely and performantly loads yaml data from the given source. Either a + path or a file must be passed in. + + :rtype: Union[dict[Hashable, Any], list, None] + :type path: str | None + :type file: typing.TextIO | None + """ + if path is not None: + assert file is None + with bom_aware_open(path, mode="rt", encoding="utf-8") as f: + return load_from_file(file=f) + + if file is not None: + assert path is None + + assert path is not None or file is not None, "this function requires an input file" + + import yaml + + try: + from yaml import CSafeLoader as SafeLoader + except ImportError: + from yaml import SafeLoader + + return yaml.load(file, Loader=SafeLoader) + + +def _save_to_file_base(data, file=None, path=None, pretty=False, **kwargs): + if path is not None: + assert file is None + with io.open(path, "wt", encoding="utf-8") as f: + return _save_to_file_base(data, file=f, pretty=pretty, **kwargs) + + if file is not None: + assert path is None + + import yaml + + try: + from yaml import CSafeDumper as SafeDumper + except ImportError: + from yaml import SafeDumper + + if pretty: + # make each element go on a new line and indent by 2 + kwargs.update(default_flow_style=False, indent=2) + + return yaml.dump( + data, + stream=file, + Dumper=SafeDumper, + allow_unicode=True, # no good reason not to allow it these days + **kwargs + ) + + +def save_to_file(data, file=None, path=None, pretty=False, **kwargs): + """ + Safely and performantly dumps the `data` to yaml. + + To dump to a string, use `yaml.dump()`. + + :type data: object + :param data: the data to be serialized + :type file: typing.TextIO | None + :type path: str | None + :type pretty: bool + :param pretty: formats the output yaml into a more human-friendly format + """ + assert file is not None or path is not None, "this function requires an output file" + _save_to_file_base(data, file=file, path=path, pretty=pretty, **kwargs) + + +def dump(data, pretty=False, **kwargs): + """ + Safely and performantly dumps the `data` to a yaml string. + + :param data: the data to be serialized + :param pretty: formats the output yaml into a more human-friendly format + :param kwargs: any other args to be passed to the internal yaml.dump() call. + :return: yaml-serialized data + :rtype: str + """ + return _save_to_file_base(data, file=None, pretty=pretty, **kwargs) diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index 7be8f3016..52b45c910 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -382,9 +382,11 @@ class FileManagerTest(unittest.TestCase): ) @mock.patch("octoprint.util.atomic_write", create=True) - @mock.patch("yaml.safe_dump", create=True) + @mock.patch("octoprint.util.yaml.save_to_file", create=True) @mock.patch("time.time") - def test_save_recovery_data(self, mock_time, mock_yaml_safe_dump, mock_atomic_write): + def test_save_recovery_data( + self, mock_time, mock_yaml_save_to_file, mock_atomic_write + ): import os now = 123456789 @@ -411,16 +413,14 @@ class FileManagerTest(unittest.TestCase): "date": now, } - mock_yaml_safe_dump.assert_called_with( + mock_yaml_save_to_file.assert_called_with( expected, - stream=mock_atomic_write_handle, - default_flow_style=False, - indent=2, - allow_unicode=True, + file=mock_atomic_write_handle, + pretty=True, ) @mock.patch("octoprint.util.atomic_write", create=True) - @mock.patch("yaml.safe_dump", create=True) + @mock.patch("octoprint.util.yaml.save_to_file", create=True) @mock.patch("time.time") def test_save_recovery_data_with_error( self, mock_time, mock_yaml_safe_dump, mock_atomic_write @@ -471,8 +471,6 @@ class FileManagerTest(unittest.TestCase): def test_get_recovery_data(self, mock_isfile): import os - import yaml - recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") data = { @@ -481,16 +479,14 @@ class FileManagerTest(unittest.TestCase): "pos": 1234, "date": 123456789, } - text_data = yaml.dump(data) - with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(read_data=text_data)) as m: - # moved safe_load to here so we could mock up the return value properly - with mock.patch("yaml.safe_load", return_value=data) as n: - result = self.file_manager.get_recovery_data() + # moved safe_load to here so we could mock up the return value properly + with mock.patch("octoprint.util.yaml.load_from_file", return_value=data) as n: + result = self.file_manager.get_recovery_data() - self.assertDictEqual(data, result) - n.assert_called_with(m()) - mock_isfile.assert_called_with(recovery_file) + self.assertDictEqual(data, result) + n.assert_called_with(path=recovery_file) + mock_isfile.assert_called_with(recovery_file) @mock.patch("os.path.isfile") def test_get_recovery_data_no_file(self, mock_isfile): @@ -501,17 +497,17 @@ class FileManagerTest(unittest.TestCase): self.assertIsNone(result) @mock.patch("os.path.isfile") - @mock.patch("yaml.safe_load") + @mock.patch("octoprint.util.yaml.load_from_file") @mock.patch("os.remove") def test_get_recovery_data_broken_file( - self, mock_remove, mock_yaml_safe_load, mock_isfile + self, mock_remove, mock_yaml_load, mock_isfile ): import os recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") mock_isfile.return_value = True - mock_yaml_safe_load.side_effect = RuntimeError + mock_yaml_load.side_effect = RuntimeError result = self.file_manager.get_recovery_data() From 411b925506a05e6b7821a999e0cd9edbace2ba0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 14 Sep 2021 17:56:16 +0200 Subject: [PATCH 006/269] =?UTF-8?q?=F0=9F=97=91=20Deprecate=20octoprint.ut?= =?UTF-8?q?il.bom=5Faware=5Fopen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The same can be achieved with io.open and a -sig encoding. To be removed in 2.0 Closes #4228 --- src/octoprint/util/__init__.py | 32 +++++++++++++++++++++++++ src/octoprint/util/comm.py | 14 +++++------ tests/util/test_file_helpers.py | 41 +++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 7 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index c940c5dbd..213e9e4f9 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -9,6 +9,7 @@ from __future__ import absolute_import, division, print_function, unicode_litera __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +import codecs import collections import contextlib import copy @@ -1078,7 +1079,9 @@ else: self.cleanup() +@deprecated("Please use io.open with '-sig' encoding instead", since="1.8.0") def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs): + # TODO Remove in 2.0.0 import codecs assert "b" not in mode, "binary mode not support by bom_aware_open" @@ -1103,6 +1106,35 @@ def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs): return io.open(filename, encoding=encoding, mode=mode, **kwargs) +BOMS = { + "utf-8-sig": codecs.BOM_UTF8, + "utf-16-le": codecs.BOM_UTF16_LE, + "utf-16-be": codecs.BOM_UTF16_BE, + "utf-32-le": codecs.BOM_UTF32_LE, + "utf-32-be": codecs.BOM_UTF32_BE, +} + + +def get_bom(filename, encoding): + """ + Check if the file has a BOM and if so return it. + + Params: + filename (str): The file to check. + encoding (str): The encoding to check for. + + Returns: + (bytes) the BOM or None if there is no BOM. + """ + with io.open(filename, mode="rb") as f: + header = f.read(4) + + for enc, bom in BOMS.items(): + if header.startswith(bom) and encoding.lower() == enc: + return bom + return None + + def is_hidden_path(path): if path is None: # we define a None path as not hidden here diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index eb1e909f3..315b7a7ce 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -14,6 +14,7 @@ import contextlib import copy import fnmatch import glob +import io import os import re import threading @@ -48,10 +49,10 @@ from octoprint.util import ( ResettableTimer, TypeAlreadyInQueue, TypedQueue, - bom_aware_open, chunks, filter_non_ascii, filter_non_utf8, + get_bom, get_exception_string, monotonic_time, sanitize_ascii, @@ -5648,18 +5649,17 @@ class PrintingGcodeFileInformation(PrintingFileInformation): """ PrintingFileInformation.start(self) with self._handle_mutex: - self._handle = bom_aware_open( - self._filename, encoding="utf-8", errors="replace", newline="" + bom = get_bom(self._filename, encoding="utf-8-sig") + self._handle = io.open( + self._filename, encoding="utf-8-sig", errors="replace", newline="" ) self._pos = self._handle.tell() - if self._handle.encoding.endswith("-sig"): + if bom: # Apparently we found an utf-8 bom in the file. # We need to add its length to our pos because it will # be stripped transparently and we'll have no chance # catching that. - import codecs - - self._pos += len(codecs.BOM_UTF8) + self._pos += len(bom) self._read_lines = 0 def close(self): diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index 3d57388d1..eda914849 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -113,6 +113,47 @@ class BomAwareOpenTest(unittest.TestCase): ) +class GetBomTest(unittest.TestCase): + """ + Tests for :func:`octoprint.util.get_bom`. + """ + + def setUp(self): + self.filename_utf8_with_bom = os.path.join( + os.path.abspath(os.path.dirname(__file__)), "_files", "utf8_with_bom.txt" + ) + self.filename_utf8_without_bom = os.path.join( + os.path.abspath(os.path.dirname(__file__)), "_files", "utf8_without_bom.txt" + ) + + def test_get_bom_no_bom(self): + """Tests that no BOM is returned if no BOM is present.""" + + # test + bom = octoprint.util.get_bom(self.filename_utf8_without_bom, "utf-8-sig") + + # assert + self.assertIsNone(bom) + + def test_get_bom_utf8_bom(self): + """Tests that a UTF8 BOM is returned if present.""" + + # test + bom = octoprint.util.get_bom(self.filename_utf8_with_bom, "utf-8-sig") + + # assert + self.assertEqual(bom, b"\xef\xbb\xbf") + + def test_get_bom_wrong_encoding(self): + """Tests that an UTF8 BOM is only returned if proper encoding was set.""" + + # test + bom = octoprint.util.get_bom(self.filename_utf8_with_bom, "utf-16-le") + + # assert + self.assertIsNone(bom) + + class TestAtomicWrite(unittest.TestCase): """ Tests for :func:`octoprint.util.atomic_write`. From 1509f38779bd2f4b261f32d65a9aad36fc64cd38 Mon Sep 17 00:00:00 2001 From: John Boiles Date: Tue, 14 Sep 2021 12:26:08 -0700 Subject: [PATCH 007/269] Move away from Ubuntu 16.04 Because it's going to be gone on September 20th 2021: https://github.com/actions/virtual-environments/issues/3287 --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ae1f20280..36387cde7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -95,7 +95,7 @@ jobs: test-e2e: name: 🧪 E2E tests needs: build - runs-on: ubuntu-16.04 + runs-on: ubuntu-18.04 steps: - name: ⬇ Checkout code uses: actions/checkout@v2 From d3bd4a895d79a089ef1777eeb5efebd0f4cf77ea Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 11 Sep 2021 14:11:25 -0400 Subject: [PATCH 008/269] Send Server-Timing header This is useful to be able to tell when a performance issue is due to the network or due to the actual execution time There's hardly any overhead, so send it with every request. --- src/octoprint/server/__init__.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index a2dde3b46..561b470db 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1392,6 +1392,10 @@ class Server(object): @app.before_request def before_request(): g.locale = self._get_locale() + + # used for performance measurement + g.start_time = octoprint.util.monotonic_time() + if self._debug and "perfprofile" in request.args: try: from pyinstrument import Profiler @@ -1415,6 +1419,11 @@ class Server(object): output_html = g.perfprofiler.output_html() return make_response(output_html) + if hasattr(g, "start_time"): + end_time = octoprint.util.monotonic_time() + duration_ms = int((end_time - g.start_time) * 1000) + response.headers.add("Server-Timing", "app;dur={}".format(duration_ms)) + return response from octoprint.util.jinja import MarkdownFilter From 4c854b435c08b7071ce6986034ffe60bb9218371 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 11 Sep 2021 07:31:59 -0400 Subject: [PATCH 009/269] Improve settings processing time This brings the load time of /api/settings on my crappy ARM board from 1s to 0.4s This is done by - optimizizing the hot loop inside deep_dict, which provides most the gain (to 0.46s) - using pickle for deep-copying, which is fast when doing lots of pointer chasing, but slow when doing long copies (to 0.37s) --- src/octoprint/settings.py | 31 +++++++++++-------------------- src/octoprint/util/__init__.py | 23 +++++++++++++++++++---- 2 files changed, 30 insertions(+), 24 deletions(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 0ea890e49..0fb13d796 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -22,7 +22,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import copy import fnmatch import io import logging @@ -54,6 +53,7 @@ from octoprint.util import ( CaseInsensitiveSet, atomic_write, dict_merge, + fast_deepcopy, generate_api_key, is_hidden_path, yaml, @@ -542,17 +542,14 @@ class DuplicateFolderPaths(InvalidSettings): class HierarchicalChainMap(ChainMap): - def deep_dict(self, root=None): - if root is None: - root = self + def deep_dict(self): + def deep_dict_inner(root): + return { + key: deep_dict_inner(root[key]) if isinstance(value, dict) else value + for key, value in root.items() + } - result = {} - for key, value in root.items(): - if isinstance(value, dict): - result[key] = self.deep_dict(root=self.__class__._get_next(key, root)) - else: - result[key] = value - return result + return deep_dict_inner(self) def has_path(self, path, only_local=False, only_defaults=False): if only_defaults: @@ -1778,19 +1775,13 @@ class Settings(object): except KeyError: raise NoSuchSettingsPath() - if preprocessors is not None: - try: - preprocessor = self._get_by_path(path, preprocessors) - except Exception: - pass - - if callable(preprocessor): - value = preprocessor(value) + if callable(preprocessor): + value = preprocessor(value) if do_copy: if isinstance(value, KeysView): value = list(value) - value = copy.deepcopy(value) + value = fast_deepcopy(value) if asdict: results[key] = value diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 213e9e4f9..589db7d39 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -46,6 +46,11 @@ try: except ImportError: import Queue as queue +try: + import cPickle as pickle +except ImportError: + import pickle + # noinspection PyCompatibility from past.builtins import basestring, unicode @@ -539,6 +544,18 @@ def is_running_from_source(): ) +def fast_deepcopy(obj): + # the best way to implement this would be as a C module, that way we'd be able to use + # the fast path every time. + try: + # implemented in C and much faster than deepcopy: + # https://stackoverflow.com/a/29385667 + return pickle.loads(pickle.dumps(obj, -1)) + except AttributeError: + # fall back when something unpickable is found + return copy.deepcopy(obj) + + def dict_merge(a, b, leaf_merger=None, in_place=False): """ Recursively deep-merges two dictionaries. @@ -587,8 +604,6 @@ def dict_merge(a, b, leaf_merger=None, in_place=False): dict: ``b`` deep-merged into ``a`` """ - from copy import deepcopy - if a is None: a = {} if b is None: @@ -600,7 +615,7 @@ def dict_merge(a, b, leaf_merger=None, in_place=False): if in_place: result = a else: - result = deepcopy(a) + result = fast_deepcopy(a) for k, v in b.items(): if k in result and isinstance(result[k], dict): @@ -617,7 +632,7 @@ def dict_merge(a, b, leaf_merger=None, in_place=False): pass if merged is None: - merged = deepcopy(v) + merged = fast_deepcopy(v) result[k] = merged return result From 99e7d9b14196a25652060f928cd9d88cf0c99aa4 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 13 Sep 2021 16:54:07 -0400 Subject: [PATCH 010/269] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Gina Häußge --- src/octoprint/util/__init__.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 589db7d39..c62f42130 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -47,10 +47,9 @@ except ImportError: import Queue as queue try: - import cPickle as pickle + import cPickle as pickle # Python 2 has pickle and cPickle, we want cPickle except ImportError: - import pickle - + import pickle # Python 3 # noinspection PyCompatibility from past.builtins import basestring, unicode @@ -550,7 +549,7 @@ def fast_deepcopy(obj): try: # implemented in C and much faster than deepcopy: # https://stackoverflow.com/a/29385667 - return pickle.loads(pickle.dumps(obj, -1)) + return pickle.loads(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)) except AttributeError: # fall back when something unpickable is found return copy.deepcopy(obj) From 1f712c70ac1c2fac187964030007dd996b46cfbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Sep 2021 17:11:09 +0200 Subject: [PATCH 011/269] =?UTF-8?q?=F0=9F=90=9B=20Fix=20wrong=20calculatio?= =?UTF-8?q?n=20of=20deep=5Fdict?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/settings.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 0fb13d796..53ea034c2 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -545,7 +545,9 @@ class HierarchicalChainMap(ChainMap): def deep_dict(self): def deep_dict_inner(root): return { - key: deep_dict_inner(root[key]) if isinstance(value, dict) else value + key: deep_dict_inner(self.__class__._get_next(key, root)) + if isinstance(value, dict) + else value for key, value in root.items() } From 6c81c355b0614015479b73872fe1c336924fbd24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Sep 2021 17:24:59 +0200 Subject: [PATCH 012/269] =?UTF-8?q?=F0=9F=90=9B=20Fix=20fast=5Fdeepcopy=20?= =?UTF-8?q?error=20handling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Python 2 will raise pickle.PicklingError --- src/octoprint/util/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index c62f42130..0a1f4c271 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -50,6 +50,7 @@ try: import cPickle as pickle # Python 2 has pickle and cPickle, we want cPickle except ImportError: import pickle # Python 3 + # noinspection PyCompatibility from past.builtins import basestring, unicode @@ -550,7 +551,7 @@ def fast_deepcopy(obj): # implemented in C and much faster than deepcopy: # https://stackoverflow.com/a/29385667 return pickle.loads(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)) - except AttributeError: + except (AttributeError, pickle.PicklingError): # fall back when something unpickable is found return copy.deepcopy(obj) From 4c1d0338f4f2399de1b0a7d604768a5df3bbf62e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Sep 2021 17:34:06 +0200 Subject: [PATCH 013/269] =?UTF-8?q?=E2=9C=85=20Add=20basic=20tests=20for?= =?UTF-8?q?=20fast=5Fdeepcopy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Should handle regular dict and something that's not pickleable. --- tests/util/test_fast_deepcopy.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/util/test_fast_deepcopy.py diff --git a/tests/util/test_fast_deepcopy.py b/tests/util/test_fast_deepcopy.py new file mode 100644 index 000000000..9234c6ecf --- /dev/null +++ b/tests/util/test_fast_deepcopy.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import unittest + +import octoprint.util + + +class FastDeepcopyTest(unittest.TestCase): + def test_clean(self): + data = {"a": 1, "b": 2, "c": 3} + self.assertEqual(data, octoprint.util.fast_deepcopy(data)) + + def test_function(self): + data = {"a": 1, "b": 2, "c": 3, "f": lambda x: x + 1} + self.assertEqual(data, octoprint.util.fast_deepcopy(data)) From 0f398328ad3da46ee2cc7560125e38198e62ac4d Mon Sep 17 00:00:00 2001 From: John Boiles Date: Thu, 9 Sep 2021 21:57:14 +0100 Subject: [PATCH 014/269] WebRTC support --- AUTHORS.md | 1 + src/octoprint/static/js/app/helpers.js | 68 +++++++++++++++++++ .../static/js/app/viewmodels/control.js | 15 ++++ .../static/js/app/viewmodels/settings.js | 7 ++ src/octoprint/templates/tabs/control.jinja2 | 3 + 5 files changed, 94 insertions(+) diff --git a/AUTHORS.md b/AUTHORS.md index 1016145b9..5df4de2c5 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -148,6 +148,7 @@ date of first contribution): * [ldursw](https://github.com/ldursw) * [Ian Wilt](https://github.com/ianwiltdotcom) * [Ben Sycha](https://github.com/Sycha) + * [John Boiles](https://github.com/johnboiles) 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/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index ef6ac98e8..e52a11c3a 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -1543,6 +1543,10 @@ var copyToClipboard = function (text) { var determineWebcamStreamType = function (streamUrl) { if (streamUrl) { + if (streamUrl.startsWith("webrtc://")) { + return "webrtc"; + } + var lastDotPosition = streamUrl.lastIndexOf("."); var firstQuotationSignPosition = streamUrl.indexOf("?"); if ( @@ -1619,3 +1623,67 @@ var deepMerge = function (target, source) { return target; }; + +var negotiateWebRTC = function (streamUrl) { + pc.addTransceiver("video", {direction: "recvonly"}); + pc.addTransceiver("audio", {direction: "recvonly"}); + return pc + .createOffer() + .then(function (offer) { + return pc.setLocalDescription(offer); + }) + .then(function () { + // Wait for ICE gathering to complete + return new Promise(function (resolve) { + if (pc.iceGatheringState === "complete") { + resolve(); + } else { + function checkState() { + if (pc.iceGatheringState === "complete") { + pc.removeEventListener("icegatheringstatechange", checkState); + resolve(); + } + } + pc.addEventListener("icegatheringstatechange", checkState); + } + }); + }) + .then(function () { + var offer = pc.localDescription; + streamUrl = streamUrl.slice("webrtc://".length); + return fetch("http://" + streamUrl, { + body: JSON.stringify({ + sdp: offer.sdp, + type: offer.type + }), + headers: { + "Content-Type": "application/json" + }, + method: "POST" + }); + }) + .then(function (response) { + return response.json(); + }) + .then(function (answer) { + return pc.setRemoteDescription(answer); + }) + .catch(function (e) { + console.error(e); + }); +}; + +var startWebRTC = function (videoElement, streamUrl) { + var config = { + sdpSemantics: "unified-plan", + iceServers: [{urls: ["stun:stun.l.google.com:19302"]}] + }; + pc = new RTCPeerConnection(config); + pc.addEventListener("track", function (evt) { + if (evt.track.kind == "video") { + videoElement.srcObject = evt.streams[0]; + } + }); + + negotiateWebRTC(streamUrl); +}; diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index 2fefcef18..a8444ded4 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -41,6 +41,7 @@ $(function () { self.webcamLoaded = ko.observable(false); self.webcamMjpgEnabled = ko.observable(false); self.webcamHlsEnabled = ko.observable(false); + self.webcamWebRTCEnabled = ko.observable(false); self.webcamError = ko.observable(false); self.keycontrolActive = ko.observable(false); @@ -524,6 +525,8 @@ $(function () { self._switchToMjpgWebcam(); } else if (streamType == "hls") { self._switchToHlsWebcam(); + } else if (streamType == "webrtc") { + self._switchToWebRTCWebcam(); } else { throw "Unknown stream type " + streamType; } @@ -708,6 +711,7 @@ $(function () { self.webcamHlsEnabled(false); self.webcamMjpgEnabled(true); + self.webcamWebRTCEnabled(false); } }; @@ -729,6 +733,17 @@ $(function () { self.webcamMjpgEnabled(false); self.webcamHlsEnabled(true); + self.webcamWebRTCEnabled(false); + }; + + self._switchToWebRTCWebcam = function () { + var video = document.getElementById("webcam_webrtc"); + + startWebRTC(video, self.settings.webcam_streamUrl()); + + self.webcamMjpgEnabled(false); + self.webcamHlsEnabled(false); + self.webcamWebRTCEnabled(true); }; } diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index ab0dfa877..5c8df6acb 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -453,6 +453,13 @@ $(function () { hls.loadSource(self.webcam_streamUrl()); hls.attachMedia(video_element); } + } else if (streamType == "webrtc") { + webcam_element = $( + '