137 lines
9.1 KiB
JavaScript
137 lines
9.1 KiB
JavaScript
import crypto from 'node:crypto';
|
|
import fs from 'node:fs';
|
|
import http from 'node:http';
|
|
import https from 'node:https';
|
|
import path from 'node:path';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const panelURL = process.env.SEA_PANEL_URL?.trim();
|
|
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
|
|
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
|
|
const activationHost = process.env.SEA_TEST_ACTIVATION_HOST?.trim();
|
|
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
|
|
if (!panelURL || !panelAPIKey || !consoleURL || !activationHost) process.exit(2);
|
|
if (!/^[A-Za-z0-9.-]+$/.test(activationHost)) throw new Error('SEA_TEST_ACTIVATION_HOST must be a host name or IP address');
|
|
const panelBase = new URL(panelURL);
|
|
const consoleBase = new URL(consoleURL);
|
|
const panelClient = panelBase.protocol === 'https:' ? https : http;
|
|
const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
|
|
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
|
|
const q = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
const suffix = crypto.randomBytes(6).toString('hex');
|
|
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
|
|
const workspace = path.dirname(scriptDirectory);
|
|
const packagePath = path.join(workspace, 'build', 'sea-vhost-linux-amd64.tar.gz');
|
|
if (!fs.statSync(packagePath).isFile()) throw new Error('deployment package is missing');
|
|
|
|
function authFields() {
|
|
const requestTime = Math.floor(Date.now() / 1000).toString();
|
|
return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) };
|
|
}
|
|
|
|
function panelForm(pathname, values) {
|
|
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
|
|
return new Promise((resolve, reject) => {
|
|
const request = panelClient.request(new URL(pathname, panelBase), {
|
|
method: 'POST', agent: panelAgent, timeout: 60_000,
|
|
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
|
|
}, (response) => {
|
|
let data = '';
|
|
response.setEncoding('utf8');
|
|
response.on('data', (chunk) => { data += chunk; });
|
|
response.on('end', () => {
|
|
if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`));
|
|
try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); }
|
|
});
|
|
});
|
|
request.on('timeout', () => request.destroy(new Error('panel request timed out')));
|
|
request.on('error', reject);
|
|
request.end(body);
|
|
});
|
|
}
|
|
|
|
async function runShell(name, shell, marker, attempts = 90) {
|
|
const task = await panelForm('/crontab', {
|
|
action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0',
|
|
sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost upgrade verification', save: '0', backupTo: 'localhost',
|
|
});
|
|
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task');
|
|
const taskID = Number(task.id);
|
|
try {
|
|
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
|
|
let log = '';
|
|
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
|
|
log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log;
|
|
if (log.includes(marker)) return log;
|
|
}
|
|
throw new Error(`temporary task failed: ${log.trim()}`);
|
|
} finally {
|
|
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
|
|
}
|
|
}
|
|
|
|
const snapshotShell = (marker) => [
|
|
'set -Eeuo pipefail',
|
|
'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')',
|
|
'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"',
|
|
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
|
|
'db_counts="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT CONCAT((SELECT COUNT(*) FROM tenants),\':\',(SELECT COUNT(*) FROM users),\':\',(SELECT COUNT(*) FROM projects),\':\',(SELECT COUNT(*) FROM sites),\':\',(SELECT COUNT(*) FROM ftp_accounts),\':\',(SELECT COUNT(*) FROM \\`databases\\`));")"',
|
|
'for service in sea-vhost-agent sea-vhost-panel-broker sea-vhost-api; do systemctl is-active --quiet "$service"; done',
|
|
'/www/server/nginx/sbin/nginx -t >/dev/null',
|
|
'test "$(curl --silent --show-error --fail --max-time 10 http://127.0.0.1:8080/healthz)" = \'{"status":"ok"}\'',
|
|
'for file in /etc/sea-vhost/sea-vhost.env /var/lib/sea-vhost/config.json /var/lib/sea-vhost-panel/credentials.json /var/lib/sea-vhost-panel/resources.json; do test -f "$file"; done',
|
|
// New releases may append a documented default without changing an
|
|
// operator's existing settings. Exclude only the newly introduced key;
|
|
// every pre-existing line, secret and custom override remains hash-checked.
|
|
'printf "env_sha=%s\\nconfig_sha=%s\\ncredentials_sha=%s\\nresources_sha=%s\\ndb_counts=%s\\n" "$(grep -Ev \'^(SEA_NODE_PID_ROOT|SEA_BACKUP_ROOT)=\' /etc/sea-vhost/sea-vhost.env | sha256sum | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost/config.json | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost-panel/credentials.json | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')" "$db_counts"',
|
|
`printf '%s\n' ${q(marker)}`,
|
|
].join('\n');
|
|
|
|
function parseSnapshot(log) {
|
|
const get = (name) => log.match(new RegExp(`(?:^|\\n)${name}=([^\\r\\n]+)`))?.[1];
|
|
const snapshot = Object.fromEntries(['env_sha', 'config_sha', 'credentials_sha', 'resources_sha', 'db_counts'].map((name) => [name, get(name)]));
|
|
if (Object.values(snapshot).some((value) => !value)) throw new Error('remote snapshot was incomplete');
|
|
return snapshot;
|
|
}
|
|
|
|
const beforeMarker = `upgrade-before-${suffix}`;
|
|
const before = parseSnapshot(await runShell(`Sea vHost upgrade before ${suffix}`, snapshotShell(beforeMarker), beforeMarker));
|
|
const child = spawnSync(process.execPath, [path.join(scriptDirectory, 'panel-stage.mjs'), packagePath, '--install', `--activate-http-test=${activationHost}`, '--diagnose'], {
|
|
cwd: workspace,
|
|
env: { ...process.env, SEA_PANEL_URL: panelURL, SEA_PANEL_API_KEY: panelAPIKey, SEA_PANEL_TLS_INSECURE: String(insecureTLS) },
|
|
encoding: 'utf8', timeout: 12 * 60_000, maxBuffer: 8 * 1024 * 1024,
|
|
});
|
|
const stageOutput = `${child.stdout ?? ''}\n${child.stderr ?? ''}`;
|
|
if (child.status !== 0 || !stageOutput.includes('Sea vHost install result: success') || !stageOutput.includes('Sea vHost test activation result: success') || !stageOutput.includes('Sea vHost diagnostic result: success')) {
|
|
throw new Error(`upgrade deployment failed: ${stageOutput.trim().slice(-3000)}`);
|
|
}
|
|
const afterMarker = `upgrade-after-${suffix}`;
|
|
const after = parseSnapshot(await runShell(`Sea vHost upgrade after ${suffix}`, snapshotShell(afterMarker), afterMarker));
|
|
for (const key of Object.keys(before)) {
|
|
if (before[key] !== after[key]) throw new Error(`upgrade changed preserved state: ${key}`);
|
|
}
|
|
const setupResponse = await fetch(new URL('/api/v1/setup/status', consoleBase), { signal: AbortSignal.timeout(15_000), redirect: 'manual' });
|
|
const setupPayload = await setupResponse.json();
|
|
if (setupResponse.status !== 200 || setupPayload?.required !== false) throw new Error('installed instance returned to setup mode after upgrade');
|
|
|
|
const stagedPath = stageOutput.match(/Staged package: (\/opt\/sea-vhost-staging-[A-Fa-f0-9]+-\d+)/)?.[1];
|
|
if (stagedPath && /^\/opt\/sea-vhost-staging-[a-f0-9]{12}-\d+$/.test(stagedPath)) {
|
|
try { await panelForm('/files', { action: 'DeleteDir', path: stagedPath }); } catch { /* staging cleanup is best effort */ }
|
|
}
|
|
|
|
console.log(JSON.stringify({ status: 'passed', packageSHA256: crypto.createHash('sha256').update(fs.readFileSync(packagePath)).digest('hex'), checks: {
|
|
preflightPassedInUpgradeMode: stageOutput.includes('Result: 0 failure(s)'),
|
|
installerCompleted: true,
|
|
servicesRestartedAndHealthy: true,
|
|
diagnosticsPassed: true,
|
|
environmentPreserved: before.env_sha === after.env_sha,
|
|
applicationConfigPreserved: before.config_sha === after.config_sha,
|
|
panelCredentialsPreserved: before.credentials_sha === after.credentials_sha,
|
|
managedResourceRegistryPreserved: before.resources_sha === after.resources_sha,
|
|
databaseObjectCountsPreserved: before.db_counts === after.db_counts,
|
|
setupRemainedClosed: true,
|
|
}, databaseObjectCounts: after.db_counts }, null, 2));
|