✨ SWU: Update capability for single file plugins

Also added a bunch of new version checks for that usecase.
This commit is contained in:
Gina Häußge committed 2020-06-10 19:44:55 +02:00
1 parent 37526800c1
commit 31e98b8949
8 files changed
+315 -38

No files matched your search

+89 -15
View File
@@ -146,6 +146,9 @@ Configuring the Plugin
Version checks
++++++++++++++
Version check types are configured through the ``type`` parameter. The following
types are currently recognized:
* ``github_release``: Checks against releases published on Github. Additional
config parameters:
@@ -196,10 +199,29 @@ Version checks
* ``checkout_folder``: (mandatory) The full path to the folder with a valid git
repository to check.
* ``pypi_release``: Checks `pypi.org <https://pypi.org>`_ for new releases of a specified package.
* ``pypi_release``: Checks `pypi.org <https://pypi.org>`_ for new releases of a specified package. Additional
config parameters:
* ``package``: (mandatory) Name of the package which to check.
* ``etag``: Checks the ``ETag`` header on a defined URL for changes. Additional
config parameters:
* ``etag_url`` or ``url``: (mandatory) URL to check. ``url`` can be used to avoid duplication in case of updater
methods such as ``single_file_plugin``.
* ``lastmodified``: Checks the ``Last-Modified`` header on a defined URL for changes. Additional
config parameters:
* ``lastmodified_url`` or ``url``: (mandatory) URL to check. ``url`` can be used to avoid duplication in case of updater
methods such as ``single_file_plugin``.
* ``jsondata``: Checks the provided JSON endpoint for changes. The JSON endpoint must return an object with the
property ``version``, which should contain the latest version, e.g. ``{"version":"1.2.3"}``. Additional
config parameters:
* ``jsondata``: (mandatory) URL from which to fetch the JSON data
* ``command_line``: Uses a provided script to determine whether an update
is available. Additional config parameters:
@@ -233,20 +255,42 @@ Version checks
Update methods
++++++++++++++
* ``pip``: An URL to provide to ``pip install`` in order to perform the
update. May contain a placeholder ``{target}`` which will be the most
recent version specifier as retrieved from the update check.
* ``update_script``: A script to execute in order to perform the update. May
contain placeholders ``{target}`` (for the most recent version specified
as retrieved from the update check), ``{branch}`` for the branch to switch
to to access the release, ``{folder}`` for the working directory
of the script and ``{python}`` for the python executable OctoPrint is
running under. The working directory must be specified either by an
``update_folder`` setting or if the ``git_commit`` check is used its
``checkout_folder`` setting.
* ``python_updater``: Can only be specified by plugins through the
:ref:`hook <sec-bundledplugins-softwareupdate-hooks>`. A Python callable
which performs the update, see below for details.
Update methods are specified via the ``method`` parameter. Some update methods are assigned implicitly
through the presence of their mandatory configuration parameters. The following methods are currently
supported:
* ``pip``: Update by ``pip install``ing the supplied URL. May contain a
placeholder ``{target}`` which will be the most recent version specifier as retrieved from the update check.
Additional config parameters:
* ``pip``: The URL to use for installing. Presence implies ``method: pip``.
* ``single_file_plugin``: Update a single file plugin by re-downloading it from a configured URL.
Additional config parameters:
* ``url``: (mandatory) The URL from which to install the single file plugin. Must be a single self contained
python file.
* ``update_script``: Update by executing a script.
Additional config parameters:
* ``update_script``: (mandatory) The path of the script to run. May
contain placeholders ``{target}`` (for the most recent version specified
as retrieved from the update check), ``{branch}`` for the branch to switch
to to access the release, ``{folder}`` for the working directory
of the script and ``{python}`` for the python executable OctoPrint is
running under. Presence implies ``method: update_script``.
* ``update_folder`` or ``checkout_folder``: (mandatory) The working directory.
``checkout_folder`` can be used to avoid duplication in case of check
types such as ``git_commit``.
* ``python_updater``: Update by executing a custom python callable.
Additional config parameters:
* ``python_updater``: (mandatory) Can only be specified by plugins through the
:ref:`hook <sec-bundledplugins-softwareupdate-hooks>`. A Python callable
which performs the update, see below for details. Presence implies ``method: python_updater``.
* ``sleep_a_bit``: Does nothing but block for a configurable ``duration`` and log
a countdown in the meantime. Useful for debugging software update mechanisms
during development.
@@ -329,6 +373,36 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing
branch: devel
pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip'
Single file plugin hosted in a gist ``https://gist.github.com/someUser/somegist`` and updated whenever there are changes:
.. code-block:: yaml
plugins:
softwareupdate:
checks:
some_plugin:
type: etag
url: 'https://gist.github.com/someUser/somegist/raw/some_plugin.py'
method: single_file_plugin
The same but updated when a ``version.json`` hosted alongside gets updated with a new version can be found at
.. code-block:: yaml
plugins:
softwareupdate:
checks:
some_plugin:
type: jsondata
jsondata: 'https://gist.github.com/someUser/somegist/raw/version.json'
url: 'https://gist.github.com/someUser/somegist/raw/some_plugin.py'
method: single_file_plugin
Note that for gist hosted single file plugins, you need to use the "Raw" install link but should remove the
commit identifier. E.g. ``https://gist.githubusercontent.com/<user>/<gistid>/raw/my_plugin.py`` instead of
``https://gist.githubusercontent.com/<user>/<gistid>/raw/<commit>/my_plugin.py``. Note that these URLs will
be cached by Github for a bit, so update will not be immediately picked up.
.. _sec-bundledplugins-softwareupdate-events:
Events
@@ -52,6 +52,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.EventHandlerPlugin):
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("etag", "lastmodified", "jsondata")
OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin")
DATA_FORMAT_VERSION = "v4"
@@ -172,7 +175,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# This used to be part of the settings migration (version 2) due to a bug - it can't
# stay there though since it interferes with manual entries to the checks not
# originating from within a plugin. Hence we do that step now here.
if "type" not in effective_config or effective_config["type"] not in self.COMMIT_TRACKING_TYPES:
if "type" not in effective_config or effective_config["type"] not in self.CURRENT_TRACKING_TYPES:
deletables = ["current", "displayVersion"]
else:
deletables = []
@@ -507,7 +510,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is not None and "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if "type" not in octoprint_check or octoprint_check["type"] not in self.COMMIT_TRACKING_TYPES:
if "type" not in octoprint_check or octoprint_check["type"] not in self.CURRENT_TRACKING_TYPES:
deletables=["current", "displayName", "displayVersion"]
else:
deletables=[]
@@ -860,8 +863,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
try:
version_checker = self._get_version_checker(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
if information is not None:
if is_current and check["type"] in self.CURRENT_TRACKING_TYPES and check["current"] is None:
self._persist_check_current(target, check, information["remote"]["value"])
del self._version_cache[target]
self._version_cache_dirty = True
elif not is_current:
update_available = True
except exceptions.CannotCheckOffline:
update_possible = False
information["needs_online"] = True
@@ -882,6 +890,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
updater = self._get_updater(target, check)
update_possible = updater.can_perform_update(target, check, online=online)
except Exception:
self._logger.exception("Error while checking if {} can be updated".format(target))
update_possible = False
self._version_cache[target] = dict(timestamp=time.time(),
@@ -966,7 +975,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if "restart" in check:
target_restart_type = check["restart"]
elif "pip" in check:
elif "pip" in check or check.get("method") in self.OCTOPRINT_RESTART_TYPES:
target_restart_type = "octoprint"
else:
target_restart_type = None
@@ -1090,21 +1099,30 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.load()
# persist the new version if necessary for check type
if check["type"] in self.COMMIT_TRACKING_TYPES:
dummy_default = dict(plugins=dict())
dummy_default["plugins"][self._identifier] = dict(checks=dict())
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
self._settings.set(["checks", target, "current"], target_version, defaults=dummy_default)
# we have to save here (even though that makes us save quite often) since otherwise the next
# load will overwrite our changes we just made
self._settings.save()
self._persist_check_current(target, check, target_version)
del self._version_cache[target]
self._version_cache_dirty = True
return target_error, target_result
def _persist_check_current(self, target, check, current):
if check["type"] not in self.CURRENT_TRACKING_TYPES:
return
self._settings.load()
dummy_default = dict(plugins=dict())
dummy_default["plugins"][self._identifier] = dict(checks=dict())
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
self._settings.set(["checks", target, "current"], current, defaults=dummy_default)
# we have to save here (even though that makes us save quite often) since otherwise the next
# load will overwrite our changes we just made
self._settings.save()
check["current"] = current
def _perform_restart(self, restart_command):
"""
Performs a restart using the supplied restart_command.
@@ -1214,7 +1232,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# displayVersion AND current missing or None
result["displayVersion"] = "unknown"
if check["type"] in self.COMMIT_TRACKING_TYPES:
if check["type"] in self.CURRENT_TRACKING_TYPES:
result["current"] = check.get("current", None)
else:
result["current"] = check.get("current", check.get("displayVersion", None))
@@ -1285,13 +1303,15 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
cannot be determined.
"""
mapping = dict(update_script=updaters.update_script,
pip=updaters.pip,
python_updater=updaters.python_updater,
sleep_a_bit=updaters.sleep_a_bit)
method = self._get_update_method(target, check)
if method is None:
raise exceptions.UnknownUpdateType()
method = self._get_update_method(target, check, valid_methods=list(mapping.keys()))
return mapping[method]
updater = getattr(updaters, method)
if updater is None:
raise exceptions.UnknownUpdateType()
return updater
def _get_octoprint_checkout_folder(self, checks=None):
if checks is None:
@@ -5,4 +5,4 @@ __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 . import pip, python_updater, update_script, sleep_a_bit
from . import pip, python_updater, update_script, sleep_a_bit, single_file_plugin
@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import tempfile
import logging
import shutil
import os
import ast
import io
from octoprint.util.net import download_file
from octoprint.settings import settings
from .. import exceptions
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.download_single_file_plugin")
def can_perform_update(target, check, online=True):
return online or check.get("offline", False)
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
url = check.get("url")
if url is None:
raise exceptions.ConfigurationInvalid("download_single_file_plugin updater needs url set")
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
folder = None
try:
try:
_log_message("Download file from {}".format(url))
folder = tempfile.TemporaryDirectory()
path = download_file(url, folder.name)
except Exception as exc:
raise exceptions.NetworkError(cause=exc)
filename = os.path.basename(path)
_, ext = os.path.splitext(filename)
if ext not in (".py",):
raise exceptions.UpdateError("File is not a python file: {}".format(filename), None)
try:
with io.open(path, 'rb') as f:
ast.parse(f.read(), filename=path)
except Exception:
logger.exception("Could not parse {} as python file".format(path), None)
raise exceptions.UpdateError("Could not parse {} as python file.".format(filename), None)
destination = os.path.join(settings().getBaseFolder("plugins"), filename)
try:
_log_message("Copy {} to {}".format(path, destination))
shutil.copy(path, destination)
except Exception:
logger.exception("Could not copy {} to {}".format(path, destination))
raise exceptions.UpdateError("Could not copy {} to {}".format(path, destination), None)
return "ok"
finally:
if folder is not None:
folder.cleanup()
@@ -5,7 +5,8 @@ __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 . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker, never_current, always_current, pypi_release
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, \
python_checker, never_current, always_current, pypi_release, etag, lastmodified, jsondata
def log_github_ratelimit(logger, r):
ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import requests
import logging
from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.etag")
def get_latest(target, check, online=True):
if not online:
raise CannotCheckOffline()
url = check.get("etag_url", check.get("url"))
current = check.get("current")
if url is None:
raise ConfigurationInvalid("ETag version check needs etag_url or url set")
try:
with requests.head(url) as r:
latest = r.headers.get("Etag")
except Exception as exc:
raise NetworkError(cause=exc)
information = dict(local=dict(name="ETag {}".format(current if current else "-"), value=current),
remote=dict(name="ETag {}".format(latest if latest else "-"), value=latest))
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
return information, current is None or current == latest or latest is None
@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import requests
import logging
from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.jsondata")
def get_latest(target, check, online=True):
if not online:
raise CannotCheckOffline()
url = check.get("jsondata")
current = check.get("current")
if url is None:
raise ConfigurationInvalid("jsondata version check needs jsondata set")
try:
with requests.get(url) as r:
data = r.json()
except Exception as exc:
raise NetworkError(cause=exc)
latest = data.get("version")
information = dict(local=dict(name=current if current else "-", value=current),
remote=dict(name=latest if latest else "-", value=latest))
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
return information, current is None or current == latest or latest is None
@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import requests
import logging
from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.etag")
def get_latest(target, check, online=True):
if not online:
raise CannotCheckOffline()
url = check.get("lastmodified_url", check.get("url"))
current = check.get("current")
if url is None:
raise ConfigurationInvalid("Last-Modified version check needs either lastmodified_url or url set")
try:
with requests.head(url) as r:
latest = r.headers.get("Last-Modified")
except Exception as exc:
raise NetworkError(cause=exc)
information = dict(local=dict(name="Last-Modified {}".format(current if current else "-"), value=current),
remote=dict(name="Last-Modified {}".format(latest if latest else "-"), value=latest))
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
return information, current is None or current == latest or latest is None