You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-object-storage.js

358 lines
17 KiB
JavaScript

(function () {
'use strict';
var runtime = window.VenixAdminRequestRuntime.create();
function request(url, payload) {
return runtime.mutate(url, {
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body: payload,
response: 'json',
}).then(function (result) {
if (Number(result && result.ret) !== 1) {
throw new Error(result && result.msg || '请求失败');
}
return result;
});
}
function showNotice(node, message, ok, uncertain) {
if (!node) return;
node.textContent = message;
node.className = node.classList && node.classList.contains('os-row-notice')
? 'os-row-notice is-show ' + (ok ? 'is-ok' : 'is-error')
: 'os-notice is-show ' + (ok ? 'is-ok' : 'is-error');
if (uncertain) node.setAttribute('data-effect-unknown', '1');
else node.removeAttribute('data-effect-unknown');
}
function confirmAction(options) {
return window.VenixAdminDangerDialog.confirm({
title: options.title,
message: options.message,
confirmText: options.confirmLabel,
tone: options.tone === 'primary' ? 'warning' : 'danger',
});
}
function backendId(card) {
var value = String(card && card.getAttribute('data-backend-id') || '');
return /^\d+$/.test(value) ? value : '';
}
function backendRevision(card) {
return Math.max(0, Number(card && card.getAttribute('data-revision')) || 0);
}
function setBackendBusy(card, busy) {
if (!card) return;
card.classList.toggle('is-busy', busy);
card.querySelectorAll('[data-os-edit], [data-os-action]').forEach(function (button) {
if (busy) {
button.dataset.wasDisabled = button.disabled ? '1' : '0';
button.disabled = true;
} else if (button.dataset.wasDisabled === '0') {
button.disabled = false;
}
});
}
function initializeBackendActions() {
var actions = {
test: { progress: '正在执行只读连接验证...', success: '连接验证完成。' },
activate: { progress: '正在启用新对象写入...', success: '后端已启用。' },
resume: { progress: '正在恢复新对象写入...', success: '后端已恢复。' },
drain: {
progress: '正在将后端切换为排空...', success: '后端已排空。',
title: '排空对象存储后端',
message: '排空后不再接收新对象;历史读取、核对和精确删除仍继续。',
confirmLabel: '确认排空', tone: 'primary',
},
disable: {
progress: '正在停用对象存储后端...', success: '后端已停用。',
title: '停用对象存储后端',
message: '停用不会删除加密凭据或历史对象身份,但该后端不会参与新写入。',
confirmLabel: '确认停用', tone: 'danger',
},
};
document.querySelectorAll('[data-os-backend]').forEach(function (card) {
card.querySelectorAll('[data-os-action]').forEach(function (button) {
button.addEventListener('click', function () {
var action = String(button.getAttribute('data-os-action') || '');
var config = actions[action];
var id = backendId(card);
if (!config || !id || button.disabled || card.getAttribute('data-effect-unknown') === '1') return;
var run = function () {
var notice = card.querySelector('.os-row-notice');
setBackendBusy(card, true);
showNotice(notice, config.progress, true, false);
request('/admin/object-storage/backends/' + encodeURIComponent(id) + '/' + action, {
expected_revision: backendRevision(card),
}).then(function (result) {
showNotice(notice, result.msg || config.success, true, false);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
var unknown = error && error.mutationMayHaveApplied === true;
if (unknown) {
card.setAttribute('data-effect-unknown', '1');
showNotice(notice, '操作结果待核对,请勿再次提交。请刷新后检查该后端状态。', false, true);
return;
}
showNotice(notice, error && error.message || '请求失败', false, false);
setBackendBusy(card, false);
});
};
if (!config.title) {
run();
return;
}
confirmAction(config).then(function (confirmed) {
if (confirmed) run();
});
});
});
});
}
function initializeConfigurationDrawer() {
var drawer = document.getElementById('osConfigDrawer');
var form = document.getElementById('objectStorageForm');
var addButton = document.getElementById('osAddBackend');
if (!drawer || !form) return;
var title = document.getElementById('osDrawerTitle');
var description = document.getElementById('osDrawerDescription');
var notice = document.getElementById('osNotice');
var saveButton = document.getElementById('osSave');
var replaceWrap = document.getElementById('osReplaceCredentialsWrap');
var replaceCredentials = document.getElementById('osReplaceCredentials');
var credentialFields = document.getElementById('osCredentialFields');
var credentialHint = document.getElementById('osCredentialHint');
var dialog = drawer.querySelector('[role="dialog"]');
var previousFocus = null;
var canManage = form.dataset.canManage === '1';
function field(name) { return form.elements[name]; }
function setCredentials(visible, required) {
credentialFields.hidden = !visible;
field('access_key_id').required = required;
field('secret_access_key').required = required;
if (!visible) {
field('access_key_id').value = '';
field('secret_access_key').value = '';
}
}
function open(card) {
if (!canManage) return;
var editing = !!card;
previousFocus = document.activeElement;
form.reset();
field('backend_id').value = editing ? backendId(card) : '';
field('expected_revision').value = editing ? String(backendRevision(card)) : '0';
field('name').value = editing ? card.dataset.name || '' : '';
field('endpoint').value = editing ? card.dataset.endpoint || '' : '';
field('region').value = editing ? card.dataset.region || '' : '';
field('bucket').value = editing ? card.dataset.bucket || '' : '';
field('prefix').value = editing ? card.dataset.prefix || '' : '';
field('path_style').value = editing ? card.dataset.pathStyle || 'false' : 'true';
field('failure_domain').value = editing ? card.dataset.failureDomain || '' : '';
field('write_priority').value = editing ? card.dataset.writePriority || '100' : '100';
title.textContent = editing ? '编辑对象存储后端' : '添加对象存储后端';
description.textContent = editing
? '保存后当前验证会失效;历史对象身份不会被页面重写。'
: '创建后先验证连接;验证成功不会自动启用写入。';
saveButton.textContent = editing ? '保存后端配置' : '创建后端';
replaceWrap.hidden = !editing;
replaceCredentials.checked = false;
credentialHint.textContent = editing
? '凭据已加密保存;只有显式打开替换开关才会提交新凭据。'
: '首次创建必须填写完整凭据。';
setCredentials(!editing, !editing);
showNotice(notice, '', true, false);
notice.className = 'os-notice';
drawer.hidden = false;
document.body.classList.add('os-drawer-open');
if (dialog) dialog.focus({ preventScroll: true });
}
function close() {
if (drawer.hidden) return;
drawer.hidden = true;
document.body.classList.remove('os-drawer-open');
if (previousFocus && typeof previousFocus.focus === 'function') previousFocus.focus({ preventScroll: true });
previousFocus = null;
}
if (addButton) addButton.addEventListener('click', function () { if (!addButton.disabled) open(null); });
document.querySelectorAll('[data-os-backend]').forEach(function (card) {
var edit = card.querySelector('[data-os-edit]');
if (edit) edit.addEventListener('click', function () { if (!edit.disabled) open(card); });
});
drawer.querySelectorAll('[data-os-drawer-close]').forEach(function (button) {
button.addEventListener('click', close);
});
document.addEventListener('keydown', function (event) {
if (event.key === 'Escape' && !drawer.hidden) close();
});
replaceCredentials.addEventListener('change', function () {
setCredentials(replaceCredentials.checked, replaceCredentials.checked);
if (replaceCredentials.checked) field('access_key_id').focus();
});
form.addEventListener('submit', function (event) {
event.preventDefault();
if (!canManage || saveButton.disabled) return;
var id = String(field('backend_id').value || '');
var editing = /^\d+$/.test(id);
var payload = {
name: String(field('name').value || ''),
endpoint: String(field('endpoint').value || ''),
region: String(field('region').value || ''),
bucket: String(field('bucket').value || ''),
prefix: String(field('prefix').value || ''),
path_style: String(field('path_style').value || ''),
failure_domain: String(field('failure_domain').value || ''),
write_priority: String(field('write_priority').value || ''),
access_key_id: String(field('access_key_id').value || ''),
secret_access_key: String(field('secret_access_key').value || ''),
};
if (editing) payload.expected_revision = String(field('expected_revision').value || '');
saveButton.disabled = true;
showNotice(notice, '正在加密并保存对象存储后端...', true, false);
request(editing
? '/admin/object-storage/backends/' + encodeURIComponent(id) + '/config'
: '/admin/object-storage/backends', payload).then(function (result) {
field('access_key_id').value = '';
field('secret_access_key').value = '';
showNotice(notice, result.msg, true, false);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
var unknown = error && error.mutationMayHaveApplied === true;
showNotice(notice, unknown
? '保存结果待核对,请勿再次提交。请刷新后检查后端目录。'
: error && error.message || '请求失败', false, unknown);
if (!unknown) saveButton.disabled = false;
});
});
}
function formatBytes(value) {
var bytes = Math.max(0, Number(value) || 0);
var units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
var index = 0;
while (bytes >= 1024 && index < units.length - 1) { bytes /= 1024; index += 1; }
return (index === 0 ? String(Math.round(bytes)) : bytes.toFixed(bytes >= 10 ? 1 : 2)) + ' ' + units[index];
}
function initializeCleanupDebt() {
document.querySelectorAll('.os-byte-value').forEach(function (node) {
node.textContent = formatBytes(node.getAttribute('data-bytes'));
});
var refresh = document.getElementById('osDebtRefresh');
if (refresh) refresh.addEventListener('click', function () { window.location.reload(); });
var notice = document.getElementById('osDebtNotice');
document.querySelectorAll('.os-cleanup-retry').forEach(function (button) {
button.addEventListener('click', function () {
var id = String(button.getAttribute('data-backup-id') || '');
if (!/^\d+$/.test(id) || button.disabled) return;
confirmAction({ title: '重新开启清理核对', message: '系统先检查准确对象身份并等待第二次稳定证据;不会直接重放原删除请求。', confirmLabel: '开始核对', tone: 'primary' }).then(function (confirmed) {
if (!confirmed) return;
button.disabled = true;
showNotice(notice, '正在核对准确对象版本...', true, false);
request('/admin/object-storage/cleanup-debts/' + encodeURIComponent(id) + '/retry', {}).then(function (result) {
showNotice(notice, result.msg, true, false);
window.setTimeout(function () { window.location.reload(); }, 700);
}).catch(function (error) {
var unknown = error && error.mutationMayHaveApplied === true;
showNotice(notice, unknown ? '核对结果无法确认,请勿重复提交。' : error.message || '请求失败', false, unknown);
if (!unknown) button.disabled = false;
});
});
});
});
}
function initializeReplicaAttention() {
var refresh = document.getElementById('osAttentionRefresh');
if (refresh) refresh.addEventListener('click', function () {
window.location.hash = 'protection';
window.location.reload();
});
var notice = document.getElementById('osAttentionNotice');
document.querySelectorAll('.os-attention-retry').forEach(function (button) {
button.addEventListener('click', function () {
var operationId = String(button.getAttribute('data-operation-id') || '');
var operationKind = String(button.getAttribute('data-operation-kind') || 'copy');
if (!/^[a-f0-9]{32}$/.test(operationId) || button.disabled) return;
var finalization = operationKind === 'finalize';
var primary = operationKind === 'publish';
confirmAction({
title: finalization ? '重新执行目录最终化'
: (primary ? '重新核对主副本发布' : '重新核对副本复制'),
message: finalization
? '本次只重开已经完成双副本保护的本地目录最终化,不会上传、覆盖或删除对象存储内容。'
: '请先在对象存储提供商确认已清理多余的 multipart 会话。本次点击只重开原操作的只读核对,不会终止会话或直接新建上传;只有对象与会话的无效果证据稳定后才会沿用原操作安全重试。',
confirmLabel: finalization ? '重新最终化' : '开始核对',
tone: 'primary',
}).then(function (confirmed) {
if (!confirmed) return;
button.disabled = true;
showNotice(notice, finalization
? '正在重新打开本地目录最终化…'
: '正在重开原操作的只读核对…', true, false);
request('/admin/object-storage/replica-attention/'
+ encodeURIComponent(operationId) + '/retry', {
operation_kind: operationKind,
}).then(function (result) {
showNotice(notice, result.msg, true, false);
window.setTimeout(function () {
window.location.hash = 'protection';
window.location.reload();
}, 700);
}).catch(function (error) {
var unknown = error && error.mutationMayHaveApplied === true;
showNotice(notice, unknown
? '重开结果无法确认,请刷新后查看原操作,不要重复提交。'
: error && error.message || '重新核对失败。', false, unknown);
if (!unknown) button.disabled = false;
});
});
});
});
}
function initializeTabs() {
var tabs = Array.prototype.slice.call(document.querySelectorAll('[data-os-tab]'));
var panels = Array.prototype.slice.call(document.querySelectorAll('[data-os-panel]'));
function activate(name, updateLocation) {
var allowed = ['backends', 'protection', 'cleanup'];
var selected = allowed.indexOf(name) === -1 ? 'backends' : name;
tabs.forEach(function (tab) {
var active = tab.getAttribute('data-os-tab') === selected;
tab.classList.toggle('is-active', active);
tab.setAttribute('aria-selected', active ? 'true' : 'false');
tab.tabIndex = active ? 0 : -1;
});
panels.forEach(function (panel) {
var active = panel.getAttribute('data-os-panel') === selected;
panel.classList.toggle('is-active', active);
panel.hidden = !active;
});
if (updateLocation && window.history && window.history.replaceState) {
window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search + '#' + selected);
}
}
tabs.forEach(function (tab) { tab.addEventListener('click', function () { activate(tab.getAttribute('data-os-tab'), true); }); });
activate(String(window.location.hash || '').replace(/^#/, ''), false);
}
function initialize() {
initializeTabs();
initializeConfigurationDrawer();
initializeBackendActions();
initializeCleanupDebt();
initializeReplicaAttention();
}
initialize();
}());