Merge branch 'maintenance' into devel

# Conflicts:
#	docs/plugins/hooks.rst
#	src/octoprint/server/__init__.py
This commit is contained in:
Gina Häußge committed 2017-07-26 14:31:08 +02:00
commit cd6009c180
76 files changed
+4870 -4411

No files matched your search

+5 -5
View File
@@ -18,12 +18,12 @@ HEAD
# maintenance is currently the branch for preparation of maintenance release 1.3.5
# so are any fix/... and improve/... branches
maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.5rc1
staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.5rc2
staging/maintenance 1.3.5rc2 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+71
View File
@@ -1,5 +1,76 @@
# OctoPrint Changelog
## 1.3.5rc1 (2017-07-26)
### Improvements
* [#1162](https://github.com/foosel/OctoPrint/pull/1162) - Allow `octoprint.comm.protocol.gcode.queuing` hook to return a list of commands.
* [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order.
* [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time.
* [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature.
* [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder).
* [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)).
* [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts.
* [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins.
* [#1941](https://github.com/foosel/OctoPrint/issues/1941) - Enable "block while dwelling" flag when Malyan firmware is detected since that firmware seems to handle `G4` identically to Repetier Firmware instead of Marlin (like it claims to). See also [#1762](https://github.com/foosel/OctoPrint/issues/1762).
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Add option to disable position logging on cancel/pause. See "Log position on cancel" and "Log position on pause" under Settings > Serial > Advanced options.
* [#1971](https://github.com/foosel/OctoPrint/issues/1971) - Refactored temperature inputs. They now sport some fancy +/- buttons to increment/decrement the current temperature (which also auto submit after a couple of seconds) and easier editing by keyboard. The temperature offset was also slightly redesigned to make room for that.
* [#1975](https://github.com/foosel/OctoPrint/issues/1975) - Better error reporting when deleting timelapses.
* [#2010](https://github.com/foosel/OctoPrint/pull/2010) - Slight refactoring in the terminal tab: Full width input field, auto focus of input field when just clicking on terminal output.
* [#2011](https://github.com/foosel/OctoPrint/issues/2011) - Centralized online connectivity check (with opt-in of course). None of the bundled plugins will attempt to fetch data from the net when the connectivity check indicates that would fail anyhow. This should improve server startup times and various requests when running isolated.
* [#2025](https://github.com/foosel/OctoPrint/issues/2025) - More verbose logging of asynchronous system commands (e.g. restart/shutdown).
* Allow timelapse configuration through UI even when not connected to the printer (suggested in [#1918](https://github.com/foosel/OctoPrint/issues/1918))
* Disable "Upload to SD" UI elements while printing (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
* Update bundled SockJS to 1.1.2 incl. source maps
* Set `X-Robots` HTTP header and remove `Server` header from all responses, also set `robots` meta tag in page.
* Don't require to enter programmer mode for printer port autodetection when there's only one possible port candidate anyhow.
* More sensible sorting of baudrates (additionally configured, then 115200, then 250000, then everything else).
* Don't show "Unhandled communication error" on autodetection failure.
* Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937))
* Add `ToolChange` event and tool change GCODE scripts
* Support parsing GCODE subcodes.
* Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses.
* Corewizard: Disable view model and client code if it's not actually required.
* Corewizard: Disable injection of JS files into UI when it's not actually required.
* GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems.
* GCODE viewer: Ignore coordinates outside bed when zooming/centering on model. Those usually are nozzle priming routines.
* JS Client Lib: Add centralized browser detection as `OctoPrint.coreui.browser`. Available properties: `chrome`, `firefox`, `safari`, `ie`, `edge`, `opera` as well as `mobile` and `desktop`, all of which are boolean values.
* Plugin Manager plugin: Detect if a plugin requires a reconnect to the printer to become fully active/inactive.
* Software Update plugin: Force exact version when updating OctoPrint and tracking releases.
* Software Update plugin: "Devel RCs" release channel now also tracks maintenance RCs. That way people don't have to toggle between the two any more to get *all* RCs.
* Software Update plugin: `bitbucket_commit` check type now supports API credentials (see also [#1993](https://github.com/foosel/OctoPrint/pull/1993)).
* Wizard: Allow suppressing the "the settings got updated" dialog through subwizards, in case they need to update settings asynchronously as part of their workflow.
* More resilience against expected folders being files.
* More resilience against a wrong user manager class being configured.
* Some code refactoring & cleanup.
* Some HTML & CSS improvements.
### Bug fixes
* [#1916](https://github.com/foosel/OctoPrint/issues/1916) - Fix webcam not loading if first/initial tab is "Control"
* [#1924](https://github.com/foosel/OctoPrint/issues/1924) - Filter out source map links from bundled JS webassets.
* [#1943](https://github.com/foosel/OctoPrint/issues/1943) - Fix issue causing unnecessary creation of default printer profile on startup
* [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Decouple writing of print log from everything else. Fixes delay in cancel processing.
* [#1963](https://github.com/foosel/OctoPrint/issues/1963) & [#1974](https://github.com/foosel/OctoPrint/issues/1974) - Allow empty & custom size in print job events. Also fixes an issue with timelapses when printing from SD on printers that require the GPX plugin to work.
* [#1996](https://github.com/foosel/OctoPrint/issues/1996) - Support all line ending variantes in the GCODE viewer. Solves an issue with GCODE generated for Prusa's multi material extruder since that uses only `\r` for some reason.
* [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values.
* [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin.
* [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered.
* Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
* Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly.
* Don't hex-escape `\t`, `\r` or `\n` in terminal output
* Use client side default printer profile if the default profile could not be found on the server
* Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances.
* Fix potential race condition in resend request handling.
* Fix potential race condition in web socket handling.
* Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations.
* Fix `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved` events not being fired with the correct event name.
* Fix potential division by zero in progress reporting if the timing was just right.
* Fix sorting order for multiple tools in the "State" panel.
* Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress.
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5rc1))
## 1.3.4 (2017-06-01)
### Note for owners of Malyan M200/Monoprice Select Mini
+6 -5
View File
@@ -7,6 +7,7 @@ thanks to everyone who contributed!
## Patreon Patrons
* 3D Moniak
* Aaron Lieberman
* Aleph Objects, Inc.
* Andrew Moorby
* Arnljot Arntsen
@@ -14,24 +15,24 @@ thanks to everyone who contributed!
* Boris Hussein
* Brad Jackson
* Brian E. Tyler
* Chris Day
* Christian Petropolis
* COLLE+McVOY
* CreativeTools
* D Brian Kimmel
* DeltaMaker 3D Printers
* Doug Johnson
* E3D BigBox
* Ernesto Martinez
* Exovite
* F. Kunsmann
* Farren Young II
* Frank Sander
* Gary Deen
* Gary N McKinney
* George Robles
* günter weber
* Ivan Krasin
* James Seigel
* Jamie R McGuigan
* Jason Lawrence
* Jeff Moe
* Josh Daniels
* Kaile Riser
@@ -55,14 +56,14 @@ thanks to everyone who contributed!
* Roger Strolz
* Roy Cortes
* Samer Najia
* SD3D
* SeeMeCNC
* Simon Hallam
* Stefan Krister
* Stephane Schittly
* Sven Mueller
* Symbiotic Devices
* Thomas Hatley
* Timeshell.ca
* Trent Shumay
and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1117 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+14
View File
@@ -909,6 +909,20 @@ Use the following settings to configure the server:
# Command to shut down the system OctoPrint is running on, defaults to being unset
systemShutdownCommand: sudo shutdown -h now
# Configuration of the regular online connectivity check
onlineCheck:
# whether the online check is enabled, defaults to false due to valid privacy concerns
enabled: false
# interval in which to check for online connectivity (in seconds)
interval: 300
# DNS host against which to check (default: 8.8.8.8 aka Google's DNS)
host: 8.8.8.8
# DNS port against which to check (default: 53 - the default DNS port)
port: 53
# Settings of when to display what disk space warning
diskspace:
+8
View File
@@ -110,6 +110,14 @@ ClientClosed
* ``remoteAddress``: the remote address (IP) of the client that disconnected
ConnectivityChanged
The server's internet connectivity changed
Payload:
* ``old``: Old connectivity value (true for online, false for offline)
* ``new``: New connectivity value (true for online, false for offline)
Printer communication
---------------------
+6
View File
@@ -87,6 +87,9 @@ There are a few additional template variables available for the following specif
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See
``last_position`` above for the structure to expect here.
**Please note:** This will not be available if you disable
"Log position on pause" under Settings > Serial > Advanced options!
* ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
for the structure to expect here.
@@ -94,6 +97,9 @@ There are a few additional template variables available for the following specif
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
See ``last_position`` above for the structure to expect here.
**Please note:** This will not be available if you disable
"Log position on cancel" under Settings > Serial > Advanced options!
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
for the structure to expect here.
+1
View File
@@ -14,4 +14,5 @@ Internal Modules
server.rst
settings.rst
slicing.rst
users.rst
util.rst
+9
View File
@@ -0,0 +1,9 @@
.. _sec-modules-users:
octoprint.users
---------------
.. automodule:: octoprint.users
:members:
+47 -9
View File
@@ -426,7 +426,7 @@ This describes actually four hooks:
* ``None``: Don't change anything. Note that Python functions will also automatically return ``None`` if
an empty ``return`` statement is used or just nothing is returned explicitly from the handler. Hence, the following
examples are all falling into this category:
examples are all falling into this category and equivalent:
.. code-block:: python
@@ -451,21 +451,24 @@ This describes actually four hooks:
should use this option.
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
Handlers which wish to rewrite both the command and the command type should use this option.
* A list of any of the above to allow for expanding one command into
* **"queuing" phase only**: A list of any of the above to allow for expanding one command into
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
does not make a lot of sense to be quite honest):
.. code-block:: python
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
if gcode or not cmd.startswith("@foo"):
return
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
if gcode or not cmd.startswith("@foo"):
return
return [("M105", "temperature_poll"),
("M110",),
"M117 echo foo: {}".format(cmd)]
return [("M105", "temperature_poll"), # 2-tuple, command & command type
("M110",), # 1-tuple, just the command
"M117 echo foo: {}".format(cmd)] # string, just the command
__plugin_hooks__ = {
"octoprint.comm.protocol.gcode.queuing": rewrite_foo
}
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
to one already in the queue will give an error.
@@ -944,6 +947,41 @@ octoprint.ui.web.templatetypes
:return: a list of 3-tuples (template type, rule, sorting spec)
:rtype: list
.. _sec-plugins-hook-users-factory:
octoprint.users.factory
~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
be called only once during initial server startup.
The provided ``components`` is a dictionary containing the already initialized system components:
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
* ``event_bus``: The :class:`~octoprint.events.EventManager`
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
If no of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
:class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage
file ``~/.octoprint/users.yaml``.
:param dict components: System components to use for user manager instance initialization
:param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
:return: The ``userManager`` instance to use globally.
:rtype: UserManager subclass or None
.. _sec-plugins-hook-timelapse-capture-pre:
octoprint.timelapse.capture.pre
@@ -974,4 +1012,4 @@ octoprint.timelapse.capture.post
:param str filename: The path of the frame that should have been saved.
:param boolean success: Indicates whether the capture was successful or not.
:return: None
:rtype: None
:rtype: None
+2
View File
@@ -45,6 +45,8 @@ An overview of these properties follows.
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
``self._user_manager``
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
``self._connectivity_checker``
OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
.. seealso::
+2 -1
View File
@@ -46,7 +46,8 @@ INSTALL_REQUIRES = [
"scandir>=1.3,<1.4",
"websocket-client>=0.40,<0.41",
"python-dateutil>=2.6,<2.7",
"wrapt>=1.10.10,<1.11"
"wrapt>=1.10.10,<1.11",
"futures>=3.1.1,<3.2"
]
if sys.platform == "darwin":
+47 -24
View File
@@ -9,7 +9,7 @@ import json
import octoprint_client
from octoprint.cli import get_ctx_obj_option
from octoprint.cli import get_ctx_obj_option, bulk_options
from octoprint import init_settings, FatalStartupError
@@ -23,43 +23,66 @@ class JsonStringParamType(click.ParamType):
self.fail("%s is not a valid json string" % value, param, ctx)
def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
assert(host is not None or settings is not None)
assert(port is not None or settings is not None)
assert(apikey is not None or settings is not None)
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not apikey:
apikey = settings.get(["api", "key"])
baseurl = octoprint_client.build_base_url(https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix)
return octoprint_client.Client(baseurl, apikey)
client_options = bulk_options([
click.option("--apikey", "-a", type=click.STRING),
click.option("--host", "-h", type=click.STRING),
click.option("--port", "-p", type=click.INT),
click.option("--httpuser", type=click.STRING),
click.option("--httppass", type=click.STRING),
click.option("--https", is_flag=True),
click.option("--prefix", type=click.STRING)
])
"""Common options to configure an API client."""
@click.group()
def client_commands():
pass
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
@click.option("--apikey", "-a", type=click.STRING)
@click.option("--host", "-h", type=click.STRING)
@click.option("--port", "-p", type=click.INT)
@click.option("--httpuser", type=click.STRING)
@click.option("--httppass", type=click.STRING)
@click.option("--https", is_flag=True)
@click.option("--prefix", type=click.STRING)
@client_options
@click.pass_context
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
ctx.obj.client = create_client(settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
if not apikey:
apikey = settings.get(["api", "key"])
baseurl = octoprint_client.build_base_url(https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix)
ctx.obj.client = octoprint_client.Client(baseurl, apikey)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
+4 -2
View File
@@ -60,6 +60,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN)
self._initialized = True
def list_commands(self, ctx):
@@ -88,14 +90,14 @@ class OctoPrintPluginCommands(click.MultiCommand):
continue
result[name + self.sep + command.name] = command
except:
self._logger.exception("Error while retrieving cli commants for plugin {}".format(name))
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
return result
@click.group()
@pass_octoprint_ctx
def plugin_commands(obj):
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
pass
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins():
+2 -1
View File
@@ -27,9 +27,10 @@ def all_events():
class Events(object):
# application startup
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# connect/disconnect to printer
CONNECTING = "Connecting"
+13
View File
@@ -135,3 +135,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else:
return c * indent + " " + message
def prefix_multilines(text, prefix=": "):
lines = text.splitlines()
if not lines:
return ""
if len(lines) == 1:
return lines[0]
return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
lines[1:]))
+6 -1
View File
@@ -177,7 +177,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -213,6 +213,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
is determined be presence of injected ``_identifier`` property.
"""
@@ -225,6 +227,9 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if initialized and not hasattr(plugin, "_identifier"):
continue
if hasattr(plugin, method):
try:
result = getattr(plugin, method)(*args, **kwargs)
@@ -28,7 +28,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin):
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin):
def __init__(self):
self._cached_channel_configs = None
@@ -210,6 +211,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return NO_CONTENT
##~~ EventHandlerPlugin
def on_event(self, event, payload):
from octoprint.events import Events
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
return
self._fetch_all_channels_async()
# Internal Tools
def _mark_read_until(self, channel, until):
@@ -266,6 +275,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
safe_key = self._slugify(key)
return self._get_channel_configs(force=force).get(safe_key)
def _fetch_all_channels_async(self, force=False):
thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force))
thread.daemon = True
thread.start()
def _fetch_all_channels(self, force=False):
"""Fetch all channel feeds from cache or network."""
@@ -298,7 +312,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
if data is None:
# cache not allowed or empty, fetch from network
data = self._get_channel_data_from_network(key, config)
if self._connectivity_checker.online:
data = self._get_channel_data_from_network(key, config)
else:
self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key))
return data
@@ -40,7 +40,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o";
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -317,7 +317,13 @@ $(function() {
self.announcementDialog = $("#plugin_announcements_dialog");
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
};
self.onEventConnectivityChanged = function(payload) {
if (!payload || !payload.new) return;
self.retrieveData();
}
}
// view model class, parameters for constructor, container to bind to
+40 -2
View File
@@ -59,8 +59,14 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ WizardPlugin API
def is_wizard_required(self):
methods = self._get_subwizard_attrs("_is_", "_wizard_required")
return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values()))
required = self._get_subwizard_attrs("_is_", "_wizard_required")
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
any_not_firstrunonly = any(map(lambda m: not m(), firstrunonly.values()))
any_required = any(map(lambda m: m(), required.values()))
return (firstrun or any_not_firstrunonly) and any_required
def get_wizard_details(self):
result = dict()
@@ -71,8 +77,14 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
return result
def get_wizard_version(self):
return 1
#~~ ACL subwizard
def _is_acl_wizard_firstrunonly(self):
return True
def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
@@ -114,6 +126,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ Webcam subwizard
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
@@ -129,6 +144,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ Server commands subwizard
def _is_servercommands_wizard_firstrunonly(self):
return True
def _is_servercommands_wizard_required(self):
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
@@ -142,8 +160,28 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
def _get_servercommands_wizard_name(self):
return gettext("Server Commands")
#~~ Online check subwizard
def _is_onlinecheck_wizard_firstrunonly(self):
return False
def _is_onlinecheck_wizard_required(self):
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
def _get_onlinecheck_wizard_details(self):
return dict(required=self._is_onlinecheck_wizard_required())
def _get_onlinecheck_wizard_name(self):
return gettext("Online connectivity check")
def _get_onlinecheck_additional_wizard_template_data(self):
return dict(mandatory=self._is_onlinecheck_wizard_required())
#~~ Printer profile subwizard
def _is_printerprofile_wizard_firstrunonly(self):
return True
def _is_printerprofile_wizard_required(self):
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
@@ -125,6 +125,88 @@ $(function() {
self.settingsViewModel = parameters[0];
}
function CoreWizardOnlineCheckViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.setup = ko.observable(false);
self.decision = ko.observable();
self.required = false;
self.active = false;
self.enableOnlineCheck = function() {
self.settingsViewModel.server_onlineCheck_enabled(true);
self.decision(true);
self._sendData();
};
self.disableOnlineCheck = function() {
self.settingsViewModel.server_onlineCheck_enabled(false);
self.decision(false);
self._sendData();
};
self.onBeforeWizardTabChange = function(next, current) {
if (!self.required) return true;
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
return true;
}
self._showDecisionNeededDialog();
return false;
};
self.onBeforeWizardFinish = function() {
if (!self.required) return true;
if (self.setup()) {
return true;
}
self._showDecisionNeededDialog();
return false;
};
self.onWizardPreventSettingsRefreshDialog = function() {
return self.active;
};
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
};
self._showDecisionNeededDialog = function() {
showMessageDialog({
title: gettext("Please set up the online connectivity check"),
message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
});
};
self._sendData = function() {
var data = {
server: {
onlineCheck: {
enabled: self.settingsViewModel.server_onlineCheck_enabled(),
interval: self.settingsViewModel.server_onlineCheck_interval(),
host: self.settingsViewModel.server_onlineCheck_host(),
port: self.settingsViewModel.server_onlineCheck_port()
}
}
};
self.active = true;
self.settingsViewModel.saveData(data)
.done(function() {
self.setup(true);
self.active = false;
});
};
}
function CoreWizardPrinterProfileViewModel(parameters) {
var self = this;
@@ -172,6 +254,10 @@ $(function() {
CoreWizardServerCommandsViewModel,
["settingsViewModel"],
"#wizard_plugin_corewizard_servercommands"
], [
CoreWizardOnlineCheckViewModel,
["settingsViewModel"],
"#wizard_plugin_corewizard_onlinecheck"
], [
CoreWizardPrinterProfileViewModel,
["printerProfilesViewModel"],
@@ -0,0 +1,46 @@
<h3>{{ _('Configure the connectivity check') }}</h3>
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
<p>{% trans %}
If it is disabled OctoPrint will always assume to have a working connection to the internet.
If that should not actually be the case, server startups, update checks and the like might take longer.
{% endtrans %}</p>
<p>{% trans %}
OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here.
{% endtrans %}</p>
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
</form>
<p>{% trans %}
OctoPrint comes preconfigured to utilize Google's DNS server <code>8.8.8.8</code>, port 53 for the connectivity check (if
it's enabled). If you have concerns about using that, define the IP and port of a different online server that you
trust and that has a high availability.
{% endtrans %}</p>
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
</form>
<p>{% trans %}
Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
any time to a later date through Settings > Server right from within OctoPrint.
{% endtrans %}</p>
<div class="row-fluid">
<a href="#" class="btn span6" data-bind="click: function() { if(!setup()){disableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Connectivity Check') }}</a>
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){enableOnlineCheck()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Enable Connectivity Check') }}</a>
</div>
<div class="onlinecheck_decision" style="display: none" data-bind="visible: setup()">
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
Connectivity check is <strong class="text-success">enabled</strong>.
{% endtrans %}</div>
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
Connectivity check is <strong class="text-danger">disabled</strong>.
{% endtrans %}</div>
</div>
+35 -10
View File
@@ -36,7 +36,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.BlueprintPlugin):
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.EventHandlerPlugin):
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
@@ -100,13 +101,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.propagate = False
# decouple repository fetching from server startup
def fetch_data():
self._repository_available = self._fetch_repository_from_disk()
self._notices_available = self._fetch_notices_from_disk()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
self._fetch_all_data(async=True)
##~~ SettingsPlugin
@@ -197,6 +192,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
except Exception as e:
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
##~~ EventHandlerPlugin
def on_event(self, event, payload):
from octoprint.events import Events
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
return
self._fetch_all_data(async=True)
##~~ SimpleApiPlugin
def get_api_commands(self):
@@ -239,7 +242,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
additional_args=self._settings.get(["pip_args"]),
python=sys.executable
),
safe_mode=safe_mode)
safe_mode=safe_mode,
online=self._connectivity_checker.online)
def etag():
import hashlib
@@ -250,6 +254,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
hash.update(str(self._notices_available))
hash.update(repr(self._notices))
hash.update(repr(safe_mode))
hash.update(repr(self._connectivity_checker.online))
return hash.hexdigest()
def condition():
@@ -679,6 +684,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
def _fetch_all_data(self, async=False):
def run():
self._repository_available = self._fetch_repository_from_disk()
self._notices_available = self._fetch_notices_from_disk()
if async:
thread = threading.Thread(target=run)
thread.daemon = True
thread.start()
else:
run()
def _fetch_repository_from_disk(self):
repo_data = None
if os.path.isfile(self._repository_cache_path):
@@ -696,6 +713,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return self._refresh_repository(repo_data=repo_data)
def _fetch_repository_from_url(self):
if not self._connectivity_checker.online:
self._logger.info("Looks like we are offline, can't fetch repository from network")
return None
repository_url = self._settings.get(["repository"])
try:
r = requests.get(repository_url, timeout=30)
@@ -758,13 +779,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
import json
with open(self._notices_cache_path) as f:
notice_data = json.load(f)
self._logger.info("Loaded notices from disk, was still valid")
self._logger.info("Loaded notice data from disk, was still valid")
except:
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
return self._refresh_notices(notice_data=notice_data)
def _fetch_notices_from_url(self):
if not self._connectivity_checker.online:
self._logger.info("Looks like we are offline, can't fetch notices from network")
return None
notices_url = self._settings.get(["notices"])
try:
r = requests.get(notices_url, timeout=30)
@@ -174,6 +174,7 @@ $(function() {
self.pipPython = ko.observable();
self.safeMode = ko.observable();
self.online = ko.observable();
self.pipUseUserString = ko.pureComputed(function() {
return self.pipUseUser() ? "yes" : "no";
@@ -234,7 +235,7 @@ $(function() {
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
};
self.invalidUrl = ko.pureComputed(function() {
@@ -244,7 +245,7 @@ $(function() {
self.enableUrlInstall = ko.pureComputed(function() {
var url = self.installUrl();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && url !== undefined && url.trim() != "" && !self.invalidUrl();
});
self.invalidArchive = ko.pureComputed(function() {
@@ -321,6 +322,7 @@ $(function() {
self._fromPipResponse(data.pip, options);
self.safeMode(data.safe_mode || false);
self.online(data.online !== undefined ? data.online : true);
};
self._fromPluginsResponse = function(data, options) {
@@ -814,7 +816,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle";
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -1020,6 +1022,10 @@ $(function() {
self._closeAllNotifications();
};
self.onEventConnectivityChanged = function(payload) {
self.requestData({eval_notices: true});
};
self._closeAllNotifications = function() {
if (self.notifications) {
_.each(self.notifications, function(notification) {
@@ -20,6 +20,13 @@
{% endtrans %}</div>
{% endmacro %}
{% macro pluginmanager_offline() %}
<div class="alert" data-bind="visible: !online()">{% trans %}
It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
to install new plugins from the plugin repository or archive URLs.
{% endtrans %}</div>
{% endmacro %}
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
@@ -124,6 +131,7 @@
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
{{ pluginmanager_offline() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<div class="dropdown pull-right">
+128 -58
View File
@@ -15,6 +15,9 @@ import time
import logging
import logging.handlers
import hashlib
import traceback
from concurrent import futures
from . import version_checks, updaters, exceptions, util, cli
@@ -34,7 +37,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin):
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin):
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
@@ -44,7 +48,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._configured_checks = None
self._refresh_configured_checks = False
self._get_versions_mutex = threading.Lock()
self._get_versions_mutex = threading.RLock()
self._get_versions_data = None
self._get_versions_data_ready = threading.Event()
self._version_cache = dict()
self._version_cache_ttl = 0
@@ -467,15 +473,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
def view():
try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
# we don't want to transfer python_checker or python_updater values through json - replace with True
for key, data in information.items():
if "check" in data:
if "python_checker" in data["check"]:
data["check"]["python_checker"] = True
if "python_updater" in data["check"]:
data["check"]["python_updater"] = True
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
information=information,
timestamp=self._version_cache_timestamp))
@@ -502,9 +499,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash.update(repr(data["information"]))
hash.update(str(data["available"]))
hash.update(str(data["possible"]))
hash.update(str(data.get("online", None)))
hash.update(",".join(targets))
hash.update(str(self._version_cache_timestamp))
hash.update(str(self._connectivity_checker.online))
return hash.hexdigest()
def condition():
@@ -568,6 +567,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
return check and "update_script" in check and not checkout_folder
##~~ EventHandlerPlugin API
def on_event(self, event, payload):
from octoprint.events import Events
if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
return
thread = threading.Thread(target=self.get_current_versions)
thread.daemon = True
thread.start()
#~~ Updater
def get_current_versions(self, check_targets=None, force=False):
@@ -587,53 +597,91 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
information = dict()
# we don't want to do the same work twice, so let's use a lock
with self._get_versions_mutex:
for target, check in checks.items():
if not target in check_targets:
continue
if self._get_versions_mutex.acquire(False):
self._get_versions_data_ready.clear()
try:
futures_to_result = dict()
online = self._connectivity_checker.check_immediately()
self._logger.debug("Looks like we are {}".format("online" if online else "offline"))
if not check:
continue
with futures.ThreadPoolExecutor(max_workers=5) as executor:
for target, check in checks.items():
if not target in check_targets:
continue
try:
populated_check = self._populated_check(target, check)
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
if target_information is None:
target_information = dict()
except exceptions.UnknownCheckType:
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
continue
if not check:
continue
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
try:
populated_check = self._populated_check(target, check)
future = executor.submit(self._get_current_version, target, populated_check, force=force)
futures_to_result[future] = (target, populated_check)
except exceptions.UnknownCheckType:
self._logger.warn("Unknown update check type for target {}: {}".format(target,
check.get("type",
"<n/a>")))
continue
except:
self._logger.exception("Could not check {} for updates".format(target))
continue
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
for future in futures.as_completed(futures_to_result):
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
target, populated_check = futures_to_result[future]
if future.exception() is not None:
self._logger.error("Could not check {} for updates, error: {!r}".format(target,
future.exception()))
continue
release_notes = None
if target_information and target_information["remote"] and target_information["remote"]["value"]:
if "release_notes" in populated_check and populated_check["release_notes"]:
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"]["release_notes"]
target_information, target_update_available, target_update_possible, target_online, target_error = future.result()
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
target_information = dict_merge(dict(local=dict(name="?", value="?"),
remote=dict(name="?", value="?",
release_notes=None),
needs_online=True), target_information)
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
check=populated_check,
releaseNotes=release_notes)
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
release_notes = None
if target_information and target_information["remote"] and target_information["remote"][
"value"]:
if "release_notes" in populated_check and populated_check["release_notes"]:
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION,
local_name=local_name,
local_value=local_value),
releaseNotes=release_notes,
online=target_online,
error=target_error)
if self._version_cache_dirty:
self._save_version_cache()
self._get_versions_data = information, update_available, update_possible
self._get_versions_data_ready.set()
finally:
self._get_versions_mutex.release()
else: # something's already in progress, let's wait for it to complete and use its result
self._get_versions_data_ready.wait()
information, update_available, update_possible = self._get_versions_data
if self._version_cache_dirty:
self._save_version_cache()
return information, update_available, update_possible
def _get_check_hash(self, check):
@@ -652,36 +700,50 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash.update(dict_to_sorted_repr(check))
return hash.hexdigest()
def _get_current_version(self, target, check, force=False):
def _get_current_version(self, target, check, force=False, online=None):
"""
Determines the current version information for one target based on its check configuration.
"""
current_hash = self._get_check_hash(check)
if online is None:
online = self._connectivity_checker.online
if target in self._version_cache and not force:
data = self._version_cache[target]
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
if data["hash"] == current_hash \
and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"] \
and data.get("online", None) == online:
# we also check that timestamp < now to not get confused too much by clock changes
return data["information"], data["available"], data["possible"]
return data["information"], data["available"], data["possible"], data["online"], data.get("error", None)
information = dict()
update_available = False
error = None
try:
version_checker = self._get_version_checker(target, check)
information, is_current = version_checker.get_latest(target, check)
information, is_current = version_checker.get_latest(target, check, online=online)
if information is not None and not is_current:
update_available = True
except exceptions.CannotCheckOffline:
update_possible = False
information["needs_online"] = True
except exceptions.UnknownCheckType:
self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
update_possible = False
error = "unknown_check"
except exceptions.NetworkError:
self._logger.warn("Could not check %s for updates due to a network error" % target)
update_possible = False
error = "network"
except:
self._logger.exception("Could not check %s for updates" % target)
update_possible = False
error = "unknown"
else:
try:
updater = self._get_updater(target, check)
update_possible = updater.can_perform_update(target, check)
update_possible = updater.can_perform_update(target, check, online=online)
except:
update_possible = False
@@ -689,9 +751,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash=current_hash,
information=information,
available=update_available,
possible=update_possible)
possible=update_possible,
online=online,
error=error)
self._version_cache_dirty = True
return information, update_available, update_possible
return information, update_available, update_possible, online, error
def perform_updates(self, check_targets=None, force=False):
"""
@@ -803,7 +867,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._send_client_message("success", dict(results=target_results))
def _perform_update(self, target, check, force):
information, update_available, update_possible = self._get_current_version(target, check)
online = self._connectivity_checker.online
information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online)
if not update_available and not force:
return False, None
@@ -826,7 +892,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if updater is None:
raise exceptions.UnknownUpdateType()
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log)
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online)
target_result = ("success", update_result)
self._logger.info("Update of %s to %s successful!" % (target, target_version))
@@ -835,6 +901,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
return False, None
except exceptions.CannotUpdateOffline:
self._logger.warn("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target)
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection"))
except Exception as e:
self._logger.exception("Update of %s can not be performed" % target)
if not "ignorable" in populated_check or not populated_check["ignorable"]:
+31 -9
View File
@@ -9,12 +9,14 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
import sys
import requests.exceptions
import octoprint_client as client
from octoprint.cli.client import create_client, client_options
@click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
@click.option("--only-new", is_flag=True, help="Only show entries with updates available")
@client_options
@click.argument("targets", nargs=-1)
def check_command(force, targets):
def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
"""
Check for updates.
@@ -37,7 +39,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
if targets:
params["check"] = ",".join(targets)
client.init_client(cli_group.settings)
client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
@@ -58,10 +68,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
status_text = "Update available"
else:
status_text = "Update available (manual)"
line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text)
elif only_new:
continue
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
key,
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text)
if key == "octoprint":
octoprint_line = line
else:
@@ -83,8 +98,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
@click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date")
@client_options
@click.argument("targets", nargs=-1)
def update_command(force, targets):
def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets):
"""
Apply updates.
@@ -108,7 +124,13 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
if targets:
data["check"] = targets
client.init_client(cli_group.settings)
client = create_client(apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
flags = dict(
waiting_for_restart=False,
@@ -18,6 +18,20 @@ class UnknownUpdateType(Exception):
class UnknownCheckType(Exception):
pass
class NetworkError(Exception):
def __init__(self, message=None, cause=None):
Exception.__init__(self)
self.message = message
self.cause = cause
def __str__(self):
if self.message is not None:
return self.message
elif self.cause is not None:
return "NetworkError caused by {}".format(self.cause)
else:
return "NetworkError"
class UpdateError(Exception):
def __init__(self, message, data):
self.message = message
@@ -35,3 +49,8 @@ class RestartFailed(Exception):
class ConfigurationInvalid(Exception):
pass
class CannotCheckOffline(Exception):
pass
class CannotUpdateOffline(Exception):
pass
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -417,6 +417,42 @@ $(function() {
});
};
self.iconTitleForEntry = function(data) {
if (data.updatePossible) {
return "";
} else if (!data.online && data.information && data.information.needs_online) {
return gettext("No internet connection");
} else if (data.error) {
return self.errorTextForEntry(data);
} else {
return gettext("Update not possible");
}
};
self.errorTextForEntry = function(data) {
if (!data.error) {
return "";
}
switch (data.error) {
case "unknown_check": {
return gettext("Unknown update check, configuration ok?");
}
case "needs_online": {
return gettext("Cannot check for update, need online connection");
}
case "network": {
return gettext("Network error while checking for update");
}
case "unknown": {
return gettext("Unknown error while checking for update, please check the logs");
}
default: {
return "";
}
}
};
self._markNotificationAsSeen = function(data) {
if (!Modernizr.localstorage)
return false;
@@ -607,6 +643,11 @@ $(function() {
return true;
};
self.onEventConnectivityChanged = function(payload) {
if (!payload || !payload.new) return;
self.performCheck();
};
self.onDataUpdaterReconnect = function() {
if (self.waitingForRestart) {
self.waitingForRestart = false;
@@ -2,6 +2,12 @@ td.settings_plugin_softwareupdate_column_update {
width: 16px;
}
td.settings_plugin_softwareupdate_column_information {
.line {
display: block;
}
}
#settings_plugin_softwareupdate_workingdialog_output {
font-size: 0.8em;
@@ -29,11 +29,12 @@
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small class="muted">
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
</small>
</td>
</tr>
@@ -18,9 +18,9 @@ console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pi
_pip_callers = dict()
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
def can_perform_update(target, check):
def can_perform_update(target, check, online=True):
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
return "pip" in check and pip_caller is not None and pip_caller.available
return "pip" in check and pip_caller is not None and pip_caller.available and (online or check.get("offline", False))
def _get_pip_caller(command=None):
key = command
@@ -35,11 +35,14 @@ def _get_pip_caller(command=None):
return _pip_callers[key]
def perform_update(target, check, target_version, log_cb=None):
def perform_update(target, check, target_version, log_cb=None, online=True):
pip_command = None
if "pip_command" in check:
pip_command = check["pip_command"]
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
pip_caller = _get_pip_caller(command=pip_command)
if pip_caller is None:
raise exceptions.UpdateError("Can't run pip", None)
@@ -6,9 +6,24 @@ __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"
def can_perform_update(target, check):
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update")
def can_perform_update(target, check, online=True):
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update") and (online or check.get("offline", False))
def perform_update(target, check, target_version, log_cb=None):
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
def perform_update(target, check, target_version, log_cb=None, online=True):
from ..exceptions import CannotUpdateOffline
if not online and not check("offline", False):
raise CannotUpdateOffline()
try:
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb, online=online)
except:
import inspect
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
if "online" not in args:
# old python_updater footprint, simply leave out the online parameter
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
# some other error, raise again
raise
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import sys
import logging
from ..exceptions import ConfigurationInvalid, UpdateError
from ..exceptions import ConfigurationInvalid, UpdateError, CannotUpdateOffline
from octoprint.util.commandline import CommandlineCaller, CommandlineError
@@ -36,7 +36,7 @@ def _get_caller(log_cb=None):
return caller
def can_perform_update(target, check):
def can_perform_update(target, check, online=True):
import os
script_configured = bool("update_script" in check and check["update_script"])
@@ -47,12 +47,15 @@ def can_perform_update(target, check):
folder = check["checkout_folder"]
folder_configured = bool(folder and os.path.isdir(folder))
return script_configured and folder_configured
return script_configured and folder_configured and (online or check.get("offline", False))
def perform_update(target, check, target_version, log_cb=None):
def perform_update(target, check, target_version, log_cb=None, online=True):
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
if not online and not check("offline", False):
raise CannotUpdateOffline()
if not can_perform_update(target, check):
raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target)
@@ -14,12 +14,18 @@ logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitb
def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
from ..exceptions import NetworkError
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
headers = {}
if api_user is not None and api_password is not None:
auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))
headers["authorization"] = "Basic {}".format(auth_value)
r = requests.get(url, headers=headers)
try:
r = requests.get(url, headers=headers, timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
if not r.status_code == requests.codes.ok:
return None
@@ -31,7 +37,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
return reference["hash"]
def get_latest(target, check):
def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
if "user" not in check or "repo" not in check:
@@ -46,12 +52,18 @@ def get_latest(target, check):
current = check.get("current")
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
information = dict(
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
remote=dict(name="?", value="?"),
needs_online=not check.get("offline", False)
)
if not online and information["needs_online"]:
return information, True
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
information["remote"] = dict(name=remote_name, value=remote_commit)
is_current = (current is not None and current == remote_commit) or remote_commit is None
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
@@ -8,14 +8,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
from ..exceptions import ConfigurationInvalid
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
from ..util import execute
def get_latest(target, check):
def get_latest(target, check, online=True):
command = check.get("command")
if command is None:
raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target))
if not online and not check.get("offline", False):
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
# We expect command line check commands to
@@ -47,38 +47,40 @@ def _git(args, cwd, hide_stderr=False):
return p.returncode, stdout
def get_latest(target, check):
def get_latest(target, check, online=True):
checkout_folder = check.get("checkout_folder")
if checkout_folder is None:
raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target))
returncode, _ = _git(["fetch"], checkout_folder)
if returncode != 0:
return None, True
returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder)
if returncode != 0:
return None, True
information = dict(
local=dict(name="Commit %s" % local_commit, value=local_commit),
remote=dict(name="?", value="?"),
needs_online=not check.get("offline", False)
)
if not online and information["needs_online"]:
return information, True
returncode, _ = _git(["fetch"], checkout_folder)
if returncode != 0:
return information, True
returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder)
if returncode != 0:
return None, True
return information, True
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0:
return None, True
return information, True
if local_commit == remote_commit or remote_commit == base:
information = dict(
local=dict(name="Commit %s" % local_commit, value=local_commit),
remote=dict(name="Commit %s" % local_commit, value=local_commit)
)
information["remote"] = dict(name="Commit %s" % local_commit, value=local_commit)
is_current = True
else:
information = dict(
local=dict(name="Commit %s" % local_commit, value=local_commit),
remote=dict(name="Commit %s" % remote_commit, value=remote_commit)
)
information["remote"] = dict(name="Commit %s" % remote_commit, value=remote_commit)
is_current = local_commit == remote_commit
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
@@ -13,7 +13,12 @@ BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{br
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
def _get_latest_commit(user, repo, branch):
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30)
from ..exceptions import NetworkError
try:
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -28,7 +33,7 @@ def _get_latest_commit(user, repo, branch):
return reference["object"]["sha"]
def get_latest(target, check):
def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
user = check.get("user")
@@ -43,12 +48,16 @@ def get_latest(target, check):
current = check.get("current")
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
information = dict(local=dict(name="Commit {commit}".format(commit=current if current is not None else "?"), value=current),
remote=dict(name="?", value="?"),
needs_online=not check.get("offline", False))
if not online and information["needs_online"]:
return information, True
information = dict(
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
)
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
information["remote"] = dict(name=remote_name, value=remote_commit)
is_current = (current is not None and current == remote_commit) or remote_commit is None
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
@@ -96,8 +96,14 @@ def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
commitish=None,
force_base=True):
from ..exceptions import NetworkError
nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
try:
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -258,7 +264,7 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
return True
def get_latest(target, check, custom_compare=None):
def get_latest(target, check, custom_compare=None, online=True):
from ..exceptions import ConfigurationInvalid
user = check.get("user", None)
@@ -267,6 +273,14 @@ def get_latest(target, check, custom_compare=None):
if user is None or repo is None or current is None:
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target))
information =dict(
local=dict(name=current, value=current),
remote=dict(name="?", value="?", release_notes=None),
needs_online=not check.get("offline", False)
)
if not online and information["needs_online"]:
return information, True
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
@@ -290,10 +304,13 @@ def get_latest(target, check, custom_compare=None):
commitish=commitish,
force_base=force_base)
information =dict(
local=dict(name=current, value=current),
remote=dict(name=remote_name, value=remote_tag, release_notes=release_notes)
)
if remote_name is None:
if remote_tag is not None:
remote_name = remote_tag
else:
remote_name = "-"
information["remote"] = dict(name=remote_name, value=remote_tag, release_notes=release_notes)
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
@@ -5,11 +5,24 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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"
from ..exceptions import ConfigurationInvalid
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
def get_latest(target, check, full_data=False):
def get_latest(target, check, full_data=False, online=True):
python_checker = check.get("python_checker")
if python_checker is None or not hasattr(python_checker, "get_latest"):
raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target))
return check["python_checker"].get_latest(target, check, full_data=full_data)
if not online and not check.get("offline", False):
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
try:
return check["python_checker"].get_latest(target, check, full_data=full_data, online=online)
except:
import inspect
args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest)
if "online" not in args:
# old python_checker footprint, simply leave out the online parameter
return check["python_checker"].get_latest(target, check, full_data=full_data)
# some other error, raise again
raise
+87 -5
View File
@@ -7,9 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import uuid
from sockjs.tornado import SockJSRouter
from flask import Flask, g, request, session, Blueprint, Request, Response
from flask_login import LoginManager, current_user
from flask_principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
from flask_login import LoginManager, current_user, session_protected, user_logged_out
from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
from flask_babel import Babel, gettext, ngettext
from flask_assets import Environment, Bundle
from babel import Locale
@@ -49,6 +49,7 @@ pluginManager = None
appSessionManager = None
pluginLifecycleManager = None
preemptiveCache = None
connectivityChecker = None
principals = Principal(app)
admin_permission = Permission(RoleNeed("admin"))
@@ -96,6 +97,29 @@ def on_identity_loaded(sender, identity):
if user.is_admin:
identity.provides.add(RoleNeed("admin"))
def _clear_identity(sender):
# Remove session keys set by Flask-Principal
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
if key in session:
del session[key]
# switch to anonymous identity
identity_changed.send(sender, identity=AnonymousIdentity())
@session_protected.connect_via(app)
def on_session_protected(sender):
# session was protected, that means the user is no more and we need to clear our identity
_clear_identity(sender)
@user_logged_out.connect_via(app)
def on_user_logged_out(sender, user=None):
# user was logged out, clear identity
_clear_identity(sender)
def load_user(id):
if id == "_api":
return users.ApiUser()
@@ -160,6 +184,7 @@ class Server(object):
global appSessionManager
global pluginLifecycleManager
global preemptiveCache
global connectivityChecker
global debug
global safe_mode
@@ -204,6 +229,40 @@ class Server(object):
pluginLifecycleManager = LifecycleManager(pluginManager)
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml"))
# start regular check if we are connected to the internet
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
def on_connectivity_change(old_value, new_value):
eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
connectivityChecker = octoprint.util.ConnectivityChecker(connectivityInterval,
connectivityHost,
port=connectivityPort,
enabled=connectivityEnabled,
on_change=on_connectivity_change)
def on_settings_update(*args, **kwargs):
# make sure our connectivity checker runs with the latest settings
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
if connectivityChecker.enabled != connectivityEnabled \
or connectivityChecker.interval != connectivityInterval \
or connectivityChecker.host != connectivityHost \
or connectivityChecker.port != connectivityPort:
connectivityChecker.enabled = connectivityEnabled
connectivityChecker.interval = connectivityInterval
connectivityChecker.host = connectivityHost
connectivityChecker.port = connectivityPort
connectivityChecker.check_immediately()
eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)
# setup access control
userManagerName = self._settings.get(["accessControl", "userManager"])
try:
@@ -224,10 +283,33 @@ class Server(object):
file_manager=fileManager,
app_session_manager=appSessionManager,
plugin_lifecycle_manager=pluginLifecycleManager,
user_manager=userManager,
preemptive_cache=preemptiveCache
preemptive_cache=preemptiveCache,
connectivity_checker=connectivityChecker
)
# create user manager instance
user_manager_factories = pluginManager.get_hooks("octoprint.users.factory")
for name, factory in user_manager_factories.items():
try:
userManager = factory(components, self._settings)
if userManager is not None:
self._logger.debug("Created user manager instance from factory {}".format(name))
break
except:
self._logger.exception("Error while creating user manager instance from factory {}".format(name))
else:
name = self._settings.get(["accessControl", "userManager"])
try:
clazz = octoprint.util.get_class(name)
userManager = clazz()
except:
self._logger.exception(
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name))
userManager = octoprint.users.FilebasedUserManager()
finally:
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
components.update(dict(user_manager=userManager))
# create printer instance
printer_factories = pluginManager.get_hooks("octoprint.printer.factory")
for name, factory in printer_factories.items():
+5 -6
View File
@@ -225,22 +225,21 @@ def login():
@api.route("/logout", methods=["POST"])
@restricted_access
def logout():
# Remove session keys set by Flask-Principal
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
if key in session:
del session[key]
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
# logout from user manager...
_logout(current_user)
# ... and from flask login (and principal)
logout_user()
return NO_CONTENT
def _logout(user):
if "usersession.id" in session:
del session["usersession.id"]
octoprint.server.userManager.logout_user(user)
@api.route("/util/test", methods=["POST"])
@restricted_access
@admin_permission.require(403)
+20
View File
@@ -154,6 +154,8 @@ def getSettings():
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
@@ -200,6 +202,12 @@ def getSettings():
"diskspace": {
"warning": s.getInt(["server", "diskspace", "warning"]),
"critical": s.getInt(["server", "diskspace", "critical"])
},
"onlineCheck": {
"enabled": s.getBoolean(["server", "onlineCheck", "enabled"]),
"interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60),
"host": s.get(["server", "onlineCheck", "host"]),
"port": s.getInt(["server", "onlineCheck", "port"])
}
}
}
@@ -368,6 +376,8 @@ def _saveSettings(data):
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
if "supportResendsWithoutOk" in data["serial"]: s.setBoolean(["serial", "supportResendsWithoutOk"], data["serial"]["supportResendsWithoutOk"])
if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"])
if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"])
if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"])
if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"])
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
@@ -418,6 +428,16 @@ def _saveSettings(data):
if "diskspace" in data["server"]:
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
if "onlineCheck" in data["server"]:
if "enabled" in data["server"]["onlineCheck"]: s.setBoolean(["server", "onlineCheck", "enabled"], data["server"]["onlineCheck"]["enabled"])
if "interval" in data["server"]["onlineCheck"]:
try:
interval = int(data["server"]["onlineCheck"]["interval"])
s.setInt(["server", "onlineCheck", "interval"], interval*60)
except ValueError:
pass
if "host" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "host"], data["server"]["onlineCheck"]["host"])
if "port" in data["server"]["onlineCheck"]: s.setInt(["server", "onlineCheck", "port"], data["server"]["onlineCheck"]["port"])
if "plugins" in data:
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
+46 -16
View File
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import collections
import logging
import sarge
import threading
from flask import request, make_response, jsonify, url_for
from flask_babel import gettext
@@ -16,6 +17,7 @@ from octoprint.settings import settings as s
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access, get_remote_address
from octoprint.logging import prefix_multilines
@api.route("/system", methods=["POST"])
@@ -74,38 +76,59 @@ def executeSystemCommand(source, command):
do_async = command_spec.get("async", False)
do_ignore = command_spec.get("ignore", False)
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
debug = command_spec.get("debug", False)
if logger.isEnabledFor(logging.DEBUG) or debug:
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
else:
logger.info("Performing command for {}:{}".format(source, command))
try:
if "before" in command_spec and callable(command_spec["before"]):
command_spec["before"]()
except Exception as e:
if not do_ignore:
error = "Command \"before\" failed: {}".format(str(e))
error = "Command \"before\" for {}:{} failed: {}".format(source, command, str(e))
logger.warn(error)
return make_response(error, 500)
try:
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(command_spec["command"],
stdout=sarge.Capture(),
stderr=sarge.Capture(),
shell=True,
async=do_async)
if not do_async:
def execute():
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(command_spec["command"],
stdout=sarge.Capture(),
stderr=sarge.Capture(),
shell=True)
if not do_ignore and p.returncode != 0:
returncode = p.returncode
stdout_text = p.stdout.text
stderr_text = p.stderr.text
error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(returncode, stdout_text, stderr_text)
logger.warn(error)
return make_response(error, 500)
error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(source, command,
returncode,
stdout_text,
stderr_text)
logger.warn(prefix_multilines(error, prefix="! "))
if not do_async:
raise CommandFailed(error)
if do_async:
thread = threading.Thread(target=execute)
thread.daemon = True
thread.start()
else:
try:
execute()
except CommandFailed as exc:
return make_response(exc.error, 500)
except Exception as e:
if not do_ignore:
error = "Command failed: {}".format(str(e))
error = "Command for {}:{} failed: {}".format(source, command, str(e))
logger.warn(error)
return make_response(error, 500)
@@ -164,7 +187,10 @@ def _get_core_command_specs():
for action, spec in commands.items():
if not spec["command"]:
continue
spec.update(dict(action=action, source="core", async=True, ignore=True))
spec.update(dict(action=action,
source="core",
async=True,
debug=True))
available_commands[action] = spec
return available_commands
@@ -202,3 +228,7 @@ def _get_custom_command_spec(action):
return available_actions[action]
class CommandFailed(Exception):
def __init__(self, error):
self.error = error
+8
View File
@@ -112,6 +112,8 @@ default_settings = {
"ignoreErrorsFromFirmware": False,
"logResends": True,
"supportResendsWithoutOk": False,
"logPositionOnPause": True,
"logPositionOnCancel": True,
# command specific flags
"triggerOkForM29": True
@@ -146,6 +148,12 @@ default_settings = {
"systemRestartCommand": None,
"serverRestartCommand": None
},
"onlineCheck": {
"enabled": None,
"interval": 15 * 60, # 15 min
"host": "8.8.8.8",
"port": 53
},
"diskspace": {
"warning": 500 * 1024 * 1024, # 500 MB
"critical": 200 * 1024 * 1024, # 200 MB
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -325,6 +325,11 @@ var doParse = function () {
extrude = false;
line = line.split(/[\(;]/)[0];
if (!line || line.trim() === "") {
// empty line, skip entirely
continue;
}
var addToModel = false;
var move = false;
@@ -545,7 +550,7 @@ var doParse = function () {
}
if (typeof(z) !== 'undefined' && z !== prevZ) {
if (z_heights[z]) {
if (z_heights[z] !== undefined) {
layer = z_heights[z];
} else {
layer = model.length;
@@ -44,15 +44,12 @@ GCODE.gCodeReader = (function(){
var prepareGCode = function(totalSize){
if(!lines)return;
gcode = [];
var i, tmp, byteCount;
var i, byteCount;
byteCount = 0;
for(i=0;i<lines.length;i++){
byteCount += lines[i].length + 1; // line length + \n
tmp = lines[i].indexOf(";");
if(tmp > 1 || tmp === -1) {
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
}
byteCount += lines[i].length + 1; // line length + line ending
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
}
lines = [];
};
@@ -146,7 +143,7 @@ GCODE.gCodeReader = (function(){
this.clear();
var totalSize = reader.target.result.length;
lines = reader.target.result.split(/\n/);
lines = reader.target.result.split(/[\r\n]/g);
reader.target.result = null;
prepareGCode(totalSize);
@@ -225,14 +225,16 @@ $(function() {
var result = [];
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
for (var key in data.filament) {
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue;
var keys = _.keys(data.filament);
keys.sort();
_.each(keys, function(key) {
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) return;
result.push({
name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)),
data: ko.observable(data.filament[key])
});
}
});
}
self.filament(result);
};
@@ -173,6 +173,8 @@ $(function() {
self.serial_disconnectOnErrors = ko.observable(undefined);
self.serial_triggerOkForM29 = ko.observable(undefined);
self.serial_supportResendsWithoutOk = ko.observable(undefined);
self.serial_logPositionOnPause = ko.observable(undefined);
self.serial_logPositionOnCancel = ko.observable(undefined);
self.serial_maxTimeoutsIdle = ko.observable(undefined);
self.serial_maxTimeoutsPrinting = ko.observable(undefined);
self.serial_maxTimeoutsLong = ko.observable(undefined);
@@ -211,6 +213,11 @@ $(function() {
self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning);
self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical);
self.server_onlineCheck_enabled = ko.observable();
self.server_onlineCheck_interval = ko.observable();
self.server_onlineCheck_host = ko.observable();
self.server_onlineCheck_port = ko.observable();
self.settings = undefined;
self.lastReceivedSettings = undefined;
@@ -47,7 +47,18 @@ $(function() {
var callback = function() {
OctoPrint.system.executeCommand(commandSpec.actionSource, commandSpec.action)
.done(function() {
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: commandSpec.name}), type: "success"});
var text;
if (commandSpec.async) {
text = gettext("The command \"%(command)s\" executed successfully");
} else {
text = gettext("The command \"%(command)s\" was triggered asychronously");
}
new PNotify({
title: "Success",
text: _.sprintf(text, {command: commandSpec.name}),
type: "success"
});
deferred.resolve(["success", arguments]);
})
.fail(function(jqXHR, textStatus, errorThrown) {
@@ -272,6 +272,16 @@ $(function() {
}
};
self.gotoTerminalCommand = function() {
// skip if user highlights text.
var sel = getSelection().toString();
if (sel) {
return;
}
$("#terminal-command").focus();
};
self.toggleAutoscroll = function() {
self.autoscrollEnabled(!self.autoscrollEnabled());
};
@@ -192,9 +192,25 @@ $(function() {
self.onSettingsPreventRefresh = function() {
if (!self.finishing && self.isDialogActive()
&& hasDataChanged(self.settingsViewModel.getLocalData(), self.settingsViewModel.lastReceivedSettings)) {
var preventSettingsRefreshDialog = false;
callViewModels(allViewModels, "onWizardPreventSettingsRefreshDialog", function(method) {
// if any of our methods returns that it wants to prevent the dialog
// we'll need to set preventSettingsRefreshDialog to true
//
// order is important here - the method call needs to happen
// first, or it won't happen after the flag has been
// set once due to the || making further evaluation unnecessary
// then
preventSettingsRefreshDialog = (method() === true) || preventSettingsRefreshDialog;
});
// we have local changes, show update dialog
self.settingsViewModel.settingsUpdatedDialog.modal("show");
return true;
if (preventSettingsRefreshDialog) {
return false;
} else {
self.settingsViewModel.settingsUpdatedDialog.modal("show");
return true;
}
}
return false;
+34 -8
View File
@@ -875,10 +875,6 @@ ul.dropdown-menu li a {
margin-bottom: 30px;
}
#terminal-sendpanel {
text-align: right;
}
}
#settings_dialog {
@@ -1129,10 +1125,6 @@ textarea.block {
display: inline-block !important;
}
a.dropdown-sd {
padding-top: 4px !important;
}
.center {
float: none;
margin-left: auto;
@@ -1295,6 +1287,40 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
}
}
// block level inputs with add-ons
//
// LESS based on CSS from https://stackoverflow.com/a/17466199/2028598
//
// Note: do not use <button> for attached buttons, use <a class="btn add-on">...</a>
// instead
.input-append,
.input-prepend {
&.input-block-level {
display: table;
.add-on {
display: table-cell;
width: 1%; /* remove this if you want default bootstrap button width */
}
> input {
box-sizing: border-box; /* use bootstrap mixin or include vendor variants */
display: table; /* table-cell is not working well in Chrome for small widths */
min-height: inherit;
width: 100%;
}
}
}
.input-append.input-block-level > input {
border-right: 0;
}
.input-prepend.input-block-level > input {
border-left: 0;
}
.btn-input-dec,
.btn-input-enc {
//font-size: 80%;
@@ -151,6 +151,18 @@
<input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-supportResendsWithoutOk"> {{ _('Simulate an additional <code>ok</code> for resend requests') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_logPositionOnPause" id="settings-logPositionOnPause"> {{ _('Log position on pause') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('If you disabled this, the <code>pause_position</code> placeholders in your pause/resume GCODE scripts will stay unpopulated! However, pausing speed might improve slightly.') }}</span>
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_logPositionOnCancel" id="settings-logPositionOnCancel"> {{ _('Log position on cancel') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('If you disabled this, the <code>cancel_position</code> placeholders in your cancel GCODE script and the corresponding data in the print recovery data will stay unpopulated! However, cancelling speed might improve slightly.') }}</span>
</label>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while idle. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
<div class="controls">
@@ -4,4 +4,10 @@
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
<h3>{{ _('Connectivity check') }}</h3>
{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheck.jinja2" %}
</form>
@@ -5,7 +5,7 @@
</div>
<div class="modal-body">
<p data-bind="text: changingOffset.description"></p>
<form class="form-horizontal">
<form class="form-horizontal" data-bind="submit: confirmChangeOffset">
<div class="control-group">
<label class="control-label">{{ _('Current Offset') }}</label>
<div class="controls">
@@ -29,6 +29,6 @@
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="javascript:void(0)" class="btn btn-primary" data-bind="click: confirmChangeOffset">{{ _('Submit') }}</a>
<a href="javascript:void(0)" class="btn btn-primary" data-bind="click: confirmChangeOffset">{{ _('Save') }}</a>
</div>
</div>
+1 -1
View File
@@ -5,7 +5,7 @@
<div id="login_dropdown_loggedout" style="padding: 15px" class="dropdown-menu" data-bind="css: {hide: loginState.loggedIn(), 'dropdown-menu': !loginState.loggedIn()}">
<form id="loginForm" data-bind="event: {'submit': loginState.prepareLogin }">
<label for="login_user">{{ _('Username') }}</label>
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none">
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none" autocorrect="off">
<label for="login_pass">{{ _('Password') }}</label>
<input type="password" id="login_pass" name="password" data-bind="valueWithInit: loginState.loginPass" placeholder="{{ _('Password') }}">
<label class="checkbox">
@@ -35,7 +35,7 @@
{% if enableSdSupport %}
<div class="sd-trigger accordion-heading-button btn-group">
<a class="dropdown-toggle dropdown-sd" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" title="{{ _('SD Card operations') }}">
<span class="icon-sd-black-14"></span>
</a>
<ul class="dropdown-menu">
@@ -0,0 +1,18 @@
{% include "snippets/settings/server/serverOnlineCheckEnabled.jinja2" %}
<div data-bind="visible: server_onlineCheck_enabled">
<div class="control-group">
<div class="controls">
<p>{% trans %}
Define a check interval, a host and a port to check against. If you don't know what to set here, the
default values (using Google's DNS server) should work. If you have concerns about using
that, define the IP and port of a different online server that you trust and that has a high
availability.
{% endtrans %}</p>
</div>
</div>
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
</div>
@@ -0,0 +1,5 @@
<p>{% trans %}
If the connectivity check is enabled, OctoPrint will regularly check if it's connected to the internet.
This is <strong>useful to prevent resource intensive operations</strong> (such as checking for updates) if it's already
clear that they won't succeed anyhow.
{% endtrans %}</p>
@@ -0,0 +1,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: server_onlineCheck_enabled" id="settings-serverOnlineCheckEnabled"> {{ _('Enable regular connectivity check') }}
</label>
</div>
</div>
@@ -0,0 +1,6 @@
<div class="control-group" title="{{ _('Host against which to check for internet connectivity') }}">
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Host IP') }}</label>
<div class="controls">
<input type="text" class="input-small" data-bind="value: server_onlineCheck_host" id="settings-serverOnlineCheckHost">
</div>
</div>
@@ -0,0 +1,9 @@
<div class="control-group" title="{{ _('Interval in which to check for internet connectivity') }}">
<label class="control-label" for="settings-serverOnlineCheckInterval">{{ _('Check interval') }}</label>
<div class="controls">
<span class="input-append">
<input type="number" min="1" step="1" class="input-mini" data-bind="value: server_onlineCheck_interval" id="settings-serverOnlineCheckInterval">
<span class="add-on">min</span>
</span>
</div>
</div>
@@ -0,0 +1,6 @@
<div class="control-group" title="{{ _('Port against which to check for internet connectivity') }}">
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Port') }}</label>
<div class="controls">
<input type="number" min="1" max="65535" step="1" class="input-small" data-bind="value: server_onlineCheck_port" id="settings-serverOnlineCheckPort">
</div>
</div>
+1 -1
View File
@@ -130,7 +130,7 @@
</script>
<script type="text/html" id="customControls_containerTemplate_collapsable">
<div class="custom_section">
<h1 class="fa" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.custom_section', container: '> div' }"><i class="fa" data-bind="css: {'fa-caret-down': !collapsed, 'fa-caret-right': collapsed}"></i> <span data-bind="text: name"></span></h1>
<h1 data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.custom_section', container: '> div' }"><i class="fa" data-bind="css: {'fa-caret-down': !collapsed, 'fa-caret-right': collapsed}"></i> <span data-bind="text: name"></span></h1>
<!-- ko template: { name: 'customControls_containerTemplate', data: $data } --><!-- /ko -->
</div>
</script>
+8 -9
View File
@@ -1,9 +1,15 @@
<div class="terminal">
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality()"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
<pre id="terminal-output-lowfi" style="display: none" class="pre-scrollable" data-bind="text: plainLogOutput, visible: !fancyFunctionality()"></pre>
<div id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.isUser">
<div class="input-block-level input-append">
<input type="text" id="terminal-command" data-bind="value: command, event: { keyup: function(d,e) { return handleKeyUp(e); }, keydown: function(d,e) { return handleKeyDown(e); } }, enable: isOperational() && loginState.isUser()" autocomplete="off">
<a class="btn add-on" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">{{ _('Send') }}</a>
</div>
</div>
<small class="pull-left" data-bind="visible: fancyFunctionality()"><button class="btn btn-mini" data-bind="click: toggleAutoscroll, css: {active: autoscrollEnabled}">{{ _('Autoscroll') }}</button> <span data-bind="text: lineCount, visible: enableFancyFunctionality"></span></small>
<small class="pull-right" data-bind="visible: fancyFunctionality()"><a href="#" data-bind="click: scrollToEnd">{{ _("Scroll to end") }}</a>&nbsp;|&nbsp;<a href="#" data-bind="click: selectAll">{{ _("Select all") }}</a></small>
<small class="pull-left muted" data-bind="visible: !fancyFunctionality()" style="display: none">{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}</small>
<small class="pull-left text-warning" data-bind="visible: !fancyFunctionality()" style="display: none">{{ _('For performance reasons only a limited amount of terminal functionality is enabled right now.') }}</small>
</div>
<div class="row-fluid">
@@ -14,13 +20,6 @@
</label>
</div>
</div>
<div class="span6" id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.isUser">
<div class="input-append">
<input type="text" id="terminal-command" data-bind="value: command, event: { keyup: function(d,e) { return handleKeyUp(e); }, keydown: function(d,e) { return handleKeyDown(e); } }, enable: isOperational() && loginState.isUser()" autocomplete="off">
<button class="btn" type="button" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">{{ _('Send') }}</button>
</div>
<small class="muted">{{ _('Hint: Use the arrow up/down keys to recall commands sent previously') }}</small>
</div>
</div>
<div>
@@ -116,7 +116,7 @@
</div>
<div data-bind="visible: unrenderedListHelper.allSize">
<div><small><a href="javascript:void(0)" class="fa muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Unrendered Timelapses') }}</a></small></div>
<div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Unrendered Timelapses') }}</a></small></div>
<div class="hide">
<div class="pull-left">
<div class="btn-group">
File diff suppressed because it is too large. Load diff
+157 -7
View File
@@ -735,22 +735,47 @@ def interface_addresses(family=None):
if not ifaddress["addr"].startswith("169.254."):
yield ifaddress["addr"]
def address_for_client(host, port):
def address_for_client(host, port, timeout=3.05):
"""
Determines the address of the network interface on this host needed to connect to the indicated client host and port.
"""
import socket
for address in interface_addresses():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((address, 0))
sock.connect((host, port))
return address
if server_reachable(host, port, timeout=timeout, proto="udp", source=address):
return address
except:
continue
def server_reachable(host, port, timeout=3.05, proto="tcp", source=None):
"""
Checks if a server is reachable
Args:
host (str): host to check against
port (int): port to check against
timeout (float): timeout for check
proto (str): ``tcp`` or ``udp``
source (str): optional, socket used for check will be bound against this address if provided
Returns:
boolean: True if a connection to the server could be opened, False otherwise
"""
import socket
if proto not in ("tcp", "udp"):
raise ValueError("proto must be either 'tcp' or 'udp'")
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM)
sock.settimeout(timeout)
if source is not None:
sock.bind((source, 0))
sock.connect((host, port))
return True
except:
return False
@contextlib.contextmanager
def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
@@ -1132,3 +1157,128 @@ class TypeAlreadyInQueue(Exception):
Exception.__init__(self, *args, **kwargs)
self.type = t
class ConnectivityChecker(object):
"""
Regularly checks for online connectivity.
Tries to open a connection to the provided ``host`` and ``port`` every ``interval``
seconds and sets the ``online`` status accordingly.
"""
def __init__(self, interval, host, port, enabled=True, on_change=None):
self._interval = interval
self._host = host
self._port = port
self._enabled = enabled
self._on_change = on_change
self._logger = logging.getLogger(__name__ + ".connectivity_checker")
# we initialize the online flag to True if we are not enabled (we don't know any better
# but these days it's probably a sane default)
self._online = not self._enabled
self._check_worker = None
self._check_mutex = threading.RLock()
self._run()
@property
def online(self):
"""Current online status, True if online, False if offline."""
with self._check_mutex:
return self._online
@property
def host(self):
"""DNS host to query."""
with self._check_mutex:
return self._host
@host.setter
def host(self, value):
with self._check_mutex:
self._host = value
@property
def port(self):
"""DNS port to query."""
with self._check_mutex:
return self._port
@port.setter
def port(self, value):
with self._check_mutex:
self._port = value
@property
def interval(self):
"""Interval between consecutive automatic checks."""
return self._interval
@interval.setter
def interval(self, value):
self._interval = value
@property
def enabled(self):
"""Whether the check is enabled or not."""
return self._enabled
@enabled.setter
def enabled(self, value):
with self._check_mutex:
old_enabled = self._enabled
self._enabled = value
if not self._enabled:
if self._check_worker is not None:
self._check_worker.cancel()
old_value = self._online
self._online = True
if old_value != self._online:
self._trigger_change(old_value, self._online)
elif self._enabled and not old_enabled:
self._run()
def check_immediately(self):
"""Check immediately and return result."""
with self._check_mutex:
self._perform_check()
return self.online
def _run(self):
from octoprint.util import RepeatedTimer
if not self._enabled:
return
if self._check_worker is not None:
self._check_worker.cancel()
self._check_worker = RepeatedTimer(self._interval, self._perform_check,
run_first=True)
self._check_worker.start()
def _perform_check(self):
if not self._enabled:
return
with self._check_mutex:
self._logger.debug("Checking against {}:{} if we are online...".format(self._host, self._port))
old_value = self._online
self._online = server_reachable(self._host, port=self._port)
if old_value != self._online:
self._trigger_change(old_value, self._online)
def _trigger_change(self, old_value, new_value):
self._logger.info("Connectivity changed from {} to {}".format("online" if old_value else "offline",
"online" if new_value else "offline"))
if callable(self._on_change):
self._on_change(old_value, new_value)
+24 -14
View File
@@ -462,6 +462,9 @@ class MachineCom(object):
self._record_pause_data = False
self._record_cancel_data = False
self._log_position_on_pause = settings().getBoolean(["serial", "logPositionOnPause"])
self._log_position_on_cancel = settings().getBoolean(["serial", "logPositionOnCancel"])
# print job
self._currentFile = None
@@ -945,7 +948,10 @@ class MachineCom(object):
except:
pass
self.sendCommand("M400", on_sent=_on_M400_sent)
if self._log_position_on_cancel:
self.sendCommand("M400", on_sent=_on_M400_sent)
else:
self._cancel_preparation_done()
def _pause_preparation_done(self):
self._callback.on_comm_print_job_paused()
@@ -992,7 +998,10 @@ class MachineCom(object):
self._record_pause_data = True
self.sendCommand("M114")
self.sendCommand("M400", on_sent=_on_M400_sent)
if self._log_position_on_pause:
self.sendCommand("M400", on_sent=_on_M400_sent)
else:
self._pause_preparation_done()
def getSdFiles(self):
return self._sdFiles
@@ -2247,18 +2256,13 @@ class MachineCom(object):
# and now let's fetch the next item from the queue
continue
if len(results) > 1:
with self._sendingLock:
# prepend reversed (so order gets restored)
to_prepend = reversed(results[1:-1])
for m in to_prepend:
try:
self._send_queue.prepend((m[0], None, m[1], on_sent, True), item_type=m[1])
on_sent = None
except TypeAlreadyInQueue:
pass
# we explicitly throw away plugin hook results that try
# to perform command expansion in the sending/sent phase,
# so "results" really should only have more than one entry
# at this point if our core code contains a bug
assert len(results) == 1
# we only actually send the first entry here
# we only use the first (and only!) entry here
command, _, gcode, subcode = results[0]
if command.strip() == "":
@@ -2333,7 +2337,13 @@ class MachineCom(object):
self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals()))
else:
normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, hook_results)
new_results += normalized
# make sure we don't allow multi entry results in anything but the queuing phase
if not phase in ("queuing",) and len(normalized) > 1:
self._logger.error("Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format(**locals()))
new_results.append((command, command_type, gcode, subcode))
else:
new_results += normalized
if not new_results:
# hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
return []
+108 -103
View File
@@ -10,6 +10,7 @@ import sarge
import sys
import logging
import site
import threading
import pkg_resources
@@ -17,6 +18,7 @@ from .commandline import CommandlineCaller, clean_ansi
from octoprint.util import to_unicode
_cache = dict(version=dict(), setup=dict())
_cache_mutex = threading.RLock()
class UnknownPip(Exception):
pass
@@ -173,8 +175,6 @@ class PipCaller(CommandlineCaller):
self._logger.error("This version of pip is known to have bugs that make it incompatible with how it needs to be used by OctoPrint. Please upgrade your pip version.")
return
self._logger.info("Version of pip is {}".format(version_segment))
# Now figure out if pip belongs to a virtual environment and if the
# default installation directory is writable.
#
@@ -194,10 +194,6 @@ class PipCaller(CommandlineCaller):
self._logger.error("Cannot use pip")
return
self._logger.info("pip installs to {}, --user flag needed => {}, virtual env => {}".format(pip_install_dir,
"yes" if pip_user else "no",
"yes" if pip_virtual_env else "no"))
self._command = pip_command
self._version = pip_version
self._version_string = version_segment
@@ -251,122 +247,131 @@ class PipCaller(CommandlineCaller):
if isinstance(pip_command_str, list):
pip_command_str = " ".join(pip_command_str)
if not self.ignore_cache and pip_command_str in _cache["version"]:
self._logger.debug("Using cached pip version information for {}".format(pip_command_str))
return _cache["version"][pip_command_str]
with _cache_mutex:
if not self.ignore_cache and pip_command_str in _cache["version"]:
self._logger.debug("Using cached pip version information for {}".format(pip_command_str))
return _cache["version"][pip_command_str]
sarge_command = self.to_sarge_command(pip_command, "--version")
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
sarge_command = self.to_sarge_command(pip_command, "--version")
p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
if p.returncode != 0:
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
return None, None
if p.returncode != 0:
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
return None, None
output = PipCaller._preprocess(p.stdout.text)
# output should look something like this:
#
# pip <version> from <path> (<python version>)
#
# we'll just split on whitespace and then try to use the second entry
output = PipCaller._preprocess(p.stdout.text)
# output should look something like this:
#
# pip <version> from <path> (<python version>)
#
# we'll just split on whitespace and then try to use the second entry
if not output.startswith("pip"):
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
if not output.startswith("pip"):
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
split_output = map(lambda x: x.strip(), output.split())
if len(split_output) < 2:
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
split_output = map(lambda x: x.strip(), output.split())
if len(split_output) < 2:
self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
version_segment = split_output[1]
version_segment = split_output[1]
try:
pip_version = pkg_resources.parse_version(version_segment)
except:
self._logger.exception("Error while trying to parse version string from pip command")
return None, None
try:
pip_version = pkg_resources.parse_version(version_segment)
except:
self._logger.exception("Error while trying to parse version string from pip command")
return None, None
result = pip_version, version_segment
_cache["version"][pip_command_str] = result
return result
self._logger.info("Version of pip is {}".format(version_segment))
result = pip_version, version_segment
_cache["version"][pip_command_str] = result
return result
def _check_pip_setup(self, pip_command):
pip_command_str = pip_command
if isinstance(pip_command_str, list):
pip_command_str = " ".join(pip_command_str)
if not self.ignore_cache and pip_command_str in _cache["setup"]:
self._logger.debug("Using cached pip setup information for {}".format(pip_command_str))
return _cache["setup"][pip_command_str]
with _cache_mutex:
if not self.ignore_cache and pip_command_str in _cache["setup"]:
self._logger.debug("Using cached pip setup information for {}".format(pip_command_str))
return _cache["setup"][pip_command_str]
# This is horribly ugly and I'm sorry...
#
# While we can figure out the install directory, if that's writable and if a virtual environment
# is active for pip that belongs to our sys.executable python instance by just checking some
# variables, we can't for stuff like third party software we allow to update via the software
# update plugin.
#
# What we do instead for these situations is try to install (and of course uninstall) the
# testballoon dummy package, which collects that information for us. For pip <= 7 we could
# have the testballoon provide us with the info needed through stdout, if pip was called
# with --verbose anything printed to stdout within setup.py would be output. Pip 8 managed
# to break this mechanism. Any (!) output within setup.py appears to be suppressed now, and
# no combination of --log and multiple --verbose or -v arguments could get it to bring the
# output back.
#
# So here's what we do now instead. Our sarge call sets an environment variable
# "TESTBALLOON_OUTPUT" that points to a temporary file. If the testballoon sees that
# variable set, it opens the file and writes to it the output it so far printed on stdout.
# We then open the file and read in the data that way.
#
# Yeah, I'm not happy with that either. But as long as there's no way to otherwise figure
# out for a generic pip command whether OctoPrint can even install anything with that
# and if so how, well, that's how we'll have to do things.
# This is horribly ugly and I'm sorry...
#
# While we can figure out the install directory, if that's writable and if a virtual environment
# is active for pip that belongs to our sys.executable python instance by just checking some
# variables, we can't for stuff like third party software we allow to update via the software
# update plugin.
#
# What we do instead for these situations is try to install (and of course uninstall) the
# testballoon dummy package, which collects that information for us. For pip <= 7 we could
# have the testballoon provide us with the info needed through stdout, if pip was called
# with --verbose anything printed to stdout within setup.py would be output. Pip 8 managed
# to break this mechanism. Any (!) output within setup.py appears to be suppressed now, and
# no combination of --log and multiple --verbose or -v arguments could get it to bring the
# output back.
#
# So here's what we do now instead. Our sarge call sets an environment variable
# "TESTBALLOON_OUTPUT" that points to a temporary file. If the testballoon sees that
# variable set, it opens the file and writes to it the output it so far printed on stdout.
# We then open the file and read in the data that way.
#
# Yeah, I'm not happy with that either. But as long as there's no way to otherwise figure
# out for a generic pip command whether OctoPrint can even install anything with that
# and if so how, well, that's how we'll have to do things.
import os
testballoon = os.path.join(os.path.realpath(os.path.dirname(__file__)), "piptestballoon")
import os
testballoon = os.path.join(os.path.realpath(os.path.dirname(__file__)), "piptestballoon")
from octoprint.util import temppath
with temppath() as testballoon_output_file:
sarge_command = self.to_sarge_command(pip_command, "install", ".")
try:
# our testballoon is no real package, so this command will fail - that's ok though,
# we only need the output produced within the pip environment
sarge.run(sarge_command,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
cwd=testballoon,
env=dict(TESTBALLOON_OUTPUT=testballoon_output_file))
except:
self._logger.exception("Error while trying to install testballoon to figure out pip setup")
from octoprint.util import temppath
with temppath() as testballoon_output_file:
sarge_command = self.to_sarge_command(pip_command, "install", ".")
try:
# our testballoon is no real package, so this command will fail - that's ok though,
# we only need the output produced within the pip environment
sarge.run(sarge_command,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
cwd=testballoon,
env=dict(TESTBALLOON_OUTPUT=testballoon_output_file))
except:
self._logger.exception("Error while trying to install testballoon to figure out pip setup")
return False, False, False, None
data = dict()
with open(testballoon_output_file) as f:
for line in f:
key, value = line.split("=", 2)
data[key] = value
install_dir_str = data.get("PIP_INSTALL_DIR", None)
virtual_env_str = data.get("PIP_VIRTUAL_ENV", None)
writable_str = data.get("PIP_WRITABLE", None)
if install_dir_str is not None and virtual_env_str is not None and writable_str is not None:
install_dir = install_dir_str.strip()
virtual_env = virtual_env_str.strip() == "True"
writable = writable_str.strip() == "True"
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
ok = writable or can_use_user_flag
user_flag = not writable and can_use_user_flag
self._logger.info("pip installs to {}, --user flag needed => {}, "
"virtual env => {}".format(install_dir,
"yes" if user_flag else "no",
"yes" if virtual_env else "no"))
# ok, enable user flag, virtual env yes/no, installation dir
result = ok, user_flag, virtual_env, install_dir
_cache["setup"][pip_command_str] = result
return result
else:
self._logger.debug("Could not detect desired output from testballoon install, got this instead: {!r}".format(data))
return False, False, False, None
data = dict()
with open(testballoon_output_file) as f:
for line in f:
key, value = line.split("=", 2)
data[key] = value
install_dir_str = data.get("PIP_INSTALL_DIR", None)
virtual_env_str = data.get("PIP_VIRTUAL_ENV", None)
writable_str = data.get("PIP_WRITABLE", None)
if install_dir_str is not None and virtual_env_str is not None and writable_str is not None:
install_dir = install_dir_str.strip()
virtual_env = virtual_env_str.strip() == "True"
writable = writable_str.strip() == "True"
can_use_user_flag = not virtual_env and site.ENABLE_USER_SITE
# ok, enable user flag, virtual env yes/no, installation dir
result = writable or can_use_user_flag, \
not writable and can_use_user_flag, \
virtual_env, \
install_dir
_cache["setup"][pip_command_str] = result
return result
else:
self._logger.debug("Could not detect desired output from testballoon install, got this instead: {!r}".format(data))
return False, False, False, None
def _preprocess_lines(self, *lines):
return map(self._preprocess, lines)
Binary file not shown.
File diff suppressed because it is too large. Load diff
+887 -519
View File
File diff suppressed because it is too large. Load diff