Backup works, incl management UI

This commit is contained in:
Gina Häußge committed 2018-08-06 13:35:02 +02:00
1 parent 249b3f442b
commit 6251031d6e
5 files changed
+218 -29

No files matched your search

+51 -18
View File
@@ -8,7 +8,7 @@ import octoprint.plugin
from octoprint.settings import default_settings
from octoprint.plugin.core import FolderOrigin
from octoprint.server import admin_permission
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.util import is_hidden_path
@@ -35,12 +35,6 @@ import json
"""
TODO:
* Backup:
* UI to select things to backup (timelapse? uploads?) and start the backup
* perform backup
x sanity check of available space (must be at least what the selected parts currently consume unzipped)
x zip stuff to disk, incl. plugin list as json
* trigger download in browser
* Restore:
* UI to upload a backup zip
* tornado endpoint to stream the upload
@@ -70,12 +64,15 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
##~~ AssetPlugin
def get_assets(self):
return dict(js=["js/backup.js"])
return dict(js=["js/backup.js"],
css=["css/backup.css"],
less=["less/backup.less"])
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
@admin_permission.require(403)
@restricted_access
def get_backups(self):
# TODO add caching
backups = []
@@ -85,37 +82,69 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
backups.append(dict(name=entry.name,
date=entry.stat().st_mtime,
size=entry.stat().st_size,
url=flask.url_for("index") + "downloads/backup/" + entry.name))
return flask.jsonify(backups=backups)
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
return flask.jsonify(backups=backups,
in_progress=len(self._in_progress) > 0)
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
@admin_permission.require(403)
@restricted_access
def create_backup(self):
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
data = flask.request.json
exclude = data.get("exclude", [])
thread = threading.Thread(target=self._create_backup,
args=(backup_file,),
kwargs=dict(exclude=["timelapse",
"timelapse_tmp",
"uploads"]))
kwargs=dict(exclude=exclude))
thread.daemon = True
thread.start()
response = flask.jsonify(started=True)
response.headers["Location"] = flask.url_for("index") + "downloads/backup/" + backup_file
response.headers["Location"] = flask.url_for("index") + "plugin/backup/download/" + backup_file
response.status_code = 201
return response
@octoprint.plugin.BlueprintPlugin.route("/backup/<backup>", methods=["DELETE"])
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
@admin_permission.require(403)
def delete_backup(self, backup):
pass
@restricted_access
def delete_backup(self, filename):
backup_folder = self.get_plugin_data_folder()
full_path = os.path.realpath(os.path.join(backup_folder, filename))
if full_path.startswith(backup_folder) \
and os.path.exists(full_path) \
and not is_hidden_path(full_path):
try:
os.remove(full_path)
except:
self._logger.exception("Could not delete {}".format(filename))
raise
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
@admin_permission.require(403)
@restricted_access
def perform_restore(self):
pass
##~~ tornado hook
def route_hook(self, *args, **kwargs):
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
from octoprint.util import is_hidden_path
from octoprint.server import app
from octoprint.server.util.tornado import access_validation_factory
from octoprint.server.util.flask import admin_validator
return [
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
as_attachment=True,
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
status_code=404),
access_validation=access_validation_factory(app, admin_validator)))
]
##~~ helpers
def _get_disk_size(self, path):
@@ -155,7 +184,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
self._in_progress.append(name)
self._send_client_message("backup_started", payload=dict(name=name))
self._logger.info("Creating backup zip at {}...".format(temporary_path))
self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path,
",".join(exclude) if len(exclude) else "-"))
with zipfile.ZipFile(temporary_path, "w", compression) as zip:
def add_to_zip(source, target, ignored=None):
@@ -228,3 +258,6 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin you will no long
"& restore your OctoPrint settings and data.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = BackupPlugin()
__plugin_hooks__ = {
"octoprint.server.http.routes": __plugin_implementation__.route_hook
}
@@ -0,0 +1 @@
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:50px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}
@@ -22,16 +22,20 @@
return this.get(false, opts);
};
OctoPrintBackupClient.prototype.createBackup = function(excludes, opts) {
excludes = excludes || [];
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
exclude = exclude || [];
var data = {
excludes: excludes
exclude: exclude
};
return this.base.postJson(this.url + "backup", data, opts);
};
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
return this.base.delete(this.url + "backup/" + backup, opts);
};
OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient);
return OctoPrintBackupClient;
});
@@ -58,8 +62,11 @@ $(function() {
"date",
[],
[],
0
10
);
self.markedForBackupDeletion = ko.observableArray([]);
self.excludeFromBackup = ko.observableArray([]);
self.backupInProgress = ko.observable(false);
self.requestData = function() {
OctoPrint.plugins.backup.get()
@@ -71,7 +78,42 @@ $(function() {
};
self.createBackup = function() {
OctoPrint.plugins.backup.createBackup();
var excluded = self.excludeFromBackup();
OctoPrint.plugins.backup.createBackup(excluded)
.done(function() {
self.excludeFromBackup([]);
})
};
self.removeBackup = function(backup) {
OctoPrint.plugins.backup.deleteBackup(backup)
.done(function() {
self.requestData();
})
};
self.markFilesOnPage = function() {
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
};
self.markAllFiles = function() {
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
};
self.clearMarkedFiles = function() {
self.markedForBackupDeletion.removeAll();
};
self.removeMarkedFiles = function() {
var perform = function() {
self._bulkRemove(self.markedForBackupDeletion())
.done(function() {
self.markedForBackupDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
perform);
};
self.onSettingsShown = function() {
@@ -83,8 +125,54 @@ $(function() {
if (data.type === "backup_done") {
self.requestData();
self.backupInProgress(false);
} else if (data.type === "backup_started") {
self.backupInProgress(true);
}
}
};
self._bulkRemove = function(files) {
var title, message, handler;
title = gettext("Deleting backups");
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
handler = function(filename) {
return OctoPrint.plugins.backup.deleteBackup(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
};
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: message,
max: files.length,
output: true
};
showProgressModal(options, promise);
var requests = [];
_.each(files, function(filename) {
var request = handler(filename);
requests.push(request)
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -0,0 +1,20 @@
#settings_plugin_backup_backup_table {
.settings_plugin_backup_name {
}
.settings_plugin_backup_actions {
width: 50px;
text-align: center;
a {
color: black;
}
}
.settings_plugin_backup_date {
width: 200px;
text-align: right;
}
.settings_plugin_backup_size {
width: 100px;
text-align: right;
}
}
@@ -1,5 +1,3 @@
<h3>{{ _('Backup & Restore') }}</h3>
<form class="form-horizontal">
<ul class="nav nav-pills">
<li class="active"><a href="#settings_plugin_backup_backup" data-toggle="tab">{{ _('Backup') }}</a></li>
@@ -8,9 +6,48 @@
<div class="tab-content">
<div id="settings_plugin_backup_backup" class="tab-pane active">
<table class="table table-condensed table-hover">
<h4>{{ _('Create backup') }}</h4>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'timelapse', checked: excludeFromBackup"> {{ _('Exclude timelapses from backup') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress(), click: createBackup"><i class="fa fa-spinner fa-spin" data-bind="visible: backupInProgress"></i> {{ _('Create backup now') }}</button>
</div>
</div>
<h4>{{ _('Existing backups') }}</h4>
<div class="pull-left">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
</ul>
</div>
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForBackupDeletion().length > 0">{{ _('Delete selected') }}</button>
</div>
<table class="table table-condensed table-hover" id="settings_plugin_backup_backup_table">
<thead>
<tr>
<th class="timelapse_unrendered_checkbox"></th>
<th class="settings_plugin_backup_name">{{ _('Name') }}</th>
<th class="settings_plugin_backup_date">{{ _('Date') }}</th>
<th class="settings_plugin_backup_size">{{ _('Size') }}</th>
@@ -19,6 +56,7 @@
</thead>
<tbody data-bind="foreach: backups.paginatedItems">
<tr>
<td class="timelapse_unrendered_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForBackupDeletion"></td>
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
@@ -26,8 +64,17 @@
</tr>
</tbody>
</table>
<button class="btn btn-primary" data-bind="click: createBackup">{{ _('Create backup now') }}</button>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: backups.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: backups.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: backups.pages">
<li data-bind="css: { active: $data.number === $root.backups.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.backups.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: backups.currentPage() === backups.lastPage()}"><a href="javascript:void(0)" data-bind="click: backups.nextPage">»</a></li>
</ul>
</div>
</div>
<div id="settings_plugin_backup_restore" class="tab-pane">