From 699ed1da4df9b6293f3e0baebd6f73114b238c92 Mon Sep 17 00:00:00 2001 From: Bevaz Date: Wed, 17 Dec 2014 22:08:47 +0300 Subject: [PATCH 01/19] Enframed output filename with quotes. --- src/octoprint/timelapse.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index ba5daf223..d737ed844 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -299,7 +299,7 @@ class Timelapse(object): # finalize command with output file self._logger.debug("Rendering movie to %s" % output) - command.append(output) + command.append("\"" + output + "\"") eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)}) command_str = " ".join(command) From 0737ee65bd6aadc3b609860aa1a8b0e5d7c36051 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sat, 20 Dec 2014 00:31:46 +0100 Subject: [PATCH 02/19] Support action: commands sent from printer, for now only pause, resume and disconnect are supported, plus a new hook "octoprint.comm.protocol.action" to add handlers of custom actions via plugins. Added "!!DEBUG:" command to virtual printer to be able to trigger such commands to be sent by it. --- src/octoprint/printer/__init__.py | 3 +++ src/octoprint/util/comm.py | 25 +++++++++++++++++++++++++ src/octoprint/util/virtual.py | 10 ++++++++++ 3 files changed, 38 insertions(+) diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index 05b7c6443..73839462e 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -658,6 +658,9 @@ class Printer(): def mcReceivedRegisteredMessage(self, command, output): self._sendFeedbackCommandOutput(command, output) + def mcForceDisconnect(self): + self.disconnect() + #~~ sd file handling def getSdFiles(self): diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 149a5db33..1ba81bd87 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -161,6 +161,7 @@ class MachineCom(object): # hooks self._pluginManager = octoprint.plugin.plugin_manager() self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode") + self._printer_action_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.action") # SD status data self._sdAvailable = False @@ -670,6 +671,27 @@ class MachineCom(object): if line.strip() is not "": self._timeout = getNewTimeout("communication") + ##~~ debugging output handling + if line.startswith("//"): + debugging_output = line[2:].strip() + if debugging_output.startswith("action:"): + action_command = debugging_output[len("action:"):].strip() + + if action_command == "pause": + self._log("Pausing on request of the printer...") + self.setPause(True) + elif action_command == "resume": + self._log("Resuming on request of the printer...") + self.setPause(False) + elif action_command == "disconnect": + self._log("Disconnecting on request of the printer...") + self._callback.mcForceDisconnect() + else: + for hook in self._printer_action_hooks: + self._printer_action_hooks[hook](self, line, action_command) + else: + continue + ##~~ Error handling line = self._handleErrors(line) @@ -1311,6 +1333,9 @@ class MachineComPrintCallback(object): def mcReceivedRegisteredMessage(self, command, message): pass + def mcForceDisconnect(self): + pass + ### Printing file information classes ################################################################################## class PrintingFileInformation(object): diff --git a/src/octoprint/util/virtual.py b/src/octoprint/util/virtual.py index 9ddb43851..62e63b7a0 100644 --- a/src/octoprint/util/virtual.py +++ b/src/octoprint/util/virtual.py @@ -227,6 +227,8 @@ class VirtualPrinter(): self._relative = True elif "G92" in data: self._setPosition(data) + elif data.startswith("!!DEBUG:"): + self._debugTrigger(data[len("!!DEBUG:"):].strip()) elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \ or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \ @@ -237,6 +239,14 @@ class VirtualPrinter(): if len(data.strip()) > 0: self._sendOk() + def _debugTrigger(self, data): + if data == "action_pause": + self.outgoing.put("// action:pause") + elif data == "action_resume": + self.outgoing.put("// action:resume") + elif data == "action_disconnect": + self.outgoing.put("// action:disconnect") + def _listSd(self): self.outgoing.put("Begin file list") if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]): From 256c2dfdbe49928e5f83f8bd1fdfa75a38c8a59c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sat, 20 Dec 2014 01:06:40 +0100 Subject: [PATCH 03/19] More error resilient handling of .metadata.yaml writes in local storage Writes updated metadata to a backup file first and then copies it atomically (at least under anything that is not windows where the operation is a bit more complicated and hence not atomic) --- src/octoprint/filemanager/storage.py | 19 +++++++++++++------ src/octoprint/util/__init__.py | 10 ++++++---- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 54d13a434..b2cf61425 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -9,9 +9,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os import pylru +import tempfile import octoprint.filemanager +from octoprint.util import safeRename + class StorageInterface(object): @@ -867,12 +870,16 @@ class LocalFileStorage(StorageInterface): def _save_metadata(self, path, metadata): metadata_path = os.path.join(path, ".metadata.yaml") + fh, metadata_temporary_path = tempfile.mkstemp() + os.close(fh) + with self._metadata_lock: - with open(metadata_path, "w") as f: - try: + try: + with open(metadata_temporary_path, "w") as f: import yaml yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True) - except: - self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals())) - else: - self._metadata_cache[path] = metadata + safeRename(metadata_temporary_path, metadata_path, throw_error=True) + except: + self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals())) + else: + self._metadata_cache[path] = metadata diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 8f6b1537a..2c7b72bd6 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -147,7 +147,7 @@ def findCollisionfreeName(input, extension, existingFilenames): raise ValueError("Can't create a collision free filename") -def safeRename(old, new): +def safeRename(old, new, throw_error=False): """ Safely renames a file. @@ -172,12 +172,14 @@ def safeRename(old, new): os.rename(new, backup) os.rename(old, new) os.remove(backup) - except OSError: + except OSError as e: # if anything went wrong, try to rename the backup file to its original name logger.error("Could not perform safe rename, trying to revert") if os.path.exists(backup): - os.remove(new) - os.rename(backup, new) + silentRemove(new) + os.rename(backup, new) + if throw_error: + raise e else: # on anything else than windows it's ooooh so much easier... os.rename(old, new) From 46b0367335c957cfe0d99ed5fb4d4789e64b8cf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 21 Dec 2014 15:15:59 +0100 Subject: [PATCH 04/19] Log a message to octoprint.log if Cura is not fully configured and hence not available for slicing yet. As suggested in #689 --- src/octoprint/plugins/cura/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 4e9653e3a..da0705066 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -188,7 +188,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, def is_slicer_configured(self): cura_engine = s.get(["cura_engine"]) - return cura_engine is not None and os.path.exists(cura_engine) + if cura_engine is not None and os.path.exists(cura_engine): + return True + else: + self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine) def get_slicer_properties(self): return dict( From 977cf3c3831108679905f19aa66172a43daec32a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 21 Dec 2014 15:32:07 +0100 Subject: [PATCH 05/19] Added handler for uncaught exceptions to make sure those get logged --- src/octoprint/server/__init__.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 7f3c13deb..96db47417 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -216,6 +216,8 @@ class Server(): from tornado.ioloop import IOLoop from tornado.web import Application + import sys + debug = self._debug # first initialize the settings singleton and make sure it uses given configfile and basedir if available @@ -224,6 +226,9 @@ class Server(): # then initialize logging self._initLogging(self._debug, self._logConf) logger = logging.getLogger(__name__) + def exception_logger(exc_type, exc_value, exc_tb): + logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + sys.excepthook = exception_logger logger.info("Starting OctoPrint %s" % DISPLAY_VERSION) # then initialize the plugin manager From 52ad02a08a32c197a413b886d25a6f8a08595fd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 21 Dec 2014 15:32:30 +0100 Subject: [PATCH 06/19] Updated the changelog with a lot of stuff that gone done the past weeks --- CHANGELOG.md | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96e0485c9..06d6b1d18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ * OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its core functionality. * New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications +* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A + connection to a printer will always have a printer profile associated. +* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are + - `action:pause`: Pauses the current job in OctoPrint + - `action:resume`: Resumes the current job in OctoPrint + - `action:disconnect`: Disconnects OctoPrint from the printer ### Improvements @@ -33,13 +39,17 @@ ([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590)) * Slicing has been greatly improved: * It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing - job (defining overrides is not yet part of the UI but it's on the roadmap). + job (defining overrides is not yet part of the UI but it's on the roadmap). + * A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list + as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the + sliced GCODE for printing or starting to print it directly) * Slicers themselves are integrated into the system via ``SlicingPlugins``. * The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the [CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See [the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to accommodate the new integration. * The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)). + * The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI). * File management now supports STL files as first class citizens (including UI adjustments to allow management of uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI) * Also interpret lines starting with "!!" as errors @@ -51,8 +61,15 @@ long as they are in use * Settings in UI get refreshed when opening settings dialog * New event "SettingsUpdated" -* Print time estimation is now not displayed until it becomes somewhat stable. Display in web interface now also happens - in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one +* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens + in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally + OctoPrint will use data from prior prints to enhance the initial print time estimation. +* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing + bug reports +* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if + it has been changed during runtime by external editing, hence no config settings added manually while the server + was running should be overwritten anymore. +* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected. ### Bug Fixes @@ -62,12 +79,20 @@ setups under Smoothieware * [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without side effects +* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers + in the parsed multipart data from file uploads * Various fixes of bugs in newly introduced features and improvements: * [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis queue + * [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again + * [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in + printer profiles + * [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in + printer profiles * Various fixes without tickets: * GCODE viewer now doesn't stumble over completely extrusionless GCODE files * Do not deliver the API key on settings API unless user has admin rights + * Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups ## 1.1.2 (Unreleased) From 363b23d6e337817aaf75e8b3cd884f9383467d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 21 Dec 2014 15:47:24 +0100 Subject: [PATCH 07/19] Better handling of errors while sending to (disconnected) clients on the websocket --- CHANGELOG.md | 2 ++ docs/events/index.rst | 4 ++++ src/octoprint/server/util/sockjs.py | 17 +++++++++++------ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06d6b1d18..ef1fb97fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,8 @@ it has been changed during runtime by external editing, hence no config settings added manually while the server was running should be overwritten anymore. * Automatically hard-reload the UI if upon reconnecting to the server a new version is detected. +* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning + message for now. ### Bug Fixes diff --git a/docs/events/index.rst b/docs/events/index.rst index a86f83a5e..55200cab0 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -96,6 +96,10 @@ ClientOpened ClientClosed A client has disconnected from the webserver + Payload: + + * ``remoteAddress``: the remote address (IP) of the client that disconnected + Printer communication --------------------- diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index bf9ee3cb0..3d321b39d 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -34,6 +34,8 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): self._eventManager = eventManager self._pluginManager = pluginManager + self._remoteAddress = None + def _getRemoteAddress(self, info): forwardedFor = info.headers.get("X-Forwarded-For") if forwardedFor is not None: @@ -41,8 +43,8 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): return info.ip def on_open(self, info): - remoteAddress = self._getRemoteAddress(info) - self._logger.info("New connection from client: %s" % remoteAddress) + self._remoteAddress = self._getRemoteAddress(info) + self._logger.info("New connection from client: %s" % self._remoteAddress) # connected => update the API key, might be necessary if the client was left open while the server restarted self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION}) @@ -52,20 +54,20 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): octoprint.timelapse.registerCallback(self) self._pluginManager.register_client(self) - self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress}) + self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress}) for event in octoprint.events.all_events(): self._eventManager.subscribe(event, self._onEvent) octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current) def on_close(self): - self._logger.info("Client connection closed") + self._logger.info("Client connection closed: %s" % self._remoteAddress) self._printer.unregisterCallback(self) self._fileManager.unregister_slicingprogress_callback(self) octoprint.timelapse.unregisterCallback(self) self._pluginManager.unregister_client(self) - self._eventManager.fire(Events.CLIENT_CLOSED) + self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress}) for event in octoprint.events.all_events(): self._eventManager.unsubscribe(event, self._onEvent) @@ -137,4 +139,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): self.sendEvent(event, payload) def _emit(self, type, payload): - self.send({type: payload}) + try: + self.send({type: payload}) + except Exception as e: + self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message)) From 103e0796b74f5e8ba5b2e346a2966da60a05df0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 21 Dec 2014 15:57:23 +0100 Subject: [PATCH 08/19] Request available slicers and slicing profiles from backend asynchronously when opening the slicing dialog Should make sure that slicers and new profiles are detected correctly even without reload. Could maybe help with #689 --- src/octoprint/static/js/app/viewmodels/slicing.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/slicing.js b/src/octoprint/static/js/app/viewmodels/slicing.js index 23a189372..7c60c60e9 100644 --- a/src/octoprint/static/js/app/viewmodels/slicing.js +++ b/src/octoprint/static/js/app/viewmodels/slicing.js @@ -28,6 +28,7 @@ function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) { self.afterSlicing = ko.observable("none"); self.show = function(target, file) { + self.requestData(); self.target = target; self.file = file; self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file})); @@ -48,13 +49,18 @@ function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) { && self.profile() != undefined; }); - self.requestData = function() { + self.requestData = function(callback) { $.ajax({ url: API_BASEURL + "slicing", type: "GET", dataType: "json", - success: self.fromResponse - }) + success: function(data) { + self.fromResponse(data); + if (callback !== undefined) { + callback(); + } + } + }); }; self.fromResponse = function(data) { From a0105bcb2fc5e08dc98b633470c6ca6028345cab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 1 Apr 2014 20:40:55 +0200 Subject: [PATCH 09/19] Better error handling for capture issues during timelapsing Should help debugging issue #425 and any future problems in that area. (cherry picked from commit 1a7a468) --- src/octoprint/timelapse.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 2c3b2c827..3a3ad9062 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -236,10 +236,13 @@ class Timelapse(object): return filename def _captureWorker(self, filename): - eventManager().fire(Events.CAPTURE_START, {"file": filename}); - urllib.urlretrieve(self._snapshotUrl, filename) - self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl)) - eventManager().fire(Events.CAPTURE_DONE, {"file": filename}); + eventManager().fire(Events.CAPTURE_START, {"file": filename}) + try: + urllib.urlretrieve(self._snapshotUrl, filename) + self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl)) + except: + self._logger.exception("Could not capture image %s from %s" % (filename, self._snapshotUrl)) + eventManager().fire(Events.CAPTURE_DONE, {"file": filename}) def _createMovie(self, success=True): ffmpeg = settings().get(["webcam", "ffmpeg"]) From fb1575170317c3ab96fc4f613a7ffa8cf20a2891 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 1 Apr 2014 22:32:10 +0200 Subject: [PATCH 10/19] Decrease image counter if an image could not be captured from webcam Should keep rendering of timelapse from breaking if only a couple of images couldn't be captured due to whatever reason. Suggested by @midopple in #344 (cherry picked from commit bf9d5ef) --- src/octoprint/timelapse.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 3a3ad9062..5474a4d37 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -241,7 +241,8 @@ class Timelapse(object): urllib.urlretrieve(self._snapshotUrl, filename) self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl)) except: - self._logger.exception("Could not capture image %s from %s" % (filename, self._snapshotUrl)) + self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl)) + self._imageNumber -= 1 eventManager().fire(Events.CAPTURE_DONE, {"file": filename}) def _createMovie(self, success=True): From 51341f6722f99b7909dc07fdd386fe2662bc502b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 4 Nov 2014 10:36:35 +0100 Subject: [PATCH 11/19] Added removal of pyc files (and their parent folders if they are empty after that) to the python setup.py clean command (cherry picked from commit 9e014eb) --- setup.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/setup.py b/setup.py index d06296ea2..b09d83527 100644 --- a/setup.py +++ b/setup.py @@ -27,6 +27,26 @@ def package_data_dirs(source, sub_folders): return dirs +def _recursively_handle_files(directory, file_matcher, folder_handler=None, file_handler=None): + applied_handler = False + + for filename in os.listdir(directory): + path = os.path.join(directory, filename) + + if file_handler is not None and file_matcher(filename): + file_handler(path) + applied_handler = True + + elif os.path.isdir(path): + sub_applied_handler = _recursively_handle_files(path, file_matcher, folder_handler=folder_handler, file_handler=file_handler) + if sub_applied_handler: + applied_handler = True + + if folder_handler is not None: + folder_handler(path, sub_applied_handler) + + return applied_handler + class CleanCommand(Command): description = "clean build artifacts" user_options = [] @@ -39,14 +59,37 @@ class CleanCommand(Command): pass def run(self): + # build folder if os.path.exists('build'): print "Deleting build directory" shutil.rmtree('build') + + # eggs eggs = glob.glob('OctoPrint*.egg-info') for egg in eggs: print "Deleting %s directory" % egg shutil.rmtree(egg) + # pyc files + def delete_folder_if_empty(path, applied_handler): + if not applied_handler: + return + if len(os.listdir(path)) == 0: + shutil.rmtree(path) + print "Deleted %s since it was empty" % path + + def delete_file(path): + os.remove(path) + print "Deleted %s" % path + + import fnmatch + _recursively_handle_files( + os.path.abspath("src"), + lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"), + folder_handler=delete_folder_if_empty, + file_handler=delete_file + ) + def get_cmdclass(): cmdclass = versioneer.get_cmdclass() From a30e41f0b42c51c9943b73492ee3aef8346f46d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 28 Dec 2014 00:12:19 +0100 Subject: [PATCH 12/19] Timelapses: Do not try to use image counter if still set to None and synchronize decrementing of image counter via mutex as well Possible fixes for #693, the latter maybe also for #690 --- CHANGELOG.md | 12 ++++++++++++ src/octoprint/timelapse.py | 9 +++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58e4a7c5e..e12f3ae89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,23 @@ ## 1.1.2 (Unreleased) +### Improvements + +* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported + from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0)) + ### Bug Fixes * [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated by versioneer * [IRC] Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups +* Small fixes for timelapse creation: + - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there + was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) + and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc)) + - [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset + - [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the + image file names ## 1.1.1 (2014-10-27) diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 5474a4d37..c27fb1a92 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -226,8 +226,12 @@ class Timelapse(object): self._logger.warn("Cannot capture image, capture directory is unset") return + if self._imageNumber is None: + self._logger.warn("Cannot capture image, image number is unset") + return + with self._captureMutex: - filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber)) + filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber) self._imageNumber += 1 self._logger.debug("Capturing image to %s" % filename) captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename}) @@ -242,7 +246,8 @@ class Timelapse(object): self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl)) except: self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl)) - self._imageNumber -= 1 + with self._captureMutex: + self._imageNumber -= 1 eventManager().fire(Events.CAPTURE_DONE, {"file": filename}) def _createMovie(self, success=True): From 6307b765e34029913f5b163f3dfc22c843261658 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 28 Dec 2014 00:19:55 +0100 Subject: [PATCH 13/19] Only decrement the image counter if it is set and larger than 0 Backported from devel --- src/octoprint/timelapse.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index c27fb1a92..9aa20d011 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -247,7 +247,8 @@ class Timelapse(object): except: self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl)) with self._captureMutex: - self._imageNumber -= 1 + if self._imageNumber is not None and self._imageNumber > 0: + self._imageNumber -= 1 eventManager().fire(Events.CAPTURE_DONE, {"file": filename}) def _createMovie(self, success=True): From 292856e1bd447e390b32cc232297ba1434500e89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 29 Dec 2014 20:45:54 +0100 Subject: [PATCH 14/19] Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url --- CHANGELOG.md | 3 +++ src/octoprint/templates/index.jinja2 | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e12f3ae89..d5db9e5ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated by versioneer * [IRC] Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups +* [ML] Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url * Small fixes for timelapse creation: - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) @@ -36,6 +37,8 @@ * [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup * [IRC] Also allow downloading .g files via Tornado +([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1)) + ## 1.1.0 (2014-09-03) ### New Features diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index 28d5b4f3a..fa0d72ecd 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -37,7 +37,7 @@ var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }}; var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }}; - var SOCKJS_URI = window.location.protocol.slice(0, -1) + "://" + (window.document ? window.document.domain : window.location.hostname) + ":" + window.location.port + "/sockjs"; + var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs"; var SOCKJS_DEBUG = {% if debug -%} true; {% else %} false; {%- endif %} From e3383fe4c1b54b15318d618a831e0b93642a8651 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 29 Dec 2014 20:48:33 +0100 Subject: [PATCH 15/19] Generated URLs now take X-Forwarded-Host header sent by proxies into account for included host and port --- CHANGELOG.md | 1 + src/octoprint/server/util.py | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d5db9e5ee..22c8a8ab2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ by versioneer * [IRC] Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups * [ML] Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url +* [unreported] Generated URLs now take X-Forwarded-Host header sent by proxies into account for included host and port * Small fixes for timelapse creation: - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) diff --git a/src/octoprint/server/util.py b/src/octoprint/server/util.py index 711496864..4e03d49ad 100644 --- a/src/octoprint/server/util.py +++ b/src/octoprint/server/util.py @@ -373,6 +373,14 @@ class ReverseProxied(object): if scheme: environ['wsgi.url_scheme'] = scheme + + host = environ.get('HTTP_X_FORWARDED_HOST', '') + if not host: + host = settings().get(["server", "host"]) + + if host: + environ['HTTP_HOST'] = host + return self.app(environ, start_response) From 87ddcac2fce893ef9c9d749c50623b98fc354bb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 30 Dec 2014 10:20:50 +0100 Subject: [PATCH 16/19] Don't user server.host but server.forwardedHost as fallback for generated external URLs Closes #698 --- CHANGELOG.md | 8 +++++--- src/octoprint/server/util.py | 2 +- src/octoprint/settings.py | 3 ++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22c8a8ab2..87e442086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,11 @@ * [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated by versioneer -* [IRC] Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups -* [ML] Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url -* [unreported] Generated URLs now take X-Forwarded-Host header sent by proxies into account for included host and port +* [IRC] - Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups +* [ML] - Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url +* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header + sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698) + introduced by this * Small fixes for timelapse creation: - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) diff --git a/src/octoprint/server/util.py b/src/octoprint/server/util.py index 4e03d49ad..de782d269 100644 --- a/src/octoprint/server/util.py +++ b/src/octoprint/server/util.py @@ -376,7 +376,7 @@ class ReverseProxied(object): host = environ.get('HTTP_X_FORWARDED_HOST', '') if not host: - host = settings().get(["server", "host"]) + host = settings().get(["server", "forwardedHost"]) if host: environ['HTTP_HOST'] = host diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 0f70641f2..259edaac8 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -43,7 +43,8 @@ default_settings = { "firstRun": True, "secretKey": None, "baseUrl": "", - "scheme": "" + "scheme": "", + "forwardedHost": "" }, "webcam": { "stream": None, From 2b7885c3f8738eeee34c5778b0b81fbccb1139fc Mon Sep 17 00:00:00 2001 From: bortek Date: Tue, 30 Dec 2014 12:18:39 +0100 Subject: [PATCH 17/19] Update printer.rst --- docs/api/printer.rst | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/api/printer.rst b/docs/api/printer.rst index a39c51214..9ba1ab629 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -331,7 +331,7 @@ Retrieve the current SD state GET /api/printer/sd HTTP/1.1 Host: example.com - **Example Response** + **ponse** .. sourcecode:: http @@ -345,6 +345,33 @@ Retrieve the current SD state :statuscode 200: No error :statuscode 404: If SD support has been disabled in OctoPrint's config. +.. _sec-api-printer-arbcommand: + +Send an arbitrary command to the printer +============================= + +.. http:post:: /api/printer/command + + Sends any command to the printer via serial inerface. Should be used with some care as some commands can stop a running print job. + + If successful returns a :http:statuscode:`204` and an empty body. + + **Example Request** + + .. sourcecode:: http + POST /api/printer/command HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "M27" + } + + + :json string command: The command to issue. + :statuscode 204: No error + .. _sec-api-printer-datamodel: Datamodel @@ -366,4 +393,4 @@ SD State Response * - ``ready`` - 1 - Boolean - - Whether the SD card has been initialized (``true``) or not (``false``). \ No newline at end of file + - Whether the SD card has been initialized (``true``) or not (``false``). From bf6a32907c9c32d2c65f18dc6b74f439e5f3ce86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 31 Dec 2014 15:09:31 +0100 Subject: [PATCH 18/19] Ported possibility to set external host via headers from reverse proxy to the devel branch --- src/octoprint/server/__init__.py | 4 +++- src/octoprint/server/util/__init__.py | 20 +++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 96db47417..294ee110c 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -280,8 +280,10 @@ class Server(): app.wsgi_app, settings().get(["server", "reverseProxy", "prefixHeader"]), settings().get(["server", "reverseProxy", "schemeHeader"]), + settings().get(["server", "reverseProxy", "hostHeader"]), settings().get(["server", "reverseProxy", "prefixFallback"]), - settings().get(["server", "reverseProxy", "prefixScheme"]) + settings().get(["server", "reverseProxy", "schemeFallback"]), + settings().get(["server", "reverseProxy", "hostFallback"]) ) secret_key = settings().get(["server", "secretKey"]) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 83c246cc9..b69022698 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -147,20 +147,25 @@ class ReverseProxied(object): :param app: the WSGI application :param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix :param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme + :param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs :param base_url: the prefix to use as fallback if headers are not set + :param scheme: the scheme to use as fallback if headers are not set + :param host: the host to use as fallback if headers are not set """ - def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""): + def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""): self.app = app - # headers for prefix & scheme, converted to conform to WSGI format + # headers for prefix & scheme & host, converted to conform to WSGI format to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_") self._header_prefix = to_wsgi_format(header_prefix) self._header_scheme = to_wsgi_format(header_scheme) + self._header_host = to_wsgi_format(header_host) - # fallback prefix & scheme from config + # fallback prefix & scheme & host from config self._fallback_prefix = base_url self._fallback_scheme = scheme + self._fallback_host = host def __call__(self, environ, start_response): # determine prefix @@ -184,6 +189,15 @@ class ReverseProxied(object): if scheme: environ["wsgi.url_scheme"] = scheme + # determine host + host = environ.get(self._header_host, "") + if not host: + host = self._fallback_host + + # rewrite host header based on host + if host: + environ["HTTP_HOST"] = host + # call wrapped app with rewritten environment return self.app(environ, start_response) From c9c4066331b9f68cf86591d78921d6255915b13d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 31 Dec 2014 15:22:48 +0100 Subject: [PATCH 19/19] Fixed a bunch of doc issues, updated /api/printer/command to have more meaningful error messages --- docs/api/printer.rst | 62 ++++++++++++++++++++++++++--- src/octoprint/server/api/printer.py | 15 +++---- 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/docs/api/printer.rst b/docs/api/printer.rst index b6e695754..469af8dde 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -758,29 +758,57 @@ Retrieve the current SD state .. _sec-api-printer-arbcommand: Send an arbitrary command to the printer -============================= +======================================== .. http:post:: /api/printer/command - Sends any command to the printer via serial inerface. Should be used with some care as some commands can stop a running print job. + Sends any command to the printer via the serial interface. Should be used with some care as some commands can interfere with + or even stop a running print job. + + Expects a :ref:`Arbitrary Command Request ` as the request's body. If successful returns a :http:statuscode:`204` and an empty body. - **Example Request** + **Example for sending a single command** .. sourcecode:: http + POST /api/printer/command HTTP/1.1 Host: example.com Content-Type: application/json X-Api-Key: abcdef... { - "command": "M27" + "command": "M106" } + .. sourcecode:: http + + HTTP/1.1 204 No Content + + **Example for sending multiple commands** + + .. sourcecode:: http + + POST /api/printer/command HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "commands": [ + "M18", + "M106 S0" + ] + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content - :json string command: The command to issue. - :statuscode 204: No error + :json string command: Single command to send to the printer, mutually exclusive with ``commands``. + :json string commands: List of commands to send to the printer, mutually exclusive with ``command``. + :statuscode 204: No error .. _sec-api-printer-datamodel: @@ -857,3 +885,25 @@ SD State - 1 - Boolean - Whether the SD card has been initialized (``true``) or not (``false``). + +.. _sec-api-printer-datamodel-arbcommand: + +Arbitrary Command Request +------------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``command`` + - 0..1 + - String + - Single command to send to the printer, mutually exclusive with ``commands``. + * - ``commands`` + - 0..* + - Array of String + - Multiple commands to send to the printer (in the given order), mutually exclusive with ``command``. diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 55ae6d3b1..2f5662d51 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -300,7 +300,6 @@ def printerSdState(): @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): - # TODO: document me if not printer.isOperational(): return make_response("Printer is not operational", 409) @@ -309,15 +308,17 @@ def printerCommand(): data = request.json - parameters = {} - if "parameters" in data.keys(): - parameters = data["parameters"] + parameters = dict() + if "parameters" in data.keys(): parameters = data["parameters"] - commands = [] - if "command" in data.keys(): + if "command" in data and "commands" in data: + return make_response("'command' and 'commands' are mutually exclusive", 400) + elif "command" in data: commands = [data["command"]] - elif "commands" in data.keys(): + elif "commands" in data and isinstance(data["commands"], (list, tuple)): commands = data["commands"] + else: + return make_response("Need either single 'command' or list of 'commands'", 400) commandsToSend = [] for command in commands: