From 85b3d26992b4087ceec761f7e2db9678beedf16d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Dec 2021 13:38:50 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20Get=20rid=20of=20the=20webassets?= =?UTF-8?q?=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We should rarely if ever regenerate the webassets in production and can wait a few seconds for regeneration in development, if it means we can get rid of a whole monkey patch and an internal use of pickle with non-tamperproof files. So disable the bundle component cache and switch the manifest over to use a json file. Ensure the latter is also removed on server start, just like the other webassets related generated files. Better solution to what was discussed in #4339 and originally to be solved with the now reverted 0f41a42. --- src/octoprint/server/__init__.py | 97 +++++++++++++++++------------- src/octoprint/server/util/flask.py | 76 ----------------------- 2 files changed, 55 insertions(+), 118 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index e8d43911e..95f04a512 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1962,7 +1962,6 @@ class Server(object): global assets global pluginManager - util.flask.fix_webassets_cache() util.flask.fix_webassets_filtertool() base_folder = self._settings.getBaseFolder("generated") @@ -1972,14 +1971,21 @@ class Server(object): import errno import shutil - for entry in ("webassets", ".webassets-cache"): + for entry, recreate in ( + ("webassets", True), + (".webassets-cache", False), # no longer used, but clean up just in case + (".webassets-manifest.json", False), + ): path = os.path.join(base_folder, entry) # delete path if it exists - if os.path.isdir(path): + if os.path.exists(path): try: self._logger.debug("Deleting {path}...".format(**locals())) - shutil.rmtree(path) + if os.path.isdir(path): + shutil.rmtree(path) + else: + os.remove(path) except Exception: self._logger.exception( "Error while trying to delete {path}, " @@ -1987,52 +1993,53 @@ class Server(object): ) continue - # re-create path - self._logger.debug("Creating {path}...".format(**locals())) - error_text = ( - "Error while trying to re-create {path}, that might cause " - "errors with the webassets cache".format(**locals()) - ) - try: - os.makedirs(path) - except OSError as e: - if e.errno == errno.EACCES: - # that might be caused by the user still having the folder open somewhere, let's try again after - # waiting a bit - import time + # re-create path if necessary + if recreate: + self._logger.debug("Creating {path}...".format(**locals())) + error_text = ( + "Error while trying to re-create {path}, that might cause " + "errors with the webassets cache".format(**locals()) + ) + try: + os.makedirs(path) + except OSError as e: + if e.errno == errno.EACCES: + # that might be caused by the user still having the folder open somewhere, let's try again after + # waiting a bit + import time - for n in range(3): - time.sleep(0.5) - self._logger.debug( - "Creating {path}: Retry #{retry} after {time}s".format( - path=path, retry=n + 1, time=(n + 1) * 0.5 - ) - ) - try: - os.makedirs(path) - break - except Exception: - if self._logger.isEnabledFor(logging.DEBUG): - self._logger.exception( - "Ignored error while creating " - "directory {path}".format(**locals()) + for n in range(3): + time.sleep(0.5) + self._logger.debug( + "Creating {path}: Retry #{retry} after {time}s".format( + path=path, retry=n + 1, time=(n + 1) * 0.5 ) - pass + ) + try: + os.makedirs(path) + break + except Exception: + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.exception( + "Ignored error while creating " + "directory {path}".format(**locals()) + ) + pass + else: + # this will only get executed if we never did + # successfully execute makedirs above + self._logger.exception(error_text) + continue else: - # this will only get executed if we never did - # successfully execute makedirs above + # not an access error, so something we don't understand + # went wrong -> log an error and stop self._logger.exception(error_text) continue - else: - # not an access error, so something we don't understand + except Exception: + # not an OSError, so something we don't understand # went wrong -> log an error and stop self._logger.exception(error_text) continue - except Exception: - # not an OSError, so something we don't understand - # went wrong -> log an error and stop - self._logger.exception(error_text) - continue self._logger.info("Reset webasset folder {path}...".format(**locals())) @@ -2050,6 +2057,12 @@ class Server(object): assets = CustomDirectoryEnvironment(app) assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"]) + # we should rarely if ever regenerate the webassets in production and can wait a + # few seconds for regeneration in development, if it means we can get rid of + # a whole monkey patch and in internal use of pickle with non-tamperproof files + assets.cache = False + assets.manifest = "json:.webassets-manifest.json" + UpdaterType = type(util.flask.SettingsCheckUpdater)( util.flask.SettingsCheckUpdater.__name__, (util.flask.SettingsCheckUpdater,), diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index e35062f9b..3a09e34f9 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -8,7 +8,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 functools -import io import logging import os import threading @@ -172,81 +171,6 @@ def enable_additional_translations(default_locale="en", additional_folders=None) flask_babel.get_translations = fixed_get_translations -def fix_webassets_cache(): - from webassets import cache - - error_logger = logging.getLogger(__name__ + ".fix_webassets_cache") - - def fixed_set(self, key, data): - import os - import pickle - import shutil - import tempfile - - if not os.path.exists(self.directory): - error_logger.warning( - "Cache directory {} doesn't exist, not going " - "to attempt to write cache file".format(self.directory) - ) - - md5 = "%s" % cache.make_md5(self.V, key) - filename = os.path.join(self.directory, md5) - fd, temp_filename = tempfile.mkstemp(prefix="." + md5, dir=self.directory) - try: - with os.fdopen(fd, "wb") as f: - pickle.dump(data, f) - f.flush() - shutil.move(temp_filename, filename) - except Exception: - os.remove(temp_filename) - raise - - def fixed_get(self, key): - import errno - import os - import warnings - - from webassets.cache import make_md5 - - if not os.path.exists(self.directory): - error_logger.warning( - "Cache directory {} doesn't exist, not going " - "to attempt to read cache file".format(self.directory) - ) - return None - - try: - hash = make_md5(self.V, key) - except IOError as e: - if e.errno != errno.ENOENT: - raise - return None - - filename = os.path.join(self.directory, "%s" % hash) - try: - f = io.open(filename, "rb") - except IOError as e: - if e.errno != errno.ENOENT: - error_logger.exception( - "Got an exception while trying to open webasset file {}".format( - filename - ) - ) - return None - try: - result = f.read() - finally: - f.close() - - unpickled = webassets.cache.safe_unpickle(result) - if unpickled is None: - warnings.warn("Ignoring corrupted cache file %s" % filename) - return unpickled - - cache.FilesystemCache.set = fixed_set - cache.FilesystemCache.get = fixed_get - - def fix_webassets_filtertool(): from webassets.merge import FilterTool, MemoryHunk, log