openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
444 lines (443 loc) • 16.1 kB
JavaScript
import { L as retireSqliteDatabaseAdmissionForPath } from "./sqlite-database-admission-DQIqro3d.mjs";
import { l as syncDirectory, s as requireDirectorySync } from "./directory-durability-DlnWwNmv.mjs";
import { r as hashFileDescriptorSync, t as copyFileHandle } from "./file-descriptor-DQ-v5bLt.mjs";
import { a as setSqliteDirectoryNoCow, n as isSqlitePathOnBtrfs } from "./sqlite-wal-filesystem-LJsoYuDu.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { Fn as object, Jn as string, Nt as array, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { t as DoctorMaintenanceRefusalError } from "./update-doctor-result-DwaI51On.mjs";
import { r as createVerifiedSqliteSnapshot } from "./sqlite-snapshot-BQ91cQh_.mjs";
import { b as writeSessionSqliteMigrationManifest, d as listSessionSqliteMigrationManifestPaths, i as canonicalMigrationFilePath, p as readSessionSqliteMigrationManifest } from "./session-sqlite-migration-manifest-DwBodX3i.mjs";
import { n as assertDoctorSqliteMaintenancePathsNotAliased } from "./doctor-sqlite-maintenance-lock-BDftygVG.mjs";
import { s as rebindRewrittenClientCredentials } from "./client-credential-restore-CZMFMeth.mjs";
import fs from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
import { spawnSync } from "node:child_process";
import { root } from "@openclaw/fs-safe/root";
//#region src/commands/doctor-sqlite-nocow-recovery-identity.ts
/** Transfer existing recovery evidence only across Doctor's verified offline rewrite. */
function reconcileNoCowRecoveryIdentities(e) {
const t = new Map([...e.previousIdentities].map(([e, t]) => [canonicalMigrationFilePath(e), t]));
const n = [];
const r = canonicalMigrationFilePath(resolveOpenClawStateSqlitePath(e.env));
const i = t.get(r);
if (i) try {
rebindRewrittenClientCredentials({
env: e.env,
previousSharedFile: {
path: r,
dev: String(i.dev),
ino: String(i.ino)
},
assertCurrent: e.assertCurrent
});
} catch (e) {
n.push(`NOCOW credential identity left unchanged for ${r}: ${String(e)}`);
}
const refresh = (r, i) => {
const a = t.get(canonicalMigrationFilePath(r));
if (!a) return false;
try {
if (String(a.dev) !== i.dev || String(a.ino) !== i.ino) throw new Error("rewritten file is not the recorded generation");
e.assertCurrent();
const t = fs.lstatSync(r, { bigint: true });
if (!t.isFile() || t.nlink !== 1n) throw new Error("rewritten file is not an unaliased regular file");
i.dev = String(t.dev);
i.ino = String(t.ino);
return true;
} catch (e) {
n.push(`NOCOW recovery identity left unchanged for ${r}: ${String(e)}`);
return false;
}
};
for (const t of listSessionSqliteMigrationManifestPaths(e.env)) {
const n = readSessionSqliteMigrationManifest(t);
if (!n) continue;
let r = false;
for (const e of n.targets) if (e.databaseIdentity) r = refresh(e.sqlitePath, e.databaseIdentity) || r;
if (r) {
e.assertCurrent();
writeSessionSqliteMigrationManifest({
manifest: n,
manifestPath: t
});
}
}
return n;
}
//#endregion
//#region src/commands/doctor-sqlite-nocow.ts
/** Offline btrfs rewrites retain original SQLite files and WAL-aware backups. */
const TOOL_TIMEOUT_MS = 2e3;
const FUSER_MAX_PATHS = 2e3;
const FUSER_MAX_PATH_BYTES = 65536;
function hasNoCow(e) {
const t = spawnSync("lsattr", [
"-d",
"--",
e
], {
encoding: "utf8",
timeout: TOOL_TIMEOUT_MS
});
const n = t.stdout?.trim().split(/\s+/u)[0];
if (t.error || t.status !== 0 || !n || !/^[a-zA-Z-]+$/u.test(n)) throw new Error("NOCOW check skipped: lsattr is unavailable or could not read file attributes.");
return n.includes("C");
}
function inspectDoctorSqliteNoCow(e) {
const t = {
paths: [],
notes: []
};
for (const n of new Set(e)) try {
if (!fs.existsSync(n) || !isSqlitePathOnBtrfs(n)) continue;
if (!hasNoCow(path.dirname(n)) || hasInterruptedRepair(path.dirname(n)) || SIDECARS.some((e) => {
const t = `${n}${e}`;
return fs.existsSync(t) && !hasNoCow(t);
})) {
t.paths.push(n);
t.notes.push(`SQLite store on btrfs without NOCOW: ${n}. Run openclaw doctor --fix to rewrite it while the Gateway is stopped.`);
}
} catch (e) {
t.notes.push(`${n}: ${String(e)}`);
}
return t;
}
async function copyRegularFile(e, t, n) {
const r = await fs$1.open(e, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
try {
const i = await r.stat();
n();
const a = await fs$1.open(t, "wx+", 384);
try {
await copyFileHandle(r, a);
if ((await a.stat()).size !== i.size || hashFileDescriptorSync(r.fd).sha256 !== hashFileDescriptorSync(a.fd).sha256) throw new Error(`SQLite NOCOW copy mismatch: ${e}`);
} finally {
await a.close();
}
} finally {
await r.close();
}
}
function runAclTool(e, t, n) {
const r = { ...process.env };
delete r.POSIXLY_CORRECT;
const i = spawnSync(e, t, {
encoding: "utf8",
timeout: TOOL_TIMEOUT_MS,
input: n,
env: r
});
if (i.error || i.status !== 0) throw new Error(`NOCOW repair requires working ${e} to preserve access and default ACLs`);
return i.stdout.trim();
}
function readAcls(e) {
const t = runAclTool("getfacl", [
"-cEpn",
"--",
...e
]).split(/\n\s*\n/u);
if (t.length !== e.length) throw new Error("NOCOW repair could not read all source ACLs");
return t;
}
function preserveMetadata(e, t, n) {
for (const [n, r] of e.entries()) {
const e = t[n];
const i = fs.statSync(r);
if (BigInt(i.uid) !== e.uid || BigInt(i.gid) !== e.gid) fs.chownSync(r, Number(e.uid), Number(e.gid));
fs.chmodSync(r, Number(e.mode) & 4032);
}
runAclTool("setfacl", ["--restore=-"], e.map((e, t) => {
return `# file: ${e.replaceAll("\\", "\\134").replaceAll("\n", "\\012")}\n${n[t]}\n`;
}).join("\n"));
const r = readAcls(e);
for (const [i, a] of e.entries()) {
fs.chmodSync(a, Number(t[i].mode) & 4095);
if (r[i] !== n[i] || (fs.statSync(a).mode & 4095) !== (Number(t[i].mode) & 4095)) throw new Error(`NOCOW copy ACL verification failed: ${a}`);
const e = fs.openSync(a, "r");
try {
fs.fsyncSync(e);
} finally {
fs.closeSync(e);
}
}
}
const identitySchema = object({
dev: string().regex(/^\d+$/u),
ino: string().regex(/^\d+$/u)
});
const markerSchema = object({
owner: literal("openclaw-sqlite-nocow-v1"),
directory: string(),
staging: identitySchema,
files: array(identitySchema.extend({ name: string().min(1).refine((e) => e !== "." && e !== ".." && path.basename(e) === e) }))
});
const MARKER = "nocow-repair.json";
const SIDECARS = [
"",
"-wal",
"-shm",
"-journal"
];
function fileIdentity(e) {
return {
dev: String(e.dev),
ino: String(e.ino)
};
}
function matches(e, t) {
return String(e.dev) === t.dev && String(e.ino) === t.ino;
}
function listRepairStaging(e) {
const t = `${path.basename(e)}.nocow-backup-`;
return fs.readdirSync(path.dirname(e), { withFileTypes: true }).flatMap((n) => {
if (!n.isDirectory() || !n.name.startsWith(t)) return [];
const r = path.join(path.dirname(e), n.name);
try {
const t = markerSchema.parse(JSON.parse(fs.readFileSync(path.join(r, MARKER), "utf8")));
const n = fs.lstatSync(r, { bigint: true });
return t.directory === e && matches(n, t.staging) ? [{
staging: r,
stat: n,
marker: t
}] : [];
} catch {
return [];
}
});
}
function hasInterruptedRepair(e) {
return listRepairStaging(e).some(({ staging: e, marker: t }) => {
const n = t.files.filter((t) => fs.existsSync(path.join(e, t.name)));
return n.length === 0 || n.some((t) => !matches(fs.lstatSync(path.join(e, t.name), { bigint: true }), t));
});
}
/** Only our marked staging is disposable; exchanged originals remain recovery artifacts. */
async function cleanInterruptedRepair(e, t) {
for (const { staging: n, stat: r, marker: i } of listRepairStaging(e)) {
let e = false;
for (const r of i.files) {
const i = path.join(n, r.name);
if (!fs.existsSync(i)) continue;
if (matches(fs.lstatSync(i, { bigint: true }), r)) {
e = true;
continue;
}
t();
fs.unlinkSync(i);
}
if (!e) await removeUninstalledDirectory(n, r, t);
}
}
async function removeUninstalledDirectory(e, t, n) {
await (await root(path.dirname(e))).remove(path.basename(e), {
recursive: true,
assertBeforeMutation() {
n();
const r = fs.lstatSync(e, { bigint: true });
if (r.dev !== t.dev || r.ino !== t.ino) throw new Error(`NOCOW staging identity changed: ${e}`);
}
});
}
function assertNoOpenFiles(e) {
const t = [];
let n = [];
let r = 0;
for (const i of e) {
const e = path.resolve(i);
const a = Buffer.byteLength(e, "utf8") + 1;
if (n.length > 0 && (n.length >= FUSER_MAX_PATHS || r + a > FUSER_MAX_PATH_BYTES)) {
t.push(n);
n = [];
r = 0;
}
n.push(e);
r += a;
}
if (n.length > 0) t.push(n);
const i = /* @__PURE__ */ new Set();
let a;
for (const e of t) {
const t = spawnSync("fuser", e, {
encoding: "utf8",
timeout: TOOL_TIMEOUT_MS
});
const n = t.stdout?.trim() ?? "";
const r = t.stderr?.trim() ?? "";
if (t.status === 0 && /^\d+(?:\s+\d+)*$/u.test(n)) for (const e of n.split(/\s+/u)) i.add(e);
else if (t.error || t.status !== 1 || n || r) a ??= r || t.error?.message || (t.signal ? `signal ${t.signal}` : n || `exit status ${t.status}`);
}
if (i.size > 0) throw new Error(`store files are open (pids: ${[...i].join(", ")}); stop processes using this store before retrying`);
if (a) throw new Error(`fuser could not establish that all handles are closed: ${a}; check that fuser is installed and can inspect processes using this store`);
}
/** Only the live Doctor maintenance owner may call this after draining its database handles. */
async function repairDoctorSqliteNoCow(e) {
const t = /* @__PURE__ */ new Set();
const n = {
changes: [],
warnings: []
};
for (const r of new Set(e.paths.map((e) => path.dirname(path.resolve(e))))) {
let i;
let a = false;
let o = false;
const s = /* @__PURE__ */ new Map();
try {
e.assertCurrent();
const c = path.relative(path.resolve(e.stateDir), r);
if (!c || c.startsWith("..") || path.isAbsolute(c)) throw new Error("store directory must be owned by the active state directory");
assertDoctorSqliteMaintenancePathsNotAliased("SQLite NOCOW repair", [r], [e.stateDir]);
o = true;
await cleanInterruptedRepair(r, e.assertCurrent);
const l = [...new Set(e.paths.map((e) => path.resolve(e)))].filter((e) => path.dirname(e) === r);
const u = l.flatMap((e) => SIDECARS.map((t) => `${e}${t}`));
assertDoctorSqliteMaintenancePathsNotAliased("SQLite NOCOW repair", u, [e.stateDir]);
const d = u.filter((e) => fs.existsSync(e));
const f = new Map(d.map((e) => [e, fs.lstatSync(e, { bigint: true })]));
for (const [e, t] of f) if (!t.isFile()) throw new Error(`SQLite NOCOW source is not a regular file: ${e}`);
const p = d.filter((e) => !hasNoCow(e));
if (p.length === 0) {
e.assertCurrent();
setSqliteDirectoryNoCow(r);
continue;
}
const m = fs.statSync(r, { bigint: true }).dev;
if (!t.has(m)) {
const e = fs.mkdtempSync(`${r}.nocow-probe-`);
let n;
try {
const [r, i] = [path.join(e, "a"), path.join(e, "b")];
fs.writeFileSync(r, "");
fs.writeFileSync(i, "");
n = fs.openSync(r, "r");
const a = {
encoding: "utf8",
timeout: TOOL_TIMEOUT_MS
};
const o = spawnSync("fuser", [r], a);
if (o.error || o.status !== 0 || !(o.stdout ?? "").split(/\s+/u).includes(String(process.pid))) throw new Error("fuser cannot inspect processes");
const s = spawnSync("mv", [
"--exchange",
"--no-copy",
"-T",
"--",
r,
i
], a);
if (s.error || s.status !== 0) throw new Error("kernel/filesystem lacks RENAME_EXCHANGE or mv is unsupported");
t.add(m);
} finally {
if (n !== void 0) fs.closeSync(n);
fs.rmSync(e, {
recursive: true,
force: true
});
}
}
for (const t of l) {
e.assertCurrent();
retireSqliteDatabaseAdmissionForPath(t, { requireSoleDescriptor: true });
}
assertNoOpenFiles(d);
const h = [...f.values()].reduce((e, t) => e + t.size, 0n);
const g = fs.statfsSync(r, { bigint: true });
if (g.bavail * g.bsize < h * 2n) throw new Error(`at least ${h * 2n} bytes of free space are required (twice the SQLite file size)`);
e.log?.(`Rewriting SQLite files with NOCOW: ${r} (0/${p.length}).`);
const _ = readAcls(p);
e.assertCurrent();
setSqliteDirectoryNoCow(r);
i = fs.mkdtempSync(`${r}.nocow-backup-`);
setSqliteDirectoryNoCow(i);
const v = {
owner: "openclaw-sqlite-nocow-v1",
directory: r,
staging: fileIdentity(fs.statSync(i, { bigint: true })),
files: p.map((e) => ({
name: path.basename(e),
...fileIdentity(f.get(e))
}))
};
const y = fs.openSync(path.join(i, MARKER), "wx", 384);
try {
fs.writeFileSync(y, JSON.stringify(v));
fs.fsyncSync(y);
} finally {
fs.closeSync(y);
}
const b = path.join(i, "snapshots");
fs.mkdirSync(b, { mode: 448 });
for (const t of l) {
e.log?.(`Backing up SQLite store before NOCOW repair: ${t}.`);
await createVerifiedSqliteSnapshot({
sourcePath: t,
targetPath: path.join(b, path.basename(t)),
preserveRowIds: true,
beforePublish: e.assertCurrent
});
}
const x = p.map((e) => path.join(i, path.basename(e)));
for (const [t, n] of p.entries()) {
e.log?.(`Copying SQLite file for NOCOW repair (${t + 1}/${p.length}): ${n}.`);
await copyRegularFile(n, x[t], e.assertCurrent);
if (!hasNoCow(x[t])) throw new Error(`NOCOW was not inherited by ${x[t]}`);
}
e.assertCurrent();
preserveMetadata(x, p.map((e) => f.get(e)), _);
requireDirectorySync(await syncDirectory(i), "SQLite NOCOW staging directory");
requireDirectorySync(await syncDirectory(path.dirname(r)), "SQLite NOCOW backup parent");
assertNoOpenFiles(d);
for (const [t, n] of p.entries()) {
const o = x[t];
const c = f.get(n);
const l = fs.statSync(o, { bigint: true });
e.assertCurrent();
a = true;
const u = spawnSync("mv", [
"--exchange",
"--no-copy",
"-T",
"--",
o,
n
], {
encoding: "utf8",
timeout: TOOL_TIMEOUT_MS
});
const d = fs.statSync(n, { bigint: true });
const m = fs.statSync(o, { bigint: true });
const h = matches(d, fileIdentity(l)) && matches(m, fileIdentity(c));
a = !h && !(matches(d, fileIdentity(c)) && matches(m, fileIdentity(l)));
if (!h) throw new Error(`atomic SQLite file exchange failed: ${u.error?.message ?? u.stderr}`);
s.set(n, c);
requireDirectorySync(await syncDirectory(r), "SQLite NOCOW store directory");
requireDirectorySync(await syncDirectory(i), "SQLite NOCOW recovery directory");
e.log?.(`Rewrote SQLite file with NOCOW (${t + 1}/${p.length}): ${n}.`);
}
n.changes.push(`Rewrote SQLite files with NOCOW: ${r}. Originals and verified WAL-aware snapshots retained at ${i}.`);
} catch (t) {
if (a) throw new DoctorMaintenanceRefusalError(`SQLite NOCOW publication needs inspection: ${r}; retained directory: ${i}. ${String(t)}`, {
kind: "data-at-risk",
reason: "incomplete-migration"
});
try {
if (o) await cleanInterruptedRepair(r, e.assertCurrent);
} catch (e) {
n.warnings.push(`NOCOW staging cleanup failed: ${String(e)}`);
}
n.warnings.push(`SQLite NOCOW repair skipped for ${r}: ${String(t)}. Originals remain in place or in ${i ?? "their original directory"}. Required: GNU mv with --exchange/--no-copy, fuser (psmisc), getfacl/setfacl (acl). See https://docs.openclaw.ai/reference/database-schemas/integrity-and-recovery#btrfs-and-nocow.`);
} finally {
if (s.size > 0) try {
n.warnings.push(...reconcileNoCowRecoveryIdentities({
env: e.env,
previousIdentities: s,
assertCurrent: e.assertCurrent
}));
} catch (e) {
n.warnings.push(`NOCOW recovery-identity reconciliation failed: ${String(e)}`);
}
}
}
return n;
}
//#endregion
export { inspectDoctorSqliteNoCow, repairDoctorSqliteNoCow };