feat: import Sea vHost single-server testing release

This commit is contained in:
canglan committed 2026-10-30 08:39:10 +08:00
commit 248badd33e
441 files changed
+63221

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey) process.exit(2);
const base = new URL(panelURL);
const client = base.protocol === 'https:' ? https : http;
const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
const suffix = `${new Date().toISOString().replaceAll(/[-:.TZ]/g, '').slice(0, 14)}-${crypto.randomBytes(3).toString('hex')}`;
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 = client.request(new URL(pathname, base), {
method: 'POST', agent, 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(shell, marker) {
const task = await panelForm('/crontab', {
action: 'AddCrontab', name: `Sea vHost reinstall backup ${suffix}`, 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 pre-reinstall backup', save: '0', backupTo: 'localhost',
});
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary backup task');
const taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id');
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let lastLog = '';
for (let attempt = 0; attempt < 240; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
lastLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : lastLog;
if (lastLog.includes(marker)) return lastLog;
}
throw new Error(`backup task did not complete: ${lastLog.trim()}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const marker = `sea-vhost-reinstall-backup-complete-${suffix}`;
const shell = [
'set -Eeuo pipefail',
`backup_dir=/var/backups/sea-vhost/reinstall-${suffix}`,
'case "$backup_dir" in /var/backups/sea-vhost/reinstall-[0-9]*-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]) ;; *) exit 1 ;; esac',
'test ! -e "$backup_dir"; install -d -o root -g root -m 0700 /var/backups/sea-vhost "$backup_dir"',
'test -f /var/lib/sea-vhost/config.json',
'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)"; dump_bin="$(command -v mysqldump || true)"; [[ -x "$mysql_bin" ]] || mysql_bin=/www/server/mysql/bin/mysql; [[ -x "$dump_bin" ]] || dump_bin=/www/server/mysql/bin/mysqldump; test -x "$mysql_bin"; test -x "$dump_bin"',
'MYSQL_PWD="$control_password" "$dump_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --single-transaction --skip-lock-tables --default-character-set=utf8mb4 "$control_name" >"$backup_dir/control.sql"; test -s "$backup_dir/control.sql"; chmod 0600 "$backup_dir/control.sql"',
'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 host_name FROM projects WHERE host_name REGEXP \'^sv[0-9a-f]{10}$\' ORDER BY host_name" >"$backup_dir/hosts.list"; chmod 0600 "$backup_dir/hosts.list"',
'tar --acls --xattrs --numeric-owner -cpf "$backup_dir/state.tar" -C / etc/sea-vhost var/lib/sea-vhost var/lib/sea-vhost-agent var/lib/sea-vhost-panel; chmod 0600 "$backup_dir/state.tar"',
'if [[ -s "$backup_dir/hosts.list" ]]; then while IFS= read -r host; do [[ "$host" =~ ^sv[0-9a-f]{10}$ ]]; test -d "/www/wwwroot/seavHost/vHost/$host"; done <"$backup_dir/hosts.list"; tar --acls --xattrs --numeric-owner -cpf "$backup_dir/hosts.tar" -C /www/wwwroot/seavHost/vHost --files-from="$backup_dir/hosts.list"; else tar -cpf "$backup_dir/hosts.tar" --files-from=/dev/null; fi; chmod 0600 "$backup_dir/hosts.tar"',
'if [[ -d /www/server/panel/vhost/nginx ]]; then tar --acls --xattrs --numeric-owner -cpf "$backup_dir/nginx-vhosts.tar" -C /www/server/panel/vhost nginx; else tar -cpf "$backup_dir/nginx-vhosts.tar" --files-from=/dev/null; fi; chmod 0600 "$backup_dir/nginx-vhosts.tar"',
'(cd "$backup_dir" && sha256sum control.sql hosts.list state.tar hosts.tar nginx-vhosts.tar >SHA256SUMS && sha256sum -c SHA256SUMS); chmod 0600 "$backup_dir/SHA256SUMS"',
'tree_hash="$(tar -cpf - -C "$(dirname "$backup_dir")" "$(basename "$backup_dir")" | sha256sum | awk \'{print $1}\')"',
'printf "backup_path=%s\\nbackup_tree_sha256=%s\\ncontrol_database=%s\\nmanaged_hosts=%s\\n" "$backup_dir" "$tree_hash" "$control_name" "$(wc -l <"$backup_dir/hosts.list")"',
`printf '%s\\n' '${marker}'`,
].join('\n');
const log = await runShell(shell, marker);
const backupPath = log.match(/(?:^|\n)backup_path=([^\r\n]+)/)?.[1];
const treeHash = log.match(/(?:^|\n)backup_tree_sha256=([0-9a-f]{64})/)?.[1];
const controlDatabase = log.match(/(?:^|\n)control_database=([^\r\n]+)/)?.[1];
const managedHosts = Number(log.match(/(?:^|\n)managed_hosts=(\d+)/)?.[1]);
if (!backupPath || !treeHash || !controlDatabase || !Number.isSafeInteger(managedHosts)) throw new Error('backup verification output was incomplete');
console.log(JSON.stringify({ status: 'passed', backupPath, treeHash, controlDatabase, managedHosts, checks: {
controlDatabaseDump: true, stateArchive: true, managedHostArchive: true, nginxConfigurationArchive: true, checksumsVerified: true,
} }, null, 2));