✨ swu: one month update log

Implements #4065
This commit is contained in:
Gina Häußge committed 2021-07-06 11:57:33 +02:00
1 parent 9f77502214
commit 8bb3312bba
6 files changed
+266 -67

No files matched your search

+163 -25
View File
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
__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"
@@ -47,6 +49,8 @@ MINIMUM_PYTHON = "2.7.9"
MINIMUM_SETUPTOOLS = "39.0.1"
MINIMUM_PIP = "9.0.3"
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
##~~ Plugin
@@ -91,6 +95,10 @@ class SoftwareUpdatePlugin(
self._overlay_cache_ttl = 0
self._overlay_cache_timestamp = None
self._update_log = []
self._update_log_path = None
self._update_log_dirty = False
self._environment_supported = True
self._environment_versions = {}
self._environment_ready = threading.Event()
@@ -113,6 +121,11 @@ class SoftwareUpdatePlugin(
)
self._load_version_cache()
self._update_log_path = os.path.join(
self.get_plugin_data_folder(), "updatelog.yaml"
)
self._load_update_log()
self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60
def refresh_checks(name, plugin):
@@ -500,6 +513,91 @@ class SoftwareUpdatePlugin(
pass
self._version_cache_dirty = True
def _load_update_log(self):
if not os.path.isfile(self._update_log_path):
return
import yaml
try:
with io.open(self._update_log_path, "rt", encoding="utf-8") as f:
data = yaml.safe_load(f)
except Exception:
self._logger.exception("Error while loading update log from disk")
else:
# clean up data older than updatelog_cutoff hours
before_cleanup = len(data)
cutoff = (
datetime.datetime.now()
- datetime.timedelta(minutes=self._settings.get_int(["updatelog_cutoff"]))
).strftime(DATETIME_FORMAT)
data = list(
filter(
lambda x: x.get("datetime") and x["datetime"] > cutoff,
data,
)
)
cleaned_up = len(data) - before_cleanup
if cleaned_up:
self._logger.info(
"Cleaned up {} old update log entries".format(cleaned_up)
)
self._update_log = sorted(data, key=lambda x: x["datetime"], reverse=True)
self._update_log_dirty = False
self._logger.info("Loaded update log from disk")
def _save_update_log(self):
import yaml
from octoprint.util import atomic_write
with atomic_write(
self._update_log_path, mode="wt", max_permissions=0o666
) as file_obj:
yaml.safe_dump(
self._update_log,
stream=file_obj,
default_flow_style=False,
indent=2,
allow_unicode=True,
)
self._update_log_dirty = False
self._logger.info("Saved update log to disk")
def _add_update_log_entry(
self,
target,
current_version,
target_version,
success,
text,
display_name=None,
release_notes="",
save=True,
):
if display_name is None:
display_name = target
self._update_log.append(
{
"datetime": datetime.datetime.now().strftime(DATETIME_FORMAT),
"target": target,
"current_version": current_version,
"target_version": target_version,
"display_name": display_name,
"release_notes": release_notes if release_notes else "",
"success": success,
"text": text,
}
)
self._update_log_dirty = True
if save:
self._save_update_log()
# ~~ SettingsPlugin API
def get_settings_defaults(self):
@@ -544,13 +642,14 @@ class SoftwareUpdatePlugin(
},
},
"pip_command": None,
"cache_ttl": 24 * 60,
"cache_ttl": 24 * 60, # 1 day
"notify_users": True,
"ignore_throttled": False,
"minimum_free_storage": 150,
"check_overlay_url": "https://plugins.octoprint.org/update_check_overlay.json",
"check_overlay_py2_url": "https://plugins.octoprint.org/update_check_overlay_py2.json",
"check_overlay_ttl": 6 * 60,
"check_overlay_ttl": 6 * 60, # 6 hours
"updatelog_cutoff": 30 * 24 * 60, # 30 days
"credentials": {
"github": None,
"bitbucket_user": None,
@@ -606,6 +705,7 @@ class SoftwareUpdatePlugin(
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = None
data["octoprint_release_channel"] = None
# ~~ pip check settings
@@ -922,6 +1022,21 @@ class SoftwareUpdatePlugin(
# ~~ BluePrint API
@octoprint.plugin.BlueprintPlugin.route("/updatelog", methods=["GET"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def get_update_log(self):
def view():
return flask.jsonify(updatelog=self._update_log)
def lastmodified():
if os.path.exists(self._update_log_path):
return os.stat(self._update_log_path).st_mtime
else:
return 0
return with_revalidation_checking(lastmodified_factory=lastmodified)(view)()
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
@@ -1372,28 +1487,9 @@ class SoftwareUpdatePlugin(
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"],
)
release_notes = self._get_release_notes(
target_information, populated_check
)
information[target] = {
"updateAvailable": target_update_available,
@@ -1462,6 +1558,24 @@ class SoftwareUpdatePlugin(
return information, update_available, update_possible
def _get_release_notes(self, information, populated_check):
release_notes = None
if information and information["remote"] and information["remote"]["value"]:
if populated_check.get("release_notes"):
release_notes = populated_check["release_notes"]
elif "release_notes" in information["remote"]:
release_notes = information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(
octoprint_version=VERSION,
target_name=information["remote"]["name"],
target_version=information["remote"]["value"],
)
return release_notes
def _get_check_hash(self, check):
def dict_to_sorted_repr(d):
lines = []
@@ -1706,6 +1820,9 @@ class SoftwareUpdatePlugin(
# we might have needed to update the config, so we'll save that now
self._settings.save()
# we also need to save our update log changes
self._save_update_log()
# also, we are now longer updating
self._update_in_progress = False
@@ -1759,8 +1876,22 @@ class SoftwareUpdatePlugin(
information, update_available, update_possible, _, _ = self._get_current_version(
target, check, online=online, credentials=credentials
)
populated_check = self._populated_check(target, check)
def add_update_log(success, text):
self._add_update_log_entry(
target,
information["local"]["value"],
information["remote"]["value"],
success,
text,
display_name=populated_check["displayName"],
release_notes=self._get_release_notes(information, populated_check),
save=False,
)
if not update_available and not force:
add_update_log(False, "Target is already up to date")
return False, None
if not update_possible:
@@ -1769,6 +1900,7 @@ class SoftwareUpdatePlugin(
target
)
)
add_update_log(False, "Update not possible, missing information")
return False, None
if not information.get("compatible", True):
@@ -1777,6 +1909,7 @@ class SoftwareUpdatePlugin(
target
)
)
add_update_log(False, "Update is incompatible")
return False, None
# determine the target version to update to
@@ -1807,7 +1940,6 @@ class SoftwareUpdatePlugin(
### The actual update procedure starts here...
populated_check = self._populated_check(target, check)
try:
self._logger.info(
"Starting update of {} to {}...".format(target, target_version)
@@ -1846,6 +1978,7 @@ class SoftwareUpdatePlugin(
"reason": "Unknown update type",
},
)
add_update_log(False, "Update failed, unknown update type")
return False, None
except exceptions.CannotUpdateOffline:
@@ -1862,6 +1995,8 @@ class SoftwareUpdatePlugin(
"reason": "No internet connection",
},
)
add_update_log(False, "No internet connection")
return False, None
except Exception as e:
self._logger.exception(
@@ -1895,6 +2030,7 @@ class SoftwareUpdatePlugin(
"reason": "unknown",
},
)
add_update_log(False, "Update failed")
else:
# make sure that any external changes to config.yaml are loaded into the system
@@ -1906,6 +2042,8 @@ class SoftwareUpdatePlugin(
del self._version_cache[target]
self._version_cache_dirty = True
add_update_log(True, "Update successful")
return target_error, target_result
def _persist_check_current(self, target, check, current):
@@ -12,6 +12,7 @@
this.checkUrl = url + "check";
this.updateUrl = url + "update";
this.configureUrl = url + "configure";
this.updatelogUrl = url + "updatelog";
};
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function (
@@ -88,6 +89,10 @@
return this.base.postJson(this.configureUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.getUpdatelog = function (opts) {
return this.base.get(this.updatelogUrl, opts);
};
OctoPrintClient.registerPluginComponent(
"softwareupdate",
OctoPrintSoftwareUpdateClient
@@ -1 +1 @@
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#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}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#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}
@@ -130,6 +130,7 @@ $(function () {
[],
0
);
self.updatelog = ko.observableArray([]);
self.availableAndPossible = ko.pureComputed(function () {
return _.filter(self.versions.items(), function (info) {
@@ -161,6 +162,10 @@ $(function () {
} else {
self._closePopup();
}
if (self.loginState.hasPermission(self.access.permissions.ADMIN)) {
self.requestUpdatelog();
}
};
self._showPopup = function (options, eventListeners, singleButtonNotify) {
@@ -556,6 +561,16 @@ $(function () {
});
};
self.fromUpdatelogResponse = function (response) {
self.updatelog(response.updatelog);
};
self.requestUpdatelog = function () {
OctoPrint.plugins.softwareupdate
.getUpdatelog()
.done(self.fromUpdatelogResponse);
};
self.iconTitleForEntry = function (data) {
if (data.updatePossible) {
return "";
@@ -33,6 +33,16 @@ td.settings_plugin_softwareupdate_column_information {
}
}
#settings_plugin_softwareupdate_updatelog_list {
.line {
display: block;
}
td.settings_plugin_softwareupdate_column_datetime {
width: 150px;
}
}
#settings_plugin_softwareupdate_workingdialog_output {
font-size: 0.8em;
@@ -73,52 +73,83 @@
</p>
{% endtrans %}</div>
<div class="pull-right">
<button class="btn btn-primary" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
<button class="btn" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
</div>
<ul class="nav nav-pills">
<li class="active">
<a href="#settings_plugin_softwareupdate_updates" data-toggle="tab">{{ _('Current versions') }}</a>
</li>
<li>
<a href="#settings_plugin_softwareupdate_updatelog" data-toggle="tab">{{ _('Update log') }}</a>
</li>
</ul>
<h3>{{ _('Current versions') }}</h3>
<div class="tab-content">
<div class="tab-pane active" id="settings_plugin_softwareupdate_updates">
<div class="pull-right">
<button class="btn btn-primary" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
<button class="btn" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
</div>
<div class="swupdate-advanced">
<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="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.updateAll(true); }, enable: enableUpdate() && !checking(), css: {disabled: !enableUpdate() || checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update all (even if no new versions are available)') }}</button>
<h3>{{ _('Current versions') }}</h3>
<div class="swupdate-advanced">
<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="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.updateAll(true); }, enable: enableUpdate() && !checking(), css: {disabled: !enableUpdate() || checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update all (even if no new versions are available)') }}</button>
</div>
</div>
<div id="settings_plugin_softwareupdate_updatelist">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: versions.paginatedItems">
<tr data-bind="attr: {title: displayName}">
<td class="settings_plugin_softwareupdate_column_update">
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }" title="{{ _('Update available')|edq }}"></i></a>
<span data-bind="visible: !compatible" class="muted"><i class="fas fa-power-off" title="{{ _('Not compatible') }}|edq"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: $root.enableUpdate() && updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fas 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 data-bind="visible: compatible" class="muted">
<span data-bind="visible: releaseChannels && releaseChannels.available" class="line">{{ _('Release Channel:') }} <select class="settings_plugin_softwareupdate_release_channel" data-bind="visible: releaseChannels && releaseChannels.available, value: releaseChannels.current, options: releaseChannels.available, optionsText: 'name', optionsValue: 'channel'"></select> <a href="https://faq.octoprint.org/using-release-channels" target="_blank"><i class="fas fa-question-circle"></i></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>
<small data-bind="visible: !compatible">
<span class="line text-error">{{ _('Newer versions of this plugin are not compatible to this setup.') }}</span>
</small>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane active" id="settings_plugin_softwareupdate_updatelog">
<h3>{{ _('Update log') }}</h3>
<div id="settings_plugin_softwareupdate_updatelog_list">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: updatelog">
<tr>
<td class="settings_plugin_softwareupdate_column_datetime" data-bind="text: datetime"></td>
<td>
<span class="line" data-bind="css: { 'text-error': !success, 'text-success': success }"><strong data-bind="text: display_name"></strong> <span data-bind="text: current_version"></span> ➡ <span data-bind="text: target_version"></span></span>
<span class="line" data-bind="text: text"></span>
<span class="line" data-bind="visible: release_notes"><a data-bind="attr: {href: release_notes}" target="_blank" rel="noreferrer noopener">{{ _('Release Notes') }}</a></span>
</td>
</tr>
</tbody>
</table>
</div>
<small>{{ _('Please note that the update log will only contain entries for updates performed through OctoPrint\'s Software Update plugin.') }}</small>
</div>
</div>
<div id="settings_plugin_softwareupdate_updatelist">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: versions.paginatedItems">
<tr data-bind="attr: {title: displayName}">
<td class="settings_plugin_softwareupdate_column_update">
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }" title="{{ _('Update available')|edq }}"></i></a>
<span data-bind="visible: !compatible" class="muted"><i class="fas fa-power-off" title="{{ _('Not compatible') }}|edq"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: $root.enableUpdate() && updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fas 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 data-bind="visible: compatible" class="muted">
<span data-bind="visible: releaseChannels && releaseChannels.available" class="line">{{ _('Release Channel:') }} <select class="settings_plugin_softwareupdate_release_channel" data-bind="visible: releaseChannels && releaseChannels.available, value: releaseChannels.current, options: releaseChannels.available, optionsText: 'name', optionsValue: 'channel'"></select> <a href="https://faq.octoprint.org/using-release-channels" target="_blank"><i class="fas fa-question-circle"></i></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>
<small data-bind="visible: !compatible">
<span class="line text-error">{{ _('Newer versions of this plugin are not compatible to this setup.') }}</span>
</small>
</td>
</tr>
</tbody>
</table>
</div>
<div id="settings_plugin_softwareupdate_configurationdialog" class="modal hide fade-in">
<div class="modal-header">