mirror of
https://github.com/nicotsx/ironmount.git
synced 2025-12-10 12:10:51 +01:00
refactor: improve error handling with global router catchall
This commit is contained in:
@@ -13,7 +13,7 @@ export const volumesTable = sqliteTable("volumes_table", {
|
||||
createdAt: int("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`),
|
||||
updatedAt: int("updated_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`),
|
||||
config: text("config", { mode: "json" }).$type<typeof volumeConfigSchema.inferOut>().notNull(),
|
||||
autoRemount: int("auto_remount").notNull().default(1),
|
||||
autoRemount: int("auto_remount").$type<1 | 0>().notNull().default(1),
|
||||
});
|
||||
|
||||
export type Volume = typeof volumesTable.$inferSelect;
|
||||
|
||||
@@ -8,6 +8,7 @@ import { driverController } from "./modules/driver/driver.controller";
|
||||
import { volumeController } from "./modules/volumes/volume.controller";
|
||||
import { logger } from "./utils/logger";
|
||||
import { startup } from "./modules/lifecycle/startup";
|
||||
import { handleServiceError } from "./utils/errors";
|
||||
|
||||
export const generalDescriptor = (app: Hono) =>
|
||||
openAPISpecs(app, {
|
||||
@@ -41,6 +42,18 @@ app.get("/", (c) => {
|
||||
return c.json({ message: "Welcome to the Ironmount API" });
|
||||
});
|
||||
|
||||
app.onError((err, c) => {
|
||||
logger.error(`${c.req.url}: ${err.message}`);
|
||||
|
||||
if (err.cause instanceof Error) {
|
||||
logger.error(err.cause.message);
|
||||
}
|
||||
|
||||
const { status, message } = handleServiceError(err);
|
||||
|
||||
return c.json({ error: message }, status);
|
||||
});
|
||||
|
||||
const socketPath = "/run/docker/plugins/ironmount.sock";
|
||||
|
||||
(async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { exec, execFile as execFileCb } from "node:child_process";
|
||||
import { execFile as execFileCb } from "node:child_process";
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import * as npath from "node:path";
|
||||
@@ -9,6 +9,7 @@ import { promisify } from "node:util";
|
||||
import { withTimeout } from "../../../utils/timeout";
|
||||
import { OPERATION_TIMEOUT } from "../../../core/constants";
|
||||
import { toMessage } from "../../../utils/errors";
|
||||
import { getMountForPath } from "../../../utils/mountinfo";
|
||||
|
||||
const execFile = promisify(execFileCb);
|
||||
|
||||
@@ -110,6 +111,12 @@ const checkHealth = async (path: string) => {
|
||||
logger.debug(`Checking health of NFS volume at ${path}...`);
|
||||
await fs.access(path);
|
||||
|
||||
const mount = await getMountForPath(path);
|
||||
|
||||
if (!mount || !mount.fstype.startsWith("nfs")) {
|
||||
throw new Error(`Path ${path} is not mounted as NFS.`);
|
||||
}
|
||||
|
||||
const testFilePath = npath.join(path, `.healthcheck-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
|
||||
|
||||
await fs.writeFile(testFilePath, "healthcheck");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { eq, or } from "drizzle-orm";
|
||||
import { and, eq, or } from "drizzle-orm";
|
||||
import { db } from "../../db/db";
|
||||
import { logger } from "../../utils/logger";
|
||||
import { volumesTable } from "../../db/schema";
|
||||
@@ -7,7 +7,10 @@ import { volumeService } from "../volumes/volume.service";
|
||||
|
||||
export const startup = async () => {
|
||||
const volumes = await db.query.volumesTable.findMany({
|
||||
where: or(eq(volumesTable.status, "mounted"), eq(volumesTable.autoRemount, 1)),
|
||||
where: or(
|
||||
eq(volumesTable.status, "mounted"),
|
||||
and(eq(volumesTable.autoRemount, 1), eq(volumesTable.status, "error")),
|
||||
),
|
||||
});
|
||||
|
||||
for (const volume of volumes) {
|
||||
@@ -21,7 +24,7 @@ export const startup = async () => {
|
||||
logger.info("Running health check for all volumes...");
|
||||
|
||||
const volumes = await db.query.volumesTable.findMany({
|
||||
where: or(eq(volumesTable.status, "mounted")),
|
||||
where: or(eq(volumesTable.status, "mounted"), eq(volumesTable.status, "error")),
|
||||
});
|
||||
|
||||
for (const volume of volumes) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Hono } from "hono";
|
||||
import { validator } from "hono-openapi/arktype";
|
||||
import { handleServiceError } from "../../utils/errors";
|
||||
import {
|
||||
createVolumeBody,
|
||||
createVolumeDto,
|
||||
@@ -37,12 +36,7 @@ export const volumeController = new Hono()
|
||||
const body = c.req.valid("json");
|
||||
const res = await volumeService.createVolume(body.name, body.config);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume created", volume: res.volume });
|
||||
return c.json({ message: "Volume created", volume: res.volume }, 201);
|
||||
})
|
||||
.post("/test-connection", testConnectionDto, validator("json", testConnectionBody), async (c) => {
|
||||
const body = c.req.valid("json");
|
||||
@@ -52,24 +46,14 @@ export const volumeController = new Hono()
|
||||
})
|
||||
.delete("/:name", deleteVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.deleteVolume(name);
|
||||
await volumeService.deleteVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume deleted" });
|
||||
return c.json({ message: "Volume deleted" }, 200);
|
||||
})
|
||||
.get("/:name", getVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.getVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
const response = {
|
||||
...res.volume,
|
||||
createdAt: res.volume.createdAt.getTime(),
|
||||
@@ -84,11 +68,6 @@ export const volumeController = new Hono()
|
||||
const body = c.req.valid("json");
|
||||
const res = await volumeService.updateVolume(name, body.config);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
const response = {
|
||||
message: "Volume updated",
|
||||
volume: {
|
||||
@@ -105,23 +84,13 @@ export const volumeController = new Hono()
|
||||
})
|
||||
.post("/:name/mount", mountVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.mountVolume(name);
|
||||
const { error, status } = await volumeService.mountVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume mounted successfully" }, 200);
|
||||
return c.json({ error, status }, error ? 500 : 200);
|
||||
})
|
||||
.post("/:name/unmount", unmountVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.unmountVolume(name);
|
||||
const { error, status } = await volumeService.unmountVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume unmounted successfully" }, 200);
|
||||
return c.json({ error, status }, error ? 500 : 200);
|
||||
});
|
||||
|
||||
@@ -8,11 +8,12 @@ const volumeSchema = type({
|
||||
path: "string",
|
||||
type: type.enumerated("nfs", "smb", "directory"),
|
||||
status: type.enumerated("mounted", "unmounted", "error", "unknown"),
|
||||
lastError: "string|null",
|
||||
lastError: "string | null",
|
||||
createdAt: "number",
|
||||
updatedAt: "number",
|
||||
lastHealthCheck: "number",
|
||||
config: volumeConfigSchema,
|
||||
autoRemount: "0 | 1",
|
||||
});
|
||||
|
||||
export type VolumeDto = typeof volumeSchema.infer;
|
||||
@@ -55,7 +56,6 @@ export const createVolumeResponse = type({
|
||||
volume: type({
|
||||
name: "string",
|
||||
path: "string",
|
||||
createdAt: "number",
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -195,7 +195,8 @@ export const testConnectionDto = describeRoute({
|
||||
* Mount volume
|
||||
*/
|
||||
export const mountVolumeResponse = type({
|
||||
message: "string",
|
||||
error: "string?",
|
||||
status: type.enumerated("mounted", "unmounted", "error"),
|
||||
});
|
||||
|
||||
export const mountVolumeDto = describeRoute({
|
||||
@@ -222,7 +223,8 @@ export const mountVolumeDto = describeRoute({
|
||||
* Unmount volume
|
||||
*/
|
||||
export const unmountVolumeResponse = type({
|
||||
message: "string",
|
||||
error: "string?",
|
||||
status: type.enumerated("mounted", "unmounted", "error"),
|
||||
});
|
||||
|
||||
export const unmountVolumeDto = describeRoute({
|
||||
|
||||
@@ -9,7 +9,6 @@ import { config } from "../../core/config";
|
||||
import { db } from "../../db/db";
|
||||
import { volumesTable } from "../../db/schema";
|
||||
import { createVolumeBackend } from "../backends/backend";
|
||||
import { logger } from "../../utils/logger";
|
||||
import { toMessage } from "../../utils/errors";
|
||||
|
||||
const listVolumes = async () => {
|
||||
@@ -26,7 +25,7 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return { error: new ConflictError("Volume already exists") };
|
||||
throw new ConflictError("Volume already exists");
|
||||
}
|
||||
|
||||
const volumePathHost = path.join(config.volumeRootHost);
|
||||
@@ -45,82 +44,54 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
|
||||
};
|
||||
|
||||
const deleteVolume = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
|
||||
if (!volume) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
await backend.unmount();
|
||||
await db.delete(volumesTable).where(eq(volumesTable.name, name));
|
||||
return { status: 200 };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to delete volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
await backend.unmount();
|
||||
await db.delete(volumesTable).where(eq(volumesTable.name, name));
|
||||
};
|
||||
|
||||
const mountVolume = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
|
||||
if (!volume) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
await backend.mount();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status: "mounted", lastHealthCheck: new Date(), lastError: null })
|
||||
.where(eq(volumesTable.name, name));
|
||||
|
||||
return { status: 200 };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to mount volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
const { error, status } = await backend.mount();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status, lastError: error, lastHealthCheck: new Date() })
|
||||
.where(eq(volumesTable.name, name));
|
||||
|
||||
return { error, status };
|
||||
};
|
||||
|
||||
const unmountVolume = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
|
||||
if (!volume) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
await backend.unmount();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status: "unmounted", lastHealthCheck: new Date() })
|
||||
.where(eq(volumesTable.name, name));
|
||||
|
||||
return { status: 200 };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to unmount volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
const { status, error } = await backend.unmount();
|
||||
|
||||
await db.update(volumesTable).set({ status }).where(eq(volumesTable.name, name));
|
||||
|
||||
return { error, status };
|
||||
};
|
||||
|
||||
const getVolume = async (name: string) => {
|
||||
@@ -129,121 +100,88 @@ const getVolume = async (name: string) => {
|
||||
});
|
||||
|
||||
if (!volume) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
return { volume };
|
||||
};
|
||||
|
||||
const updateVolume = async (name: string, backendConfig: BackendConfig) => {
|
||||
try {
|
||||
const existing = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
const existing = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(volumesTable)
|
||||
.set({
|
||||
config: backendConfig,
|
||||
type: backendConfig.backend,
|
||||
updatedAt: new Date(),
|
||||
status: "unmounted",
|
||||
})
|
||||
.where(eq(volumesTable.name, name))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
return { error: new InternalServerError("Failed to update volume") };
|
||||
}
|
||||
|
||||
return { volume: updated };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to update volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
if (!existing) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(volumesTable)
|
||||
.set({
|
||||
config: backendConfig,
|
||||
type: backendConfig.backend,
|
||||
updatedAt: new Date(),
|
||||
status: "unmounted",
|
||||
})
|
||||
.where(eq(volumesTable.name, name))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
throw new InternalServerError("Failed to update volume");
|
||||
}
|
||||
|
||||
return { volume: updated };
|
||||
};
|
||||
|
||||
const testConnection = async (backendConfig: BackendConfig) => {
|
||||
let tempDir: string | null = null;
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ironmount-test-"));
|
||||
|
||||
try {
|
||||
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ironmount-test-"));
|
||||
const mockVolume = {
|
||||
id: 0,
|
||||
name: "test-connection",
|
||||
path: tempDir,
|
||||
config: backendConfig,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastHealthCheck: new Date(),
|
||||
type: backendConfig.backend,
|
||||
status: "unmounted" as const,
|
||||
lastError: null,
|
||||
autoRemount: 0 as const,
|
||||
};
|
||||
|
||||
const mockVolume = {
|
||||
id: 0,
|
||||
name: "test-connection",
|
||||
path: tempDir,
|
||||
config: backendConfig,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastHealthCheck: new Date(),
|
||||
type: backendConfig.backend,
|
||||
status: "unmounted" as const,
|
||||
lastError: null,
|
||||
autoRemount: 0,
|
||||
};
|
||||
const backend = createVolumeBackend(mockVolume);
|
||||
const { error } = await backend.mount();
|
||||
|
||||
const backend = createVolumeBackend(mockVolume);
|
||||
await backend.unmount();
|
||||
|
||||
await backend.mount();
|
||||
await backend.unmount();
|
||||
await fs.access(tempDir);
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Connection successful",
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: toMessage(error),
|
||||
};
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
try {
|
||||
await fs.access(tempDir);
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
} catch (cleanupError) {
|
||||
logger.warn("Failed to cleanup temp directory:", cleanupError);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: !error,
|
||||
message: error ? toMessage(error) : "Connection successful",
|
||||
};
|
||||
};
|
||||
|
||||
const checkHealth = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
|
||||
if (!volume) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
const { error } = await backend.checkHealth();
|
||||
|
||||
if (error) {
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status: "error", lastError: error, lastHealthCheck: new Date() })
|
||||
.where(eq(volumesTable.name, volume.name));
|
||||
|
||||
return { error };
|
||||
}
|
||||
|
||||
await db.update(volumesTable).set({ lastHealthCheck: new Date() }).where(eq(volumesTable.name, volume.name));
|
||||
|
||||
return { status: 200 };
|
||||
} catch (err) {
|
||||
return { error: new InternalServerError("Health check failed", { cause: err }) };
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
const { error, status } = await backend.checkHealth();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ lastHealthCheck: new Date(), status, lastError: error })
|
||||
.where(eq(volumesTable.name, volume.name));
|
||||
|
||||
return { status, error };
|
||||
};
|
||||
|
||||
export const volumeService = {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { ConflictError, NotFoundError } from "http-errors-enhanced";
|
||||
import { logger } from "./logger";
|
||||
|
||||
export const handleServiceError = (error: unknown) => {
|
||||
if (error instanceof ConflictError) {
|
||||
@@ -10,8 +9,7 @@ export const handleServiceError = (error: unknown) => {
|
||||
return { message: error.message, status: 404 as const };
|
||||
}
|
||||
|
||||
logger.error("Unhandled service error:", error);
|
||||
return { message: "Internal Server Error", status: 500 as const };
|
||||
return { message: toMessage(error), status: 500 as const };
|
||||
};
|
||||
|
||||
export const toMessage = (err: unknown): string => {
|
||||
|
||||
53
apps/server/src/utils/mountinfo.ts
Normal file
53
apps/server/src/utils/mountinfo.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import path from "node:path";
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
type MountInfo = {
|
||||
mountPoint: string;
|
||||
fstype: string;
|
||||
};
|
||||
|
||||
function isPathWithin(base: string, target: string): boolean {
|
||||
const rel = path.posix.relative(base, target);
|
||||
return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
|
||||
}
|
||||
|
||||
function unescapeMount(s: string): string {
|
||||
return s.replace(/\\([0-7]{3})/g, (_, oct) => String.fromCharCode(parseInt(oct, 8)));
|
||||
}
|
||||
|
||||
async function readMountInfo(): Promise<MountInfo[]> {
|
||||
const text = await fs.readFile("/proc/self/mountinfo", "utf-8");
|
||||
const result: MountInfo[] = [];
|
||||
|
||||
for (const line of text.split("\n")) {
|
||||
if (!line) continue;
|
||||
const sep = line.indexOf(" - ");
|
||||
|
||||
if (sep === -1) continue;
|
||||
|
||||
const left = line.slice(0, sep).split(" ");
|
||||
const right = line.slice(sep + 3).split(" ");
|
||||
|
||||
// [0]=mount ID, [1]=parent ID, [2]=major:minor, [3]=root, [4]=mount point, [5]=mount options, ...
|
||||
const mpRaw = left[4];
|
||||
const fstype = right[0];
|
||||
|
||||
if (!mpRaw || !fstype) continue;
|
||||
|
||||
result.push({ mountPoint: unescapeMount(mpRaw), fstype });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function getMountForPath(p: string): Promise<MountInfo | undefined> {
|
||||
const mounts = await readMountInfo();
|
||||
|
||||
let best: MountInfo | undefined;
|
||||
for (const m of mounts) {
|
||||
if (!isPathWithin(m.mountPoint, p)) continue;
|
||||
if (!best || m.mountPoint.length > best.mountPoint.length) {
|
||||
best = m;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
Reference in New Issue
Block a user