From 0e302d440ff390311350c93d437f3d83803068b4 Mon Sep 17 00:00:00 2001 From: AndyQ Date: Mon, 18 Feb 2019 11:28:41 +0100 Subject: [PATCH 01/11] Added ability to preview the current layer to be drawn If selected, the current layer is drawn at 30% opacity and then the progress is drawn over the top at 100% Added additional checkbox on GCodeView page to include current layer as preview --- AUTHORS.md | 1 + src/octoprint/static/gcodeviewer/js/renderer.js | 7 ++++++- src/octoprint/static/js/app/viewmodels/gcode.js | 6 ++++++ src/octoprint/templates/tabs/gcodeviewer.jinja2 | 3 +++ 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/AUTHORS.md b/AUTHORS.md index aa13f4baa..3428b6b41 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -97,6 +97,7 @@ date of first contribution): * [Henning Groß](https://github.com/hgross) * [Jubaleth](https://github.com/jubaleth) * [Daniel Joyce](https://github.com/DanielJoyce) + * [Andy Qua](https://github.com/AndyQ) 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/gcodeviewer/js/renderer.js b/src/octoprint/static/gcodeviewer/js/renderer.js index f63412b42..87455cffb 100644 --- a/src/octoprint/static/gcodeviewer/js/renderer.js +++ b/src/octoprint/static/gcodeviewer/js/renderer.js @@ -46,6 +46,7 @@ GCODE.renderer = (function(){ modelCenter: {x: 0, y: 0}, differentiateColors: true, showNextLayer: false, + showCurrentLayer: false, showPreviousLayer: false, showBoundingBox: false, showFullSize: false, @@ -98,6 +99,9 @@ GCODE.renderer = (function(){ if (renderOptions['showNextLayer'] && layerNumStore < model.length - 1) { drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true); } + if (renderOptions['showCurrentLayer'] && layerNumStore < model.length) { + drawLayer(layerNumStore, 0, GCODE.renderer.getLayerNumSegments(layerNumStore), true); + } if (renderOptions['showPreviousLayer'] && layerNumStore > 0) { drawLayer(layerNumStore - 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore - 1), true); } @@ -567,7 +571,8 @@ GCODE.renderer = (function(){ var sizeRetractSpot = renderOptions["sizeRetractSpot"] * lineWidthFactor * 2; // alpha value (100% if current layer is being rendered, 30% otherwise) - var alpha = (renderOptions['showNextLayer'] || renderOptions['showPreviousLayer']) && isNotCurrentLayer ? 0.3 : 1.0; + // Note - If showing currently layer as preview - also render it at 30% and draw the progress over the top at 100% + var alpha = (renderOptions['showNextLayer'] || renderOptions['showCurrentLayer'] || renderOptions['showPreviousLayer']) && isNotCurrentLayer ? 0.3 : 1.0; var colorLine = {}; var colorMove = {}; diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index 5f9581f33..a553b08f7 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -52,6 +52,7 @@ $(function() { self.renderer_extrusionWidthEnabled = ko.observable(false); self.renderer_extrusionWidth = ko.observable(2); self.renderer_showNext = ko.observable(false); + self.renderer_showCurrent = ko.observable(false); self.renderer_showPrevious = ko.observable(false); self.renderer_syncProgress = ko.observable(true); @@ -79,6 +80,7 @@ $(function() { showFullSize: self.renderer_showFullSize(), extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1, showNextLayer: self.renderer_showNext(), + showCurrentLayer: self.renderer_showCurrent(), showPreviousLayer: self.renderer_showPrevious(), zoomInOnModel: self.renderer_zoomOnModel(), onInternalOptionChange: self._onInternalRendererOptionChange @@ -124,6 +126,7 @@ $(function() { self.renderer_extrusionWidthEnabled.subscribe(self.rendererOptionUpdated); self.renderer_extrusionWidth.subscribe(self.rendererOptionUpdated); self.renderer_showNext.subscribe(self.rendererOptionUpdated); + self.renderer_showCurrent.subscribe(self.rendererOptionUpdated); self.renderer_showPrevious.subscribe(self.rendererOptionUpdated); self.reader_sortLayers.subscribe(self.readerOptionUpdated); @@ -341,6 +344,7 @@ $(function() { self.renderer_extrusionWidthEnabled(false); self.renderer_extrusionWidth(2); self.renderer_showNext(false); + self.renderer_showCurrent(false); self.renderer_showPrevious(false); self.renderer_syncProgress(true); @@ -711,6 +715,7 @@ $(function() { current["showRetracts"] = self.renderer_showRetracts(); current["showPrinthead"] = self.renderer_showPrinthead(); current["showPrevious"] = self.renderer_showPrevious(); + current["showCurrent"] = self.renderer_showCurrent(); current["showNext"] = self.renderer_showNext(); current["showFullsize"] = self.renderer_showFullSize(); current["showBoundingBox"] = self.renderer_showBoundingBox(); @@ -743,6 +748,7 @@ $(function() { if (current["showRetracts"] !== undefined) self.renderer_showRetracts(current["showRetracts"]) ; if (current["showPrinthead"] !== undefined) self.renderer_showPrinthead(current["showPrinthead"]); if (current["showPrevious"] !== undefined) self.renderer_showPrevious(current["showPrevious"]) ; + if (current["showCurrent"] !== undefined) self.renderer_showCurrent(current["showCurrent"]) ; if (current["showNext"] !== undefined) self.renderer_showNext(current["showNext"]) ; if (current["showFullsize"] !== undefined) self.renderer_showFullSize(current["showFullsize"]) ; if (current["showBoundingBox"] !== undefined) self.renderer_showBoundingBox(current["showBoundingBox"]) ; diff --git a/src/octoprint/templates/tabs/gcodeviewer.jinja2 b/src/octoprint/templates/tabs/gcodeviewer.jinja2 index b9c098e07..304ec69ad 100644 --- a/src/octoprint/templates/tabs/gcodeviewer.jinja2 +++ b/src/octoprint/templates/tabs/gcodeviewer.jinja2 @@ -64,6 +64,9 @@ + From c652bed87138c6ebb874178dba6c7f87a5967f59 Mon Sep 17 00:00:00 2001 From: fieldOfView Date: Thu, 28 Feb 2019 11:31:52 +0100 Subject: [PATCH 02/11] Add missing documentation about state in `jobs` endpoint --- docs/api/datamodel.rst | 19 +++++++++++++++++++ docs/api/job.rst | 8 ++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index a55554e9e..abf0ba2b9 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -219,6 +219,25 @@ Progress information - Integer - Estimate of time left to print, in seconds +.. _sec-api-datamodel-jobs-state: + +State information +----------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - body + - 1 + - String + - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", + "Cancelling", "Error" or "Offline". + .. _sec-api-datamodel-files: File related diff --git a/docs/api/job.rst b/docs/api/job.rst index 338a10ea7..bc9d67a1e 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -212,7 +212,8 @@ Retrieve information about the current job "filepos": 337942, "printTime": 276, "printTimeLeft": 912 - } + }, + "state": "Printing" } :statuscode 200: No error @@ -243,4 +244,7 @@ Job information response - 1 - :ref:`sec-api-datamodel-jobs-progress` - Information regarding the progress of the current print job - + * - ``state`` + - 1 + - :ref:`sec-api-datamodel-jobs-state` + - Information regarding the state of the current print job From a15e2de251a2502bb285cc4f0bb0dd2cb664222b Mon Sep 17 00:00:00 2001 From: fieldOfView Date: Thu, 28 Feb 2019 12:17:35 +0100 Subject: [PATCH 03/11] Fix datamodel structure --- docs/api/datamodel.rst | 33 ++++++++++++++------------------- docs/api/job.rst | 2 +- 2 files changed, 15 insertions(+), 20 deletions(-) diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index abf0ba2b9..62f530066 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -151,6 +151,20 @@ Temperature offset Job related =========== +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``state`` + - 1 + - String + - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", + "Cancelling", "Error" or "Offline". + .. _sec-api-datamodel-jobs-job: Job information @@ -219,25 +233,6 @@ Progress information - Integer - Estimate of time left to print, in seconds -.. _sec-api-datamodel-jobs-state: - -State information ------------------ - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - body - - 1 - - String - - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", - "Cancelling", "Error" or "Offline". - .. _sec-api-datamodel-files: File related diff --git a/docs/api/job.rst b/docs/api/job.rst index bc9d67a1e..a38dda0cd 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -246,5 +246,5 @@ Job information response - Information regarding the progress of the current print job * - ``state`` - 1 - - :ref:`sec-api-datamodel-jobs-state` + - :ref:`sec-api-datamodel-jobs` - Information regarding the state of the current print job From 4dbb24ecd759d703b7af2bb61f3864235ecb5e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 28 Feb 2019 12:26:25 +0100 Subject: [PATCH 04/11] =?UTF-8?q?=F0=9F=93=9D=20`state`=20is=20not=20a=20s?= =?UTF-8?q?ub=20data=20model=20but=20a=20string?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/api/datamodel.rst | 14 -------------- docs/api/job.rst | 5 +++-- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index 62f530066..a55554e9e 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -151,20 +151,6 @@ Temperature offset Job related =========== -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``state`` - - 1 - - String - - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", - "Cancelling", "Error" or "Offline". - .. _sec-api-datamodel-jobs-job: Job information diff --git a/docs/api/job.rst b/docs/api/job.rst index a38dda0cd..0c43e2b3b 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -246,5 +246,6 @@ Job information response - Information regarding the progress of the current print job * - ``state`` - 1 - - :ref:`sec-api-datamodel-jobs` - - Information regarding the state of the current print job + - String + - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", + "Cancelling", "Error" or "Offline". From 8866ed716d3d0fd6e11424cb1d09ee5879a10244 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 1 Mar 2019 11:20:45 +0100 Subject: [PATCH 05/11] =?UTF-8?q?=E2=98=94=20Better=20resilience=20against?= =?UTF-8?q?=20invalid=20SD=20status=20reports?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/util/comm.py | 49 ++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index bbb604a71..59a2467dd 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -79,7 +79,7 @@ regex_minMaxError = re.compile("Error:[0-9]\n") regex_marlinKillError = re.compile("Heating failed|Thermal Runaway|MAXTEMP triggered|MINTEMP triggered|Invalid extruder number|Watchdog barked|KILL caused") """Regex matching first line of kill causing errors from Marlin.""" -regex_sdPrintingByte = re.compile("(?P[0-9]*)/(?P[0-9]*)") +regex_sdPrintingByte = re.compile("(?P[0-9]+)/(?P[0-9]+)") """Regex matching SD printing status reports. Groups will be as follows: @@ -1935,31 +1935,34 @@ class MachineCom(object): # answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d" match = regex_sdPrintingByte.search(line) if match: - current = int(match.group("current")) - total = int(match.group("total")) - - if current == total == 0 \ - and self.isSdPrinting() \ - and not self.isStarting() \ - and not self.isStarting() \ - and not self.isFinishing(): - # apparently not SD printing - some Marlin versions report it like that for some reason - self._consecutive_not_sd_printing += 1 - if self._consecutive_not_sd_printing > self._consecutive_not_sd_printing_maximum: - self.cancelPrint(external_sd=True) - + try: + current = int(match.group("current")) + total = int(match.group("total")) + except: + self._logger.exception("Error while parsing SD status report") else: - self._consecutive_not_sd_printing = 0 - if self.isSdFileSelected(): - if not self.isSdPrinting() and current != total and current > 0: - self.startPrint(external_sd=True) + if current == total == 0 \ + and self.isSdPrinting() \ + and not self.isStarting() \ + and not self.isStarting() \ + and not self.isFinishing(): + # apparently not SD printing - some Marlin versions report it like that for some reason + self._consecutive_not_sd_printing += 1 + if self._consecutive_not_sd_printing > self._consecutive_not_sd_printing_maximum: + self.cancelPrint(external_sd=True) - self._currentFile.pos = current - if self._currentFile.size == 0: - self._currentFile.size = total + else: + self._consecutive_not_sd_printing = 0 + if self.isSdFileSelected(): + if not self.isSdPrinting() and current != total and current > 0: + self.startPrint(external_sd=True) - if not self._currentFile.done: - self._callback.on_comm_progress() + self._currentFile.pos = current + if self._currentFile.size == 0: + self._currentFile.size = total + + if not self._currentFile.done: + self._callback.on_comm_progress() elif 'Not SD printing' in line \ and self.isSdPrinting() \ and not self.isStarting() \ From 7d0bd6a3395297386e8dc27dace97b180bf63fb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 4 Mar 2019 17:29:00 +0100 Subject: [PATCH 06/11] =?UTF-8?q?=E2=98=94=20Remove=20stale=20entries=20fr?= =?UTF-8?q?om=20metadata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If a file no longer exists on disk for whatever reason it also doesn't need to be kept in metadata.json. See also #3057 Cherry-picked from 15d3b2ca --- src/octoprint/filemanager/storage.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 9cafb0811..802728fc6 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1530,7 +1530,15 @@ class LocalFileStorage(StorageInterface): self._logger.exception("Error while reading .metadata.json from {path}".format(**locals())) else: if isinstance(metadata, dict): - self._metadata_cache[path] = deepcopy(metadata) + old_size = len(metadata) + metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) } + new_size = len(metadata) + if new_size != old_size: + self._logger.info("Deleted {} stale entries from metadata for path {}".format(old_size - new_size, + path)) + self._save_metadata(path, metadata) + else: + self._metadata_cache[path] = deepcopy(metadata) return metadata return dict() From d071684d416de5851e2464d50b4de76a04300014 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 4 Mar 2019 17:29:00 +0100 Subject: [PATCH 07/11] =?UTF-8?q?=E2=99=BB=20Remove=20old=20metadata.yaml?= =?UTF-8?q?=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Were deprecated and supposed to be removed with 1.3.10, we'll do it with 1.3.11. --- src/octoprint/filemanager/storage.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 802728fc6..fcec07f58 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1582,7 +1582,10 @@ class LocalFileStorage(StorageInterface): if os.path.exists(metadata_path_json): # already migrated - # TODO 1.3.10 Remove ".metadata.yaml" files + try: + os.remove(metadata_path_yaml) + except: + self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) return with open(metadata_path_yaml) as f: @@ -1599,7 +1602,10 @@ class LocalFileStorage(StorageInterface): with atomic_write(metadata_path_json) as f: json.dump(metadata, f, indent=4, separators=(",", ": ")) - # TODO 1.3.10 Remove ".metadata.yaml" files + try: + os.remove(metadata_path_yaml) + except: + self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) @contextmanager def _get_metadata_lock(self, path): From 92618362e1d93a89b096ca07531ba4f96255fd2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 4 Mar 2019 17:29:00 +0100 Subject: [PATCH 08/11] =?UTF-8?q?=F0=9F=92=9A=20Forgot=20to=20adjust=20the?= =?UTF-8?q?=20tests=20for=20d071684?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/filemanager/test_localstorage.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index 491608f1a..c92b764a2 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -660,7 +660,7 @@ class LocalStorageTest(unittest.TestCase): # verify self.assertTrue(os.path.exists(json_path)) - self.assertTrue(os.path.exists(yaml_path)) # TODO 1.3.10 change to assertFalse + self.assertFalse(os.path.exists(yaml_path)) # TODO 1.3.10 change to assertFalse import json with open(json_path) as f: From e01f391b30fe7b1a0189947d0f07ca1850f95d3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 4 Mar 2019 17:29:00 +0100 Subject: [PATCH 09/11] =?UTF-8?q?=E2=9A=A1=20More=20intelligent=20use=20of?= =?UTF-8?q?=20copy=20&=20deepcopy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Improves performance of file manipulation, especially in cases with a lot of files in the folder, without the added complexity of fully decoupling metadata file serialization from general processing. Better fix for #3057 --- src/octoprint/filemanager/storage.py | 139 ++++++++++++++++++--------- 1 file changed, 95 insertions(+), 44 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index fcec07f58..1b2b66b8f 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -8,9 +8,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os -import pylru import shutil import re +import pylru +import copy try: from os import scandir, walk @@ -19,7 +20,6 @@ except ImportError: from octoprint.util import atomic_write from contextlib import contextmanager -from copy import deepcopy from past.builtins import basestring @@ -28,7 +28,7 @@ from slugify import Slugify import octoprint.filemanager -from octoprint.util import is_hidden_path, to_unicode +from octoprint.util import is_hidden_path, to_unicode, timing class StorageInterface(object): """ @@ -485,6 +485,8 @@ class LocalFileStorage(StorageInterface): import threading self._metadata_lock_mutex = threading.RLock() self._metadata_locks = dict() + self._persisted_metadata_lock_mutex = threading.RLock() + self._persisted_metadata_locks = dict() self._metadata_cache = pylru.lrucache(10) @@ -883,6 +885,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata: return + metadata = self._copied_metadata(metadata, name) + if not key in metadata[name] or overwrite: metadata[name][key] = data metadata_dirty = True @@ -907,6 +911,7 @@ class LocalFileStorage(StorageInterface): if not key in metadata[name]: return + metadata = self._copied_metadata(metadata, name) del metadata[name][key] self._save_metadata(path, metadata) @@ -1050,10 +1055,7 @@ class LocalFileStorage(StorageInterface): ##~~ internals def _add_history(self, name, path, data): - metadata = self._get_metadata(path) - - if not name in metadata: - metadata[name] = dict() + metadata = self._copied_metadata(self._get_metadata(path), name) if not "hash" in metadata[name]: metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) @@ -1071,6 +1073,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata or not "history" in metadata[name]: return + metadata = self._copied_metadata(metadata, name) + try: metadata[name]["history"][index].update(data) self._calculate_stats_from_history(name, path, metadata=metadata, save=False) @@ -1084,6 +1088,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata or not "history" in metadata[name]: return + metadata = self._copied_metadata(metadata, name) + try: del metadata[name]["history"][index] self._calculate_stats_from_history(name, path, metadata=metadata, save=False) @@ -1093,9 +1099,9 @@ class LocalFileStorage(StorageInterface): def _calculate_stats_from_history(self, name, path, metadata=None, save=True): if metadata is None: - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) - if not name in metadata or not "history" in metadata[name]: + if not "history" in metadata[name]: return # collect data from history @@ -1164,12 +1170,9 @@ class LocalFileStorage(StorageInterface): if file_type: file_type = file_type[0] - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) metadata_dirty = False - if not name in metadata: - metadata[name] = dict() - if not "hash" in metadata[name]: metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) @@ -1241,13 +1244,10 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) def _remove_links(self, name, path, links): - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) metadata_dirty = False - if not name in metadata or not "hash" in metadata[name]: - hash = self._create_hash(os.path.join(path, name)) - else: - hash = metadata[name]["hash"] + hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name))) for rel, data in links: if (rel == "model" or rel == "machinecode") and "name" in data: @@ -1255,6 +1255,7 @@ class LocalFileStorage(StorageInterface): ref_rel = "model" if rel == "machinecode" else "machinecode" for link in metadata[data["name"]]["links"]: if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash: + metadata[data["name"]] = copy.deepcopy(metadata[data["name"]]) metadata[data["name"]]["links"].remove(link) metadata_dirty = True @@ -1330,10 +1331,14 @@ class LocalFileStorage(StorageInterface): if entry_name in metadata and isinstance(metadata[entry_name], dict): entry_metadata = metadata[entry_name] if not "display" in entry_metadata and entry_display != entry_name: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) metadata[entry_name]["display"] = entry_display entry_metadata["display"] = entry_display metadata_dirty = True else: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) entry_metadata = self._add_basic_metadata(path, entry_name, display_name=entry_display, save=False, @@ -1363,10 +1368,14 @@ class LocalFileStorage(StorageInterface): if entry_name in metadata and isinstance(metadata[entry_name], dict): entry_metadata = metadata[entry_name] if not "display" in entry_metadata and entry_display != entry_name: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) metadata[entry_name]["display"] = entry_display entry_metadata["display"] = entry_display metadata_dirty = True elif entry_name != entry_display: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) entry_metadata = self._add_basic_metadata(path, entry_name, display_name=entry_display, save=False, @@ -1450,6 +1459,8 @@ class LocalFileStorage(StorageInterface): entry_data["display"] = display_name entry_data.update(additional_metadata) + + metadata = copy.copy(metadata) metadata[entry] = entry_data if save: @@ -1481,6 +1492,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata: return + metadata = copy.copy(metadata) + if "hash" in metadata[name]: hash = metadata[name]["hash"] for m in metadata.values(): @@ -1494,7 +1507,7 @@ class LocalFileStorage(StorageInterface): def _update_metadata_entry(self, path, name, data): with self._get_metadata_lock(path): - metadata = self._get_metadata(path) + metadata = copy.copy(self._get_metadata(path)) metadata[name] = data self._save_metadata(path, metadata) @@ -1513,49 +1526,62 @@ class LocalFileStorage(StorageInterface): with self._get_metadata_lock(destination_path): self._update_metadata_entry(destination_path, destination_name, source_data) - def _get_metadata(self, path): - with self._get_metadata_lock(path): - if path in self._metadata_cache: - return deepcopy(self._metadata_cache[path]) + def _get_metadata(self, path, force=False): + import json - self._migrate_metadata(path) + if not force: + metadata = self._metadata_cache.get(path) + if metadata: + return metadata - metadata_path = os.path.join(path, ".metadata.json") + self._migrate_metadata(path) + + metadata_path = os.path.join(path, ".metadata.json") + + metadata = None + with self._get_persisted_metadata_lock(path): if os.path.exists(metadata_path): with open(metadata_path) as f: try: - import json metadata = json.load(f) except: self._logger.exception("Error while reading .metadata.json from {path}".format(**locals())) - else: - if isinstance(metadata, dict): - old_size = len(metadata) - metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) } - new_size = len(metadata) - if new_size != old_size: - self._logger.info("Deleted {} stale entries from metadata for path {}".format(old_size - new_size, - path)) - self._save_metadata(path, metadata) - else: - self._metadata_cache[path] = deepcopy(metadata) - return metadata + + if isinstance(metadata, dict): + old_size = len(metadata) + metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) } + new_size = len(metadata) + if new_size != old_size: + self._logger.info("Deleted {} stale entries from metadata for path {}".format(old_size - new_size, + path)) + self._save_metadata(path, metadata) + else: + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + return metadata + else: return dict() def _save_metadata(self, path, metadata): + import json + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + + with self._get_persisted_metadata_lock(path): metadata_path = os.path.join(path, ".metadata.json") try: - import json with atomic_write(metadata_path) as f: json.dump(metadata, f, indent=4, separators=(",", ": ")) except: self._logger.exception("Error while writing .metadata.json to {path}".format(**locals())) - else: - self._metadata_cache[path] = deepcopy(metadata) def _delete_metadata(self, path): with self._get_metadata_lock(path): + if path in self._metadata_cache: + del self._metadata_cache[path] + + with self._get_persisted_metadata_lock(path): metadata_files = (".metadata.json", ".metadata.yaml") for metadata_file in metadata_files: metadata_path = os.path.join(path, metadata_file) @@ -1564,15 +1590,19 @@ class LocalFileStorage(StorageInterface): os.remove(metadata_path) except: self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals())) - if path in self._metadata_cache: - del self._metadata_cache[path] + + @staticmethod + def _copied_metadata(metadata, name): + metadata = copy.copy(metadata) + metadata[name] = copy.deepcopy(metadata.get(name, dict())) + return metadata def _migrate_metadata(self, path): # we switched to json in 1.3.9 - if we still have yaml here, migrate it now import yaml import json - with self._get_metadata_lock(path): + 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") @@ -1627,3 +1657,24 @@ class LocalFileStorage(StorageInterface): del self._metadata_locks[path] else: self._metadata_locks[path] = (counter, lock) + + @contextmanager + def _get_persisted_metadata_lock(self, path): + with self._persisted_metadata_lock_mutex: + if path not in self._persisted_metadata_locks: + import threading + self._persisted_metadata_locks[path] = (0, threading.RLock()) + + counter, lock = self._persisted_metadata_locks[path] + counter += 1 + self._persisted_metadata_locks[path] = (counter, lock) + + yield lock + + with self._persisted_metadata_lock_mutex: + counter = self._persisted_metadata_locks[path][0] + counter -= 1 + if counter <= 0: + del self._persisted_metadata_locks[path] + else: + self._persisted_metadata_locks[path] = (counter, lock) From 8668c6200ac059f8747bbb8b728e348287fcf5bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 4 Mar 2019 17:29:00 +0100 Subject: [PATCH 10/11] =?UTF-8?q?=E2=9C=A8=20Decorator=20for=20timing=20me?= =?UTF-8?q?thods?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Probably mostly helpful during development... --- src/octoprint/util/__init__.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 89aca7342..a3298d22b 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1614,3 +1614,16 @@ class CaseInsensitiveSet(collections.Set): # originally from https://stackoverflow.com/a/5967539 def natural_key(text): return [ int(c) if c.isdigit() else c for c in re.split("(\d+)", text) ] + + +def timing(f): + @wraps(f) + def decorator(*args, **kwargs): + start = monotonic_time() + try: + return f(*args, **kwargs) + finally: + end = monotonic_time() + logging.getLogger("octoprint.util.timing").debug("func:{} took {:0.2f}s".format(f.__name__, + end - start)) + return decorator From aab629d80e4a71225cd91488cdb7e833b1700979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 4 Mar 2019 17:29:00 +0100 Subject: [PATCH 11/11] =?UTF-8?q?=F0=9F=8E=A8=20except:=20=3D>=20except=20?= =?UTF-8?q?Exception:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/filemanager/storage.py | 4 ++-- src/octoprint/plugins/printer_safety_check/__init__.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 74c352b9e..f373d5cce 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1614,7 +1614,7 @@ class LocalFileStorage(StorageInterface): # already migrated try: os.remove(metadata_path_yaml) - except: + except Exception: self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) return @@ -1634,7 +1634,7 @@ class LocalFileStorage(StorageInterface): try: os.remove(metadata_path_yaml) - except: + except Exception: self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) @contextmanager diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 36ee30df7..7f8ce8db9 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -127,7 +127,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, # execute method try: method(*args, **kwargs) - except: + except Exception: self._logger.exception("There was an error running method {} on check {!r}".format(check_type, check)) continue