feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,238 @@
|
||||
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
|
||||
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
|
||||
if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2);
|
||||
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 email = `quota-${suffix}@seavhost.test`;
|
||||
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}8q`;
|
||||
const planName = `Quota verification ${suffix}`;
|
||||
const statePath = `/var/lib/sea-vhost/quota-verify-${suffix}.state`;
|
||||
|
||||
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: 30_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 = 120) {
|
||||
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 quota 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 {
|
||||
const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
|
||||
if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task');
|
||||
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) || log.includes('★[')) break;
|
||||
}
|
||||
if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`);
|
||||
return log;
|
||||
} finally {
|
||||
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) {
|
||||
const response = await fetch(new URL(pathname, consoleBase), {
|
||||
method, redirect: 'manual', signal: AbortSignal.timeout(30_000),
|
||||
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const text = await response.text();
|
||||
let payload;
|
||||
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
|
||||
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`);
|
||||
return { response, payload };
|
||||
}
|
||||
|
||||
function cookieFrom(response) {
|
||||
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
|
||||
return header?.split(';', 1)[0];
|
||||
}
|
||||
|
||||
const dbParts = [
|
||||
'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',
|
||||
].join('\n');
|
||||
|
||||
const seedMarker = `quota-seeded-${suffix}`;
|
||||
const seedShell = [
|
||||
'set -Eeuo pipefail', `email=${q(email)}`, `password=${q(password)}`, `plan_name=${q(planName)}`, `state_path=${q(statePath)}`,
|
||||
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
|
||||
dbParts,
|
||||
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Quota verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
|
||||
'read -r tenant_id original_plan_id project_root < <(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 p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")',
|
||||
'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; host_name="${project_root##*/}"',
|
||||
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',1099511627776,1099511627776,1099511627776,100000,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"',
|
||||
'temp_plan_id="$(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 id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"',
|
||||
'printf "%s %s %s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" "$project_root" "$host_name" | install -o root -g root -m 0600 /dev/stdin "$state_path"',
|
||||
`printf '%s\n' ${q(seedMarker)}`,
|
||||
].join('\n');
|
||||
|
||||
function planShell(bandwidth, processes, marker) {
|
||||
return [
|
||||
'set -euo pipefail', `state_path=${q(statePath)}`, dbParts,
|
||||
'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"',
|
||||
`MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE plans SET monthly_bandwidth_bytes=${bandwidth},process_limit=${processes} WHERE id=$temp_plan_id;"`,
|
||||
`printf '%s\n' ${q(marker)}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const cleanupMarker = `quota-cleaned-${suffix}`;
|
||||
const cleanupShell = [
|
||||
'set -euo pipefail', `email=${q(email)}`, `state_path=${q(statePath)}`, dbParts,
|
||||
'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"; pkill -u "$host_name" -f "sleep 180" 2>/dev/null || true; MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi',
|
||||
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
|
||||
`printf '%s\n' ${q(cleanupMarker)}`,
|
||||
].join('\n');
|
||||
|
||||
async function sendSiteRequest(domain) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = consoleBase.protocol === 'https:' ? https : http;
|
||||
const request = client.request(consoleBase, { method: 'GET', timeout: 10_000, headers: { Host: domain, Connection: 'close' } }, (response) => {
|
||||
let bytes = 0;
|
||||
response.on('data', (chunk) => { bytes += chunk.length; });
|
||||
response.on('end', () => resolve({ status: response.statusCode, bytes }));
|
||||
});
|
||||
request.on('timeout', () => request.destroy(new Error('site request timed out')));
|
||||
request.on('error', reject);
|
||||
request.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function currentProject(cookie, projectID) {
|
||||
const result = await api('/api/v1/projects', { cookie });
|
||||
return result.payload?.projects?.find((item) => item.id === projectID);
|
||||
}
|
||||
|
||||
async function waitForStatus(cookie, projectID, status, attempts = 30) {
|
||||
let project;
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 5000));
|
||||
project = await currentProject(cookie, projectID);
|
||||
if (project?.status === status) return project;
|
||||
}
|
||||
throw new Error(`project did not reach ${status}; status=${project?.status}`);
|
||||
}
|
||||
|
||||
let seeded = false;
|
||||
let cookie;
|
||||
let project;
|
||||
let initiallyRunning = false;
|
||||
try {
|
||||
await runShell(`Sea vHost quota seed ${suffix}`, seedShell, seedMarker);
|
||||
seeded = true;
|
||||
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } });
|
||||
cookie = cookieFrom(login.response);
|
||||
project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0];
|
||||
if (!project?.id || !project?.domain) throw new Error('temporary tenant has no project');
|
||||
initiallyRunning = project.status === 'running';
|
||||
if (!initiallyRunning) await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
|
||||
|
||||
const lowBandwidthMarker = `quota-bandwidth-low-${suffix}`;
|
||||
await runShell(`Sea vHost bandwidth limit ${suffix}`, planShell(1, 100000, lowBandwidthMarker), lowBandwidthMarker);
|
||||
let deliveredBytes = 0;
|
||||
for (let index = 0; index < 3; index += 1) deliveredBytes += (await sendSiteRequest(project.domain)).bytes;
|
||||
const bandwidthSuspended = await waitForStatus(cookie, project.id, 'quota_suspended');
|
||||
const bandwidthDashboard = await api('/api/v1/dashboard', { cookie });
|
||||
if (bandwidthDashboard.payload?.usage?.bandwidthBytes < 1) throw new Error('bandwidth quota usage was not measured');
|
||||
if (!String(bandwidthSuspended.lastError ?? '').includes('bandwidth') && bandwidthSuspended.status !== 'quota_suspended') throw new Error('bandwidth suspension reason missing');
|
||||
|
||||
const highMarker = `quota-bandwidth-recover-${suffix}`;
|
||||
await runShell(`Sea vHost bandwidth recover ${suffix}`, planShell(1099511627776, 100000, highMarker), highMarker);
|
||||
await waitForStatus(cookie, project.id, 'stopped');
|
||||
await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
|
||||
|
||||
const processMarker = `quota-processes-${suffix}`;
|
||||
const processShell = [
|
||||
'set -euo pipefail', `state_path=${q(statePath)}`, dbParts,
|
||||
'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"',
|
||||
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE plans SET monthly_bandwidth_bytes=1099511627776,process_limit=1 WHERE id=$temp_plan_id;"',
|
||||
'for _ in 1 2 3; do setsid -f runuser -u "$host_name" -- sleep 180; done; sleep 1; test "$(pgrep -u "$host_name" | wc -l)" -gt 1',
|
||||
`printf '%s\n' ${q(processMarker)}`,
|
||||
].join('\n');
|
||||
await runShell(`Sea vHost process limit ${suffix}`, processShell, processMarker);
|
||||
await waitForStatus(cookie, project.id, 'quota_suspended');
|
||||
const processDashboard = await api('/api/v1/dashboard', { cookie });
|
||||
if (processDashboard.payload?.usage?.processCount <= 1) throw new Error('process quota usage was not measured');
|
||||
|
||||
const killedMarker = `quota-process-killed-${suffix}`;
|
||||
const killedShell = [
|
||||
'set -euo pipefail', `state_path=${q(statePath)}`, 'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"',
|
||||
'if pgrep -u "$host_name" -f "sleep 180" >/dev/null; then exit 1; fi', `printf '%s\n' ${q(killedMarker)}`,
|
||||
].join('\n');
|
||||
await runShell(`Sea vHost process kill verify ${suffix}`, killedShell, killedMarker);
|
||||
const processRecoverMarker = `quota-process-recover-${suffix}`;
|
||||
await runShell(`Sea vHost process recover ${suffix}`, planShell(1099511627776, 100000, processRecoverMarker), processRecoverMarker);
|
||||
await waitForStatus(cookie, project.id, 'stopped');
|
||||
await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
|
||||
|
||||
console.log(JSON.stringify({ status: 'passed', checks: {
|
||||
bandwidthTrafficReachedSite: deliveredBytes > 0,
|
||||
bandwidthUsageMeasured: true,
|
||||
bandwidthQuotaSuspendedProject: true,
|
||||
bandwidthQuotaRecoveredToStopped: true,
|
||||
processUsageMeasured: true,
|
||||
processQuotaSuspendedProject: true,
|
||||
excessProcessesTerminated: true,
|
||||
processQuotaRecoveredToStopped: true,
|
||||
manualRestartAfterRecovery: true,
|
||||
}, observedDeliveredBodyBytes: deliveredBytes,
|
||||
observedBandwidthBytes: bandwidthDashboard.payload.usage.bandwidthBytes,
|
||||
observedProcessCount: processDashboard.payload.usage.processCount }, null, 2));
|
||||
} finally {
|
||||
if (cookie && project?.id) {
|
||||
try {
|
||||
const current = await currentProject(cookie, project.id);
|
||||
if (current?.status === 'quota_suspended') {
|
||||
const marker = `quota-final-recover-${suffix}`;
|
||||
await runShell(`Sea vHost quota final recover ${suffix}`, planShell(1099511627776, 100000, marker), marker, 60);
|
||||
await waitForStatus(cookie, project.id, 'stopped', 24);
|
||||
}
|
||||
if (initiallyRunning && (await currentProject(cookie, project.id))?.status !== 'running') {
|
||||
await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
|
||||
}
|
||||
} catch { process.exitCode = 1; }
|
||||
}
|
||||
if (seeded) {
|
||||
try { await runShell(`Sea vHost quota cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch { process.exitCode = 1; }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user