✨ Pmgr: Support installing multiple plugins & add install queue (#4643)

* address review comments for PR #4478

* add install queuing while printing or paused, #4428

* PR review requested changes

* PR review refactor suggestion

Co-authored-by: Gina Häußge <gina@octoprint.org>

* PR review refactor suggestion

Co-authored-by: Gina Häußge <gina@octoprint.org>
This commit is contained in:
jneilliiiandGina Häußge authored and GitHub committed 2022-10-20 12:41:09 +02:00
1 parent 89f18a9cd8
commit b032e1339f
4 files changed
+571 -43

No files matched your search

+1
View File
@@ -171,6 +171,7 @@ date of first contribution):
* [Dawid Pieper](https://github.com/dawidpieper)
* ["arrdem"](https://github.com/arrdem)
* [Arkadiusz Miśkiewicz](https://github.com/arekm)
* ["tempodat"](https://github.com/tempodat)
* [Frederik Kemner](https://github.com/040medien)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
+123 -6
View File
@@ -33,7 +33,7 @@ from octoprint.server.util.flask import (
with_revalidation_checking,
)
from octoprint.settings import valid_boolean_trues
from octoprint.util import deprecated, to_bytes
from octoprint.util import RepeatedTimer, deprecated, to_bytes
from octoprint.util.net import download_file
from octoprint.util.pip import (
OUTPUT_SUCCESS,
@@ -193,6 +193,10 @@ class PluginManagerPlugin(
self._install_task = None
self._install_lock = threading.RLock()
self._queued_installs = []
self._queued_installs_abort_timer = None
self._print_cancelled = False
def initialize(self):
self._console_logger = logging.getLogger(
"octoprint.plugins.pluginmanager.console"
@@ -619,7 +623,42 @@ class PluginManagerPlugin(
def on_event(self, event, payload):
from octoprint.events import Events
if (
if event == Events.PRINT_STARTED:
self._queued_installs_timer_stop()
self._print_cancelled = False
elif (
event == Events.PRINT_DONE
and self._settings.global_get(["webcam", "timelapse", "type"]) == "off"
and len(self._queued_installs) > 0
):
self._queued_installs_timer_start()
elif event == Events.PRINT_FAILED and len(self._queued_installs) > 0:
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"print_failed": True,
"queued": self._queued_installs,
},
)
self._print_cancelled = True
elif (
event == Events.MOVIE_DONE
and self._settings.global_get(["webcam", "timelapse", "type"]) != "off"
and len(self._queued_installs) > 0
and not (self._printer.is_printing() or self._printer.is_paused())
and not self._print_cancelled
):
self._queued_installs_timer_start()
elif event == Events.USER_LOGGED_IN and len(self._queued_installs) > 0:
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"queued": self._queued_installs,
},
)
elif (
event != Events.CONNECTIVITY_CHANGED
or not payload
or not payload.get("new", False)
@@ -627,6 +666,53 @@ class PluginManagerPlugin(
return
self._fetch_all_data(do_async=True)
def _queued_installs_timer_start(self):
if self._queued_installs_abort_timer is not None:
return
self._logger.debug("Starting queued updates timer.")
self._timeout_value = 60
self._queued_installs_abort_timer = RepeatedTimer(
1, self._queued_installs_timer_task
)
self._queued_installs_abort_timer.start()
def _queued_installs_timer_stop(self):
if self._queued_installs_abort_timer is not None:
self._queued_installs_abort_timer.cancel()
self._queued_installs_abort_timer = None
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"queued": self._queued_installs,
"timeout_value": -1,
},
)
def _queued_installs_timer_task(self):
if self._timeout_value is None:
return
self._timeout_value -= 1
self._send_result_notification(
"queued_installs",
{
"type": "queued_installs",
"queued": self._queued_installs,
"timeout_value": self._timeout_value,
},
)
if self._timeout_value <= 0:
if self._queued_installs_abort_timer is not None:
self._queued_installs_abort_timer.cancel()
self._queued_installs_abort_timer = None
for plugin in self._queued_installs:
plugin.pop("command")
self.command_install(**plugin)
self._queued_installs = []
##~~ SimpleApiPlugin
def get_api_commands(self):
@@ -638,17 +724,48 @@ class PluginManagerPlugin(
"cleanup": ["plugin"],
"cleanup_all": [],
"refresh_repository": [],
"clear_queued_plugin": ["plugin"],
"clear_queued_installs": [],
}
def on_api_command(self, command, data):
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
abort(403)
if self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
abort(409, description="Printer is currently printing or paused")
if command == "clear_queued_plugin":
if data["plugin"] and data["plugin"] in self._queued_installs:
self._queued_installs.remove(data["plugin"])
return (
jsonify({"queued_installs": self._queued_installs}),
202,
)
if command == "install":
elif command == "clear_queued_installs":
self._queued_installs.clear()
return (
jsonify({"queued_installs": self._queued_installs}),
202,
)
elif self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
# store targets to be run later on print done event
if command == "install" and data not in self._queued_installs:
self._logger.debug(f"Queuing install of {data}")
self._queued_installs.append(data)
if len(self._queued_installs) > 0:
self._logger.debug(f"Queued installs: {self._queued_installs}")
return (
jsonify({"queued_installs": self._queued_installs}),
202,
)
else:
abort(
409,
description="Printer is currently printing or paused and install could not be queued",
)
elif command == "install":
if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can():
abort(403)
url = data["url"]
@@ -358,7 +358,6 @@ $(function () {
self.enableRepoInstall = function (data) {
return (
self.enableManagement() &&
self.pipAvailable() &&
!self.safeMode() &&
!self.throttled() &&
@@ -533,6 +532,107 @@ $(function () {
}
};
self.multiInstallQueue = ko.observableArray([]);
self.queuedInstalls = ko.observableArray([]);
self.multiInstallRunning = ko.observable(false);
self.multiInstallInitialSize = ko.observable(0);
self.multiInstallValid = function () {
return (
self.loginState.hasPermission(
self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL
) &&
self.pipAvailable() &&
!self.safeMode() &&
!self.throttled() &&
self.online() &&
self.multiInstallQueue().length > 0 &&
self.multiInstallQueue().every(self.isCompatible)
);
};
self.repoInstallSelectedButtonText = function () {
return self.multiInstallQueue().some(self.installed)
? "(Re)install selected"
: "Install selected";
};
self.repoInstallSelectedConfirm = function () {
if (!self.multiInstallValid()) return;
if (self.multiInstallQueue().length === 1) {
self.installFromRepository(self.multiInstallQueue()[0]);
return;
}
var question = "<ul>";
self.multiInstallQueue().forEach(function (plugin) {
var action = self.installed(plugin)
? gettext("Reinstall")
: gettext("Install");
question += _.sprintf(
"<li>%(action)s <em><b>%(name)s@%(version)s</b></em></li>",
{
action: _.escape(action),
name: _.escape(plugin.title),
version: _.escape(plugin.github.latest_release.tag)
}
);
});
question += "</ul>";
showConfirmationDialog({
title: gettext("Confirm installation of multiple plugins"),
message: gettext("Please confirm you want to perform these actions:"),
question: question,
cancel: gettext("Cancel"),
proceed: gettext("Install"),
proceedClass: "primary",
onproceed: self.startMultiInstall
});
};
self.startMultiInstall = function () {
if (self.multiInstallRunning() || !self.multiInstallValid()) return;
self.multiInstallRunning(true);
self.multiInstallInitialSize(self.multiInstallQueue().length);
self._markWorking(
gettext("Installing multiple plugins"),
gettext("Starting installation of multiple plugins...")
);
self.performMultiInstallJob();
};
self.performMultiInstallJob = function () {
if (!self.multiInstallRunning() || self.multiInstallQueue().length === 0)
return;
var plugin = self.multiInstallQueue.pop();
self.installFromRepository(plugin);
};
self.alertMultiInstallJobDone = function (response) {
if (
!self.multiInstallRunning() ||
response.action != "install" ||
!response.result
)
return;
if (self.multiInstallQueue().length === 0) {
self.installUrl("");
self.multiInstallQueue([]);
self.multiInstallRunning(false);
self._markDone();
} else {
self.performMultiInstallJob();
}
};
self.performRepositorySearch = function () {
var query = self.repositorySearchQuery();
if (query !== undefined && query.trim() !== "") {
@@ -1050,10 +1150,6 @@ $(function () {
return;
}
if (!self.enableManagement()) {
return;
}
self.installPlugin(
data.archive,
data.title,
@@ -1062,6 +1158,22 @@ $(function () {
);
};
self.removeFromQueue = function (plugin) {
var data = {
plugin: {
command: self.installed(plugin) ? "reinstall" : "install",
url: plugin.archive,
dependency_links:
plugin.follow_dependency_links || self.followDependencyLinks()
}
};
OctoPrint.simpleApiCommand("pluginmanager", "clear_queued_plugin", data).done(
function (response) {
self.queuedInstalls(response.queued_installs);
}
);
};
self.installPlugin = function (url, name, reinstall, followDependencyLinks) {
if (
!self.loginState.hasPermission(
@@ -1071,10 +1183,6 @@ $(function () {
return;
}
if (!self.enableManagement()) {
return;
}
if (self.throttled()) {
return;
}
@@ -1108,10 +1216,59 @@ $(function () {
{url: _.escape(url), name: _.escape(name)}
);
}
if (self.multiInstallRunning()) {
workTitle =
_.sprintf("[%(index)d/%(total)d] ", {
index:
this.multiInstallInitialSize() -
self.multiInstallQueue().length,
total: this.multiInstallInitialSize()
}) + workTitle;
}
self._markWorking(workTitle, workText);
var onSuccess = function (response) {
self.installUrl("");
if (response.hasOwnProperty("queued_installs")) {
self.queuedInstalls(response.queued_installs);
var text =
'<div class="row-fluid"><p>' +
gettext("The following plugins are queued to be installed.") +
"</p><ul><li>" +
_.map(response.queued_installs, function (info) {
var plugin = ko.utils.arrayFirst(
self.repositoryplugins.paginatedItems(),
function (item) {
return item.archive === info.url;
}
);
return plugin.title;
}).join("</li><li>") +
"</li></ul></div>";
if (typeof self.installQueuePopup !== "undefined") {
self.installQueuePopup.update({
text: text
});
if (self.installQueuePopup.state === "closed") {
self.installQueuePopup.open();
}
} else {
self.installQueuePopup = new PNotify({
title: gettext("Plugin installs queued"),
text: text,
type: "notice"
});
}
if (self.multiInstallQueue().length > 0) {
self.performMultiInstallJob();
} else {
self.multiInstallRunning(false);
self.workingDialog.modal("hide");
self._markDone();
}
}
},
onError = function (jqXHR) {
if (jqXHR.status === 409) {
@@ -1429,19 +1586,58 @@ $(function () {
);
};
self.installButtonAction = function (data) {
if (self.enableRepoInstall(data)) {
if (!self.installQueued(data)) {
self.installFromRepository(data);
} else {
self.removeFromQueue(data);
}
} else {
return false;
}
};
self.installButtonText = function (data) {
return self.isCompatible(data)
? self.installed(data)
? gettext("Reinstall")
: gettext("Install")
: data.disabled
? gettext("Disabled")
: gettext("Incompatible");
if (!self.isCompatible(data)) {
if (data.disabled) {
return gettext("Disabled");
} else {
return gettext("Incompatible");
}
}
if (self.installQueued(data)) {
return gettext("Dequeue");
} else if (self.installed(data)) {
return gettext("Reinstall");
} else {
return gettext("Install");
}
};
self._processPluginManagementResult = function (response, action, plugin) {
if (response.result) {
self._markDone();
if (self.queuedInstalls().length > 0 && action === "install") {
var plugin_dequeue = ko.utils.arrayFirst(
self.queuedInstalls(),
function (item) {
return item.url === response.source;
}
);
if (plugin_dequeue) {
self.queuedInstalls.remove(plugin_dequeue);
}
if (self.queuedInstalls().length === 0) {
self.multiInstallRunning(false);
self._markDone();
}
} else if (self.multiInstallRunning() && action === "install") {
// A MultiInstall job has finished
self.alertMultiInstallJobDone(response);
} else {
self._markDone();
}
} else {
self._markDone(response.reason, response.faq);
}
@@ -1541,7 +1737,7 @@ $(function () {
"</p>";
type = "warning";
if (self.restartCommandSpec) {
if (self.restartCommandSpec && !self.multiInstallRunning()) {
var restartClicked = false;
confirm = {
confirm: true,
@@ -1596,20 +1792,22 @@ $(function () {
"</p>";
type = "warning";
var refreshClicked = false;
confirm = {
confirm: true,
buttons: [
{
text: gettext("Reload now"),
click: function () {
if (refreshClicked) return;
refreshClicked = true;
location.reload(true);
if (!self.multiInstallRunning()) {
var refreshClicked = false;
confirm = {
confirm: true,
buttons: [
{
text: gettext("Reload now"),
click: function () {
if (refreshClicked) return;
refreshClicked = true;
location.reload(true);
}
}
}
]
};
]
};
}
} else if (self.logContents.action_reconnect) {
text +=
"<p>" +
@@ -2034,7 +2232,10 @@ $(function () {
var messageType = data.type;
if (messageType === "loglines" && self.working()) {
if (
messageType === "loglines" &&
(self.working() || self.queuedInstalls().length > 0)
) {
_.each(data.loglines, function (line) {
self.loglines.push(self._preprocessLine(line));
});
@@ -2054,9 +2255,210 @@ $(function () {
self._processPluginManagementResult(data, action, name);
self.requestPluginData();
} else if (messageType === "queued_installs") {
if (data.hasOwnProperty("queued")) {
self.queuedInstalls(data.queued);
var queuedInstallsPopupOptions = {
title: gettext("Queued Installs"),
text: "",
type: "notice",
icon: false,
hide: false,
buttons: {
closer: false,
sticker: false
},
history: {
history: false
}
};
if (data.print_failed && data.queued.length > 0) {
queuedInstallsPopupOptions.title = gettext(
"Queued Installs Paused"
);
queuedInstallsPopupOptions.text =
'<div class="row-fluid"><p>' +
gettext("The following plugins are queued to be installed.") +
"</p><ul><li>" +
_.map(self.queuedInstalls(), function (info) {
var plugin = ko.utils.arrayFirst(
self.repositoryplugins.paginatedItems(),
function (item) {
return item.archive === info.url;
}
);
return plugin.title;
}).join("</li><li>") +
"</li></ul></div>";
queuedInstallsPopupOptions.confirm = {
confirm: true,
buttons: [
{
text: gettext("Continue Installs"),
addClass: "btn-block btn-primary",
promptTrigger: true,
click: function (notice, value) {
notice.remove();
notice
.get()
.trigger("pnotify.continue", [notice, value]);
}
},
{
text: gettext("Cancel Installs"),
addClass: "btn-block btn-danger",
promptTrigger: true,
click: function (notice, value) {
notice.remove();
notice
.get()
.trigger("pnotify.cancel", [notice, value]);
}
}
]
};
} else if (
data.hasOwnProperty("timeout_value") &&
data.timeout_value > 0 &&
data.queued.length > 0
) {
var progress_percent = Math.floor(
(data.timeout_value / 60) * 100
);
var progress_class =
progress_percent < 25
? "progress-danger"
: progress_percent > 75
? "progress-success"
: "progress-warning";
var countdownText = _.sprintf(
gettext("Installing in %(sec)i secs..."),
{
sec: data.timeout_value
}
);
queuedInstallsPopupOptions.title = gettext(
"Starting Queued Installs"
);
queuedInstallsPopupOptions.text =
'<div class="row-fluid"><p>' +
gettext("The following plugins are going to be installed.") +
"</p><ul><li>" +
_.map(self.queuedInstalls(), function (info) {
var plugin = ko.utils.arrayFirst(
self.repositoryplugins.paginatedItems(),
function (item) {
return item.archive === info.url;
}
);
return plugin.title;
}).join("</li><li>") +
'</li></ul></p></div><div class="progress progress-softwareupdate ' +
progress_class +
'"><div class="bar">' +
countdownText +
'</div><div class="progress-text" style="clip-path: inset(0 0 0 ' +
progress_percent +
"%);-webkit-clip-path: inset(0 0 0 " +
progress_percent +
'%);">' +
countdownText +
"</div></div>";
queuedInstallsPopupOptions.confirm = {
confirm: true,
buttons: [
{
text: gettext("Cancel Installs"),
addClass: "btn-block btn-danger",
promptTrigger: true,
click: function (notice, value) {
notice.remove();
notice
.get()
.trigger("pnotify.cancel", [notice, value]);
}
},
{
text: "",
addClass: "hidden"
}
]
};
} else if (
data.hasOwnProperty("timeout_value") &&
data.timeout_value === 0 &&
data.queued.length > 0
) {
self.multiInstallRunning(true);
self._markWorking(
gettext("Installing queued plugins"),
gettext("Starting installation of multiple plugins...")
);
self.queuedInstallsPopup.remove();
self.queuedInstallsPopup = undefined;
return;
} else {
if (typeof self.queuedInstallsPopup !== "undefined") {
self.queuedInstallsPopup.remove();
self.queuedInstallsPopup = undefined;
}
return;
}
if (typeof self.queuedInstallsPopup !== "undefined") {
self.queuedInstallsPopup.update(queuedInstallsPopupOptions);
} else {
self.queuedInstallsPopup = new PNotify(
queuedInstallsPopupOptions
);
self.queuedInstallsPopup.get().on("pnotify.cancel", function () {
self.queuedInstallsPopup = undefined;
self.cancelQueuedInstalls();
});
self.queuedInstallsPopup
.get()
.on("pnotify.continue", function () {
self.queuedInstallsPopup = undefined;
self.performQueuedInstalls();
});
}
}
}
};
self.cancelQueuedInstalls = function () {
OctoPrint.simpleApiCommand("pluginmanager", "clear_queued_installs", {}).done(
function (response) {
self.queuedInstalls(response.queued_installs);
}
);
};
self.installQueued = function (plugin) {
var plugin_queued = ko.utils.arrayFirst(
self.queuedInstalls(),
function (item) {
return item.url === plugin.archive;
}
);
return typeof plugin_queued !== "undefined";
};
self.performQueuedInstalls = function () {
self.queuedInstalls().forEach(function (plugin) {
var queued_plugin = ko.utils.arrayFirst(
self.repositoryplugins.paginatedItems(),
function (item) {
return plugin.url === item.archive;
}
);
self.multiInstallQueue.push(queued_plugin);
});
self.startMultiInstall();
};
self._forcedStdoutLine =
/You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function (line) {
@@ -1,6 +1,6 @@
{% macro pluginmanager_printing() %}
<div class="alert" data-bind="visible: !enableManagement()">
{{ _('Take note that all plugin management functionality is disabled while your printer is printing or paused.') }}
{{ _('Take note that most plugin management functionality is disabled while your printer is printing or paused.') }}
</div>
{% endmacro %}
@@ -225,7 +225,6 @@
</div>
<div class="modal-body">
<div class="full-sized-box">
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
{{ pluginmanager_throttled() }}
@@ -260,14 +259,23 @@
</div>
</div>
</div>
<div style="text-align: center">
<div style="margin: 0 auto;">
<span class="muted" style="margin-right: 8px;" data-bind="text: multiInstallQueue().length + ' selected'"></span>
<button class="btn btn-primary" data-bind="enable: multiInstallValid(), click: repoInstallSelectedConfirm, text: repoInstallSelectedButtonText()"></button>
</div>
</div>
<hr />
<div data-bind="visible: repositoryAvailable() && repositoryplugins.paginatedItems().length > 0">
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="foreach: repositoryplugins.paginatedItems">
<div class="entry">
<div class="row-fluid">
<div class="span12">
<label class="checkbox span1">
<input type="checkbox" data-bind="value: $data, checked: $parent.multiInstallQueue">
</label>
<div class="span11">
<div class="span3 pull-right">
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }, attr: {title: !$root.enableRepoInstall($data) ? gettext('Plugin install is disabled') : ''}"><span data-bind="text: $root.installButtonText($data)"></span></button>
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: $root.installButtonAction"><span data-bind="text: $root.installButtonText($data)"></span></button>
<div data-bind="visible: $data.disabled !== undefined" style="text-align: center"><small><a data-bind="attr: {href: page}" target="_blank">{{ _('"Why?"') }}</a></small></div>
</div>
<div>