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/update.js

381 lines
16 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const API_BASE = '/api/v1/admin/update';
const csrfToken = typeof window.ADMIN_CSRF_TOKEN === 'string' ? window.ADMIN_CSRF_TOKEN : '';
const terminalStatuses = new Set(['succeeded', 'failed', 'blocked']);
const commitPattern = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
const state = {
checkedCommits: null,
knownLastJobId: '',
pollingJobId: '',
pollingGeneration: 0,
updateConfigured: false,
updateAvailable: false,
maintenanceBlocked: false,
};
function element(id) {
return document.getElementById(id);
}
function text(id, value) {
const target = element(id);
if (target) target.textContent = value === null || value === undefined || value === '' ? '—' : String(value);
}
function setPageStatus(message, kind = 'info') {
const target = element('update-page-status');
if (!target) return;
target.textContent = String(message);
target.className = `alert alert-${kind} cloud-admin-notice`;
}
function errorMessage(payload, fallback) {
if (payload && typeof payload.detail === 'string' && payload.detail.trim()) return payload.detail.trim();
if (payload && typeof payload.error === 'string' && payload.error.trim()) return payload.error.trim();
return fallback;
}
async function api(path, options = {}) {
const method = String(options.method || 'GET').toUpperCase();
const headers = { Accept: 'application/json' };
const request = {
method,
headers,
credentials: 'same-origin',
cache: 'no-store',
};
if (method !== 'GET') {
if (!csrfToken) throw new Error('页面安全令牌缺失,请刷新页面后重试。');
headers['Content-Type'] = 'application/json';
headers['X-Admin-CSRF-Token'] = csrfToken;
request.body = JSON.stringify(options.body || {});
}
let response;
try {
response = await fetch(`${API_BASE}${path}`, request);
} catch (_error) {
throw new Error('暂时无法连接更新服务。');
}
const raw = await response.text();
let payload = {};
if (raw) {
try {
payload = JSON.parse(raw);
} catch (_error) {
throw new Error('更新服务返回了无法识别的响应。');
}
}
if (!response.ok) {
throw new Error(errorMessage(payload, `更新请求失败(HTTP ${response.status})。`));
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
throw new Error('更新服务返回了无法识别的响应。');
}
return payload;
}
function validJobId(value) {
return typeof value === 'string' && /^[A-Za-z0-9_-]{16,64}$/.test(value);
}
function secureCredentialTransport() {
if (window.location.protocol === 'https:') return true;
return ['localhost', '127.0.0.1', '::1', '[::1]'].includes(window.location.hostname);
}
function invalidateCheck(message = '尚未检查') {
state.checkedCommits = null;
state.updateAvailable = false;
text('update-check-status', message);
text('update-checked-current', '—');
text('update-checked-remote', '—');
const apply = element('update-apply');
if (apply) apply.disabled = true;
}
function renderSettings(settings) {
text('update-repository', settings.repository);
text('update-branch', settings.branch);
text('update-current-commit', settings.current_commit);
let checkout = settings.checkout_ready === true ? '仓库可更新' : '仓库尚未就绪';
checkout += settings.token_configured === true ? ';令牌已配置' : ';令牌未配置';
if (typeof settings.checkout_error === 'string' && settings.checkout_error) checkout += `;${settings.checkout_error}`;
text('update-checkout-state', checkout);
state.knownLastJobId = validJobId(settings.last_job_id) ? settings.last_job_id : '';
state.updateConfigured = settings.token_configured === true && settings.checkout_ready === true;
const check = element('update-check');
if (check && !state.pollingJobId) {
check.disabled = state.maintenanceBlocked || !state.updateConfigured;
}
}
function setBusy(busy) {
for (const id of ['update-settings-save', 'update-check', 'update-apply']) {
const target = element(id);
if (!target) continue;
if (id === 'update-check') {
target.disabled = busy || state.maintenanceBlocked || !state.updateConfigured;
} else {
target.disabled = busy || state.maintenanceBlocked
|| (id === 'update-apply'
&& (state.checkedCommits === null || !state.updateAvailable));
}
}
}
function renderJob(job) {
text('update-job-id', job.job_id);
text('update-job-status', job.status);
text('update-job-phase', job.phase);
let result = '';
if (typeof job.error === 'string' && job.error) result = job.error;
else if (typeof job.new_commit === 'string' && job.new_commit) result = `已更新至 ${job.new_commit}`;
else if (job.status === 'succeeded') result = '更新完成';
else if (job.status === 'blocked') result = '维护锁已保留,请通过 SSH 人工恢复';
else if (job.status === 'failed') result = '更新失败,请查看服务日志';
else result = '任务执行中';
if (typeof job.rollback_ref === 'string' && job.rollback_ref) {
result += `;人工恢复回滚引用 ${job.rollback_ref}`;
}
text('update-job-result', result);
}
function delay(milliseconds) {
return new Promise((resolve) => window.setTimeout(resolve, milliseconds));
}
async function pollJob(jobId) {
if (!validJobId(jobId)) {
setPageStatus('更新服务返回了无效的任务编号。', 'danger');
return;
}
state.pollingJobId = jobId;
const generation = ++state.pollingGeneration;
let transientFailures = 0;
setBusy(true);
while (state.pollingGeneration === generation && state.pollingJobId === jobId) {
try {
// After apply, polling is deliberately GET-only. A restart must
// never cause the mutation request to be replayed.
const job = await api(`/jobs/${encodeURIComponent(jobId)}`, { method: 'GET' });
transientFailures = 0;
renderJob(job);
if (terminalStatuses.has(job.status)) {
state.pollingJobId = '';
if (job.status === 'blocked') {
state.maintenanceBlocked = true;
invalidateCheck('更新被阻断,维护锁已保留');
setBusy(true);
const recovery = errorMessage(
job,
'代码或数据库状态尚未确认,请通过 SSH 人工恢复。'
);
setPageStatus(
`${recovery} 若任务在数据库迁移期间中断,仅回退源码不会解除维护锁;必须人工完成并验证迁移与服务兼容性。`,
'danger'
);
} else if (job.status === 'succeeded') {
state.maintenanceBlocked = false;
setBusy(false);
invalidateCheck('更新已完成,请重新检查后再执行其他更新');
setPageStatus('在线更新已完成。', 'success');
} else {
state.maintenanceBlocked = false;
setBusy(false);
setPageStatus(errorMessage(job, '在线更新失败,请核对任务结果和服务日志。'), 'danger');
}
try {
renderSettings(await api('/settings', { method: 'GET' }));
} catch (_error) {
// The durable task result remains visible if settings refresh fails.
}
if (job.status === 'blocked') setBusy(true);
return;
}
if (!['queued', 'running'].includes(job.status)) {
throw new Error('更新任务状态无效。');
}
setPageStatus('更新任务正在执行,请勿关闭页面或重复提交。', 'info');
await delay(2000);
} catch (error) {
transientFailures += 1;
if (transientFailures > 30) {
state.pollingJobId = '';
// Keep mutating controls locked until a page refresh can
// recover the durable job identifier from settings.
setBusy(true);
setPageStatus(`${error.message} 请稍后刷新页面继续查看任务。`, 'danger');
return;
}
const seconds = Math.min(10, Math.max(2, transientFailures));
setPageStatus(`服务可能正在重启,${seconds} 秒后继续读取任务(第 ${transientFailures} 次重试)。`, 'warning');
await delay(seconds * 1000);
}
}
}
async function loadSettings() {
const settings = await api('/settings', { method: 'GET' });
renderSettings(settings);
if (validJobId(settings.active_job_id)) {
void pollJob(settings.active_job_id);
} else if (validJobId(settings.last_job_id)) {
try {
renderJob(await api(`/jobs/${encodeURIComponent(settings.last_job_id)}`, { method: 'GET' }));
} catch (_error) {
// A stale last-job pointer must not make the settings page unusable.
}
}
return settings;
}
async function saveSettings(event) {
event.preventDefault();
if (state.pollingJobId || state.maintenanceBlocked) return;
const tokenInput = element('update-access-token');
const clearInput = element('update-clear-token');
const token = tokenInput ? tokenInput.value : '';
const clearToken = clearInput ? clearInput.checked : false;
if (token !== '' && clearToken) {
setPageStatus('不能同时填写新令牌并选择清除令牌。', 'danger');
return;
}
if (token !== '' && !secureCredentialTransport()) {
setPageStatus('访问令牌只能通过 HTTPS(或本机回环地址)提交。', 'danger');
return;
}
// Sending an explicit blank value means "preserve" in the engine contract.
const body = clearToken ? { clear_token: true } : { access_token: token };
setBusy(true);
invalidateCheck('令牌设置已变化,请重新检查');
try {
const settings = await api('/settings', { method: 'PUT', body });
renderSettings(settings);
setPageStatus(clearToken ? '已清除访问令牌。' : (token === '' ? '已保留原访问令牌。' : '访问令牌已安全保存。'), 'success');
} catch (error) {
setPageStatus(error.message, 'danger');
} finally {
// The credential is never copied into storage or restored from a response.
if (tokenInput) tokenInput.value = '';
if (clearInput) clearInput.checked = false;
setBusy(false);
}
}
async function checkForUpdate() {
if (state.pollingJobId || state.maintenanceBlocked) return;
if (!state.updateConfigured) {
setPageStatus('请先配置访问令牌并修复仓库检出状态。', 'warning');
return;
}
setBusy(true);
invalidateCheck('正在检查…');
try {
const result = await api('/check', { method: 'POST', body: {} });
if (!commitPattern.test(result.current_commit) || !commitPattern.test(result.remote_commit)
|| !['current', 'update_available'].includes(result.status)) {
throw new Error('更新检查结果无效。');
}
// Pin both commits in memory. Apply sends exactly this pair and never
// derives either value from editable DOM content.
state.checkedCommits = Object.freeze({
expected_current_commit: result.current_commit,
expected_remote_commit: result.remote_commit,
});
state.updateAvailable = result.status === 'update_available';
text('update-repository', result.repository);
text('update-branch', result.branch);
text('update-current-commit', result.current_commit);
text('update-checked-current', result.current_commit);
text('update-checked-remote', result.remote_commit);
text('update-check-status', result.status === 'update_available' ? '发现可用更新' : '当前已是最新版本');
const apply = element('update-apply');
if (apply) apply.disabled = result.status !== 'update_available';
setPageStatus(result.status === 'update_available' ? '检查完成,可以执行更新。' : '当前已是最新版本。', 'success');
} catch (error) {
invalidateCheck('检查失败');
setPageStatus(error.message, 'danger');
} finally {
setBusy(false);
}
}
async function recoverJobAfterApply(previousLastJobId) {
for (let attempt = 1; attempt <= 30; attempt += 1) {
try {
// Recovery is read-only: never replay the apply request after an
// interrupted response from services that may be restarting.
const settings = await api('/settings', { method: 'GET' });
const recoveredJobId = validJobId(settings.active_job_id)
? settings.active_job_id
: (validJobId(settings.last_job_id) && settings.last_job_id !== previousLastJobId
? settings.last_job_id : '');
renderSettings(settings);
return recoveredJobId;
} catch (_error) {
if (attempt === 30) return '';
const seconds = Math.min(10, Math.max(2, attempt));
setPageStatus(`执行响应中断,正在只读恢复任务;${seconds} 秒后重试(第 ${attempt} 次)。`, 'warning');
await delay(seconds * 1000);
}
}
return '';
}
async function applyUpdate() {
if (state.pollingJobId || state.maintenanceBlocked || !state.updateAvailable
|| state.checkedCommits === null) return;
const confirmed = window.confirm(
'在线更新仅快进应用代码,不会安装 Composer/Python 依赖或修改 systemd 配置。它会暂停面板服务、切换代码、执行数据库初始化或迁移,并重新启动现有服务。依赖或部署文件变更必须通过 SSH 升级。确定继续吗?'
);
if (!confirmed) return;
const pinned = state.checkedCommits;
const previousLastJobId = state.knownLastJobId;
state.checkedCommits = null;
state.updateAvailable = false;
setBusy(true);
try {
// This is the sole mutating request in the apply flow. It is never retried.
const job = await api('/apply', { method: 'POST', body: pinned });
if (!validJobId(job.job_id) || !['queued', 'running'].includes(job.status)) {
throw new Error('更新服务返回了无效的任务。');
}
renderJob(job);
setPageStatus('更新任务已提交,正在等待独立更新服务。', 'info');
await pollJob(job.job_id);
} catch (error) {
// The POST is never replayed. If its response was lost while services
// restarted, recover the newly durable job using GET requests only.
const recoveredJobId = await recoverJobAfterApply(previousLastJobId);
if (recoveredJobId) {
setPageStatus('已恢复更新任务,继续读取执行进度。', 'warning');
await pollJob(recoveredJobId);
return;
}
// The request outcome is ambiguous. Keep every mutation disabled;
// refreshing the page is the safe recovery path.
setBusy(true);
invalidateCheck('执行请求结果未确认');
setPageStatus(`执行请求结果未确认,请勿重复提交。${error.message} 请稍后刷新页面恢复任务状态。`, 'danger');
}
}
function initialize() {
const settingsForm = element('update-settings-form');
const checkButton = element('update-check');
const applyButton = element('update-apply');
if (settingsForm) settingsForm.addEventListener('submit', saveSettings);
if (checkButton) checkButton.addEventListener('click', checkForUpdate);
if (applyButton) applyButton.addEventListener('click', applyUpdate);
loadSettings()
.then(() => {
if (!state.pollingJobId) setPageStatus('更新配置已载入。', 'info');
})
.catch((error) => setPageStatus(error.message, 'danger'));
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initialize);
else initialize();