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,6 +13,7 @@ export type ListVolumesResponses = {
|
|||||||
*/
|
*/
|
||||||
200: {
|
200: {
|
||||||
volumes: Array<{
|
volumes: Array<{
|
||||||
|
autoRemount: boolean;
|
||||||
config:
|
config:
|
||||||
| {
|
| {
|
||||||
backend: "directory";
|
backend: "directory";
|
||||||
@@ -155,6 +156,7 @@ export type GetVolumeResponses = {
|
|||||||
* Volume details
|
* Volume details
|
||||||
*/
|
*/
|
||||||
200: {
|
200: {
|
||||||
|
autoRemount: boolean;
|
||||||
config:
|
config:
|
||||||
| {
|
| {
|
||||||
backend: "directory";
|
backend: "directory";
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ export const CreateVolumeDialog = ({ open, setOpen }: Props) => {
|
|||||||
<Dialog open={open} onOpenChange={setOpen}>
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button className="bg-blue-900 hover:bg-blue-800">
|
<Button className="bg-blue-900 hover:bg-blue-800">
|
||||||
<Plus size={16} />
|
<Plus size={16} className="mr-2" />
|
||||||
Create volume
|
Create volume
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ export const CreateVolumeForm = ({ onSubmit, mode = "create", initialValues, for
|
|||||||
resolver: arktypeResolver(formSchema),
|
resolver: arktypeResolver(formSchema),
|
||||||
defaultValues: initialValues,
|
defaultValues: initialValues,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { watch, getValues } = form;
|
const { watch, getValues } = form;
|
||||||
|
|
||||||
const watchedBackend = watch("backend");
|
const watchedBackend = watch("backend");
|
||||||
@@ -40,6 +41,7 @@ export const CreateVolumeForm = ({ onSubmit, mode = "create", initialValues, for
|
|||||||
const testBackendConnection = useMutation({
|
const testBackendConnection = useMutation({
|
||||||
...testConnectionMutation(),
|
...testConnectionMutation(),
|
||||||
onMutate: () => {
|
onMutate: () => {
|
||||||
|
setTestMessage("");
|
||||||
setTestStatus("loading");
|
setTestStatus("loading");
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Slot } from "@radix-ui/react-slot";
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
import type * as React from "react";
|
import type * as React from "react";
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
import { cn } from "~/lib/utils";
|
||||||
@@ -9,16 +10,13 @@ const buttonVariants = cva(
|
|||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default:
|
default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
|
||||||
destructive:
|
destructive:
|
||||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
outline:
|
outline:
|
||||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||||
secondary:
|
secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
ghost:
|
|
||||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
@@ -44,15 +42,19 @@ function Button({
|
|||||||
}: React.ComponentProps<"button"> &
|
}: React.ComponentProps<"button"> &
|
||||||
VariantProps<typeof buttonVariants> & {
|
VariantProps<typeof buttonVariants> & {
|
||||||
asChild?: boolean;
|
asChild?: boolean;
|
||||||
}) {
|
} & { loading?: boolean }) {
|
||||||
const Comp = asChild ? Slot : "button";
|
const Comp = asChild ? Slot : "button";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
|
disabled={props.loading}
|
||||||
data-slot="button"
|
data-slot="button"
|
||||||
className={cn(buttonVariants({ variant, size, className }))}
|
className={cn(buttonVariants({ variant, size, className }), "transition-all")}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
>
|
||||||
|
<Loader2 className={cn("h-4 w-4 animate-spin absolute", { invisible: !props.loading })} />
|
||||||
|
<div className={cn("flex items-center justify-center", { invisible: props.loading })}>{props.children}</div>
|
||||||
|
</Comp>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||||
import { Slot } from "@radix-ui/react-slot"
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
import {
|
import {
|
||||||
Controller,
|
Controller,
|
||||||
FormProvider,
|
FormProvider,
|
||||||
@@ -9,23 +9,21 @@ import {
|
|||||||
type ControllerProps,
|
type ControllerProps,
|
||||||
type FieldPath,
|
type FieldPath,
|
||||||
type FieldValues,
|
type FieldValues,
|
||||||
} from "react-hook-form"
|
} from "react-hook-form";
|
||||||
|
|
||||||
import { cn } from "~/lib/utils"
|
import { cn } from "~/lib/utils";
|
||||||
import { Label } from "~/components/ui/label"
|
import { Label } from "~/components/ui/label";
|
||||||
|
|
||||||
const Form = FormProvider
|
const Form = FormProvider;
|
||||||
|
|
||||||
type FormFieldContextValue<
|
type FormFieldContextValue<
|
||||||
TFieldValues extends FieldValues = FieldValues,
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||||
> = {
|
> = {
|
||||||
name: TName
|
name: TName;
|
||||||
}
|
};
|
||||||
|
|
||||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue);
|
||||||
{} as FormFieldContextValue
|
|
||||||
)
|
|
||||||
|
|
||||||
const FormField = <
|
const FormField = <
|
||||||
TFieldValues extends FieldValues = FieldValues,
|
TFieldValues extends FieldValues = FieldValues,
|
||||||
@@ -37,21 +35,21 @@ const FormField = <
|
|||||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||||
<Controller {...props} />
|
<Controller {...props} />
|
||||||
</FormFieldContext.Provider>
|
</FormFieldContext.Provider>
|
||||||
)
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
const useFormField = () => {
|
const useFormField = () => {
|
||||||
const fieldContext = React.useContext(FormFieldContext)
|
const fieldContext = React.useContext(FormFieldContext);
|
||||||
const itemContext = React.useContext(FormItemContext)
|
const itemContext = React.useContext(FormItemContext);
|
||||||
const { getFieldState } = useFormContext()
|
const { getFieldState } = useFormContext();
|
||||||
const formState = useFormState({ name: fieldContext.name })
|
const formState = useFormState({ name: fieldContext.name });
|
||||||
const fieldState = getFieldState(fieldContext.name, formState)
|
const fieldState = getFieldState(fieldContext.name, formState);
|
||||||
|
|
||||||
if (!fieldContext) {
|
if (!fieldContext) {
|
||||||
throw new Error("useFormField should be used within <FormField>")
|
throw new Error("useFormField should be used within <FormField>");
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id } = itemContext
|
const { id } = itemContext;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -60,36 +58,27 @@ const useFormField = () => {
|
|||||||
formDescriptionId: `${id}-form-item-description`,
|
formDescriptionId: `${id}-form-item-description`,
|
||||||
formMessageId: `${id}-form-item-message`,
|
formMessageId: `${id}-form-item-message`,
|
||||||
...fieldState,
|
...fieldState,
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
|
|
||||||
type FormItemContextValue = {
|
type FormItemContextValue = {
|
||||||
id: string
|
id: string;
|
||||||
}
|
};
|
||||||
|
|
||||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);
|
||||||
{} as FormItemContextValue
|
|
||||||
)
|
|
||||||
|
|
||||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
const id = React.useId()
|
const id = React.useId();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FormItemContext.Provider value={{ id }}>
|
<FormItemContext.Provider value={{ id }}>
|
||||||
<div
|
<div data-slot="form-item" className={cn("grid gap-2", className)} {...props} />
|
||||||
data-slot="form-item"
|
|
||||||
className={cn("grid gap-2", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</FormItemContext.Provider>
|
</FormItemContext.Provider>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FormLabel({
|
function FormLabel({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
className,
|
const { error, formItemId } = useFormField();
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
|
||||||
const { error, formItemId } = useFormField()
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Label
|
<Label
|
||||||
@@ -99,67 +88,49 @@ function FormLabel({
|
|||||||
htmlFor={formItemId}
|
htmlFor={formItemId}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Slot
|
<Slot
|
||||||
data-slot="form-control"
|
data-slot="form-control"
|
||||||
id={formItemId}
|
id={formItemId}
|
||||||
aria-describedby={
|
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
|
||||||
!error
|
|
||||||
? `${formDescriptionId}`
|
|
||||||
: `${formDescriptionId} ${formMessageId}`
|
|
||||||
}
|
|
||||||
aria-invalid={!!error}
|
aria-invalid={!!error}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
const { formDescriptionId } = useFormField()
|
const { formDescriptionId } = useFormField();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<p
|
<p
|
||||||
data-slot="form-description"
|
data-slot="form-description"
|
||||||
id={formDescriptionId}
|
id={formDescriptionId}
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
className={cn("text-muted-foreground text-xs", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
const { error, formMessageId } = useFormField()
|
const { error, formMessageId } = useFormField();
|
||||||
const body = error ? String(error?.message ?? "") : props.children
|
const body = error ? String(error?.message ?? "") : props.children;
|
||||||
|
|
||||||
if (!body) {
|
if (!body) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<p
|
<p data-slot="form-message" id={formMessageId} className={cn("text-destructive text-sm", className)} {...props}>
|
||||||
data-slot="form-message"
|
|
||||||
id={formMessageId}
|
|
||||||
className={cn("text-destructive text-sm", className)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{body}
|
{body}
|
||||||
</p>
|
</p>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField };
|
||||||
useFormField,
|
|
||||||
Form,
|
|
||||||
FormItem,
|
|
||||||
FormLabel,
|
|
||||||
FormControl,
|
|
||||||
FormDescription,
|
|
||||||
FormMessage,
|
|
||||||
FormField,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -21,10 +21,13 @@ export const HealthchecksCard = ({ volume }: Props) => {
|
|||||||
<ScanHeartIcon size={24} />
|
<ScanHeartIcon size={24} />
|
||||||
<h2 className="text-lg font-medium">Health Checks</h2>
|
<h2 className="text-lg font-medium">Health Checks</h2>
|
||||||
</span>
|
</span>
|
||||||
<span className="">Status: {volume.status ?? "Unknown"}</span>
|
{volume.lastError && <span className="text-md text-red-600 ">{volume.lastError}</span>}
|
||||||
<span className="text-sm text-muted-foreground mb-4">Checked {timeAgo || "never"}</span>
|
{volume.status === "mounted" && <span className="text-md text-green-600">Healthy</span>}
|
||||||
<span className="flex items-center">
|
{volume.status !== "unmounted" && (
|
||||||
Enable auto remount
|
<span className="text-xs text-muted-foreground mb-4">Checked {timeAgo || "never"}</span>
|
||||||
|
)}
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
Remount on error
|
||||||
<Switch className="ml-auto cursor-pointer" checked={volume.autoRemount} />
|
<Switch className="ml-auto cursor-pointer" checked={volume.autoRemount} />
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
import { WifiIcon } from "lucide-react";
|
|
||||||
import { useNavigate, useParams } from "react-router";
|
import { useNavigate, useParams } from "react-router";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { getVolume } from "~/api-client";
|
import { getVolume } from "~/api-client";
|
||||||
@@ -88,7 +87,7 @@ export default function DetailsPage({ loaderData }: Route.ComponentProps) {
|
|||||||
<>
|
<>
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold mb-0 uppercase">Volume: {name}</h1>
|
<h1 className="text-3xl font-bold mb-0 uppercase">{name}</h1>
|
||||||
<div className="text-sm font-semibold mb-2 text-muted-foreground flex items-center gap-2">
|
<div className="text-sm font-semibold mb-2 text-muted-foreground flex items-center gap-2">
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<StatusDot status={data.status} /> {data.status[0].toUpperCase() + data.status.slice(1)}
|
<StatusDot status={data.status} /> {data.status[0].toUpperCase() + data.status.slice(1)}
|
||||||
@@ -100,7 +99,7 @@ export default function DetailsPage({ loaderData }: Route.ComponentProps) {
|
|||||||
<Button
|
<Button
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
onClick={() => mountVol.mutate({ path: { name } })}
|
onClick={() => mountVol.mutate({ path: { name } })}
|
||||||
disabled={mountVol.isPending}
|
loading={mountVol.isPending}
|
||||||
className={cn({ hidden: data.status === "mounted" })}
|
className={cn({ hidden: data.status === "mounted" })}
|
||||||
>
|
>
|
||||||
Mount
|
Mount
|
||||||
@@ -108,7 +107,7 @@ export default function DetailsPage({ loaderData }: Route.ComponentProps) {
|
|||||||
<Button
|
<Button
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
onClick={() => unmountVol.mutate({ path: { name } })}
|
onClick={() => unmountVol.mutate({ path: { name } })}
|
||||||
disabled={unmountVol.isPending}
|
loading={unmountVol.isPending}
|
||||||
className={cn({ hidden: data.status !== "mounted" })}
|
className={cn({ hidden: data.status !== "mounted" })}
|
||||||
>
|
>
|
||||||
Unmount
|
Unmount
|
||||||
@@ -118,17 +117,15 @@ export default function DetailsPage({ loaderData }: Route.ComponentProps) {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-4">
|
<div className="grid gap-4 grid-cols-1 lg:grid-cols-3 lg:grid-rows-[auto_1fr]">
|
||||||
<Card className="my-4 p-6 flex-1">
|
<Card className="p-6 lg:col-span-2 lg:row-span-2">
|
||||||
<CreateVolumeForm initialValues={{ ...data, ...data?.config }} onSubmit={console.log} />
|
<CreateVolumeForm initialValues={{ ...data, ...data?.config }} onSubmit={console.log} />
|
||||||
</Card>
|
</Card>
|
||||||
<div className="flex flex-col my-4 gap-4">
|
|
||||||
<HealthchecksCard volume={data} />
|
<HealthchecksCard volume={data} />
|
||||||
<Card className="p-6 flex-1">
|
<Card className="p-6 h-full">
|
||||||
<h2 className="text-lg font-medium">Volume Information</h2>
|
<h2 className="text-lg font-medium">Volume Information</h2>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export const volumesTable = sqliteTable("volumes_table", {
|
|||||||
createdAt: int("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`),
|
createdAt: int("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`),
|
||||||
updatedAt: int("updated_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(),
|
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;
|
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 { volumeController } from "./modules/volumes/volume.controller";
|
||||||
import { logger } from "./utils/logger";
|
import { logger } from "./utils/logger";
|
||||||
import { startup } from "./modules/lifecycle/startup";
|
import { startup } from "./modules/lifecycle/startup";
|
||||||
|
import { handleServiceError } from "./utils/errors";
|
||||||
|
|
||||||
export const generalDescriptor = (app: Hono) =>
|
export const generalDescriptor = (app: Hono) =>
|
||||||
openAPISpecs(app, {
|
openAPISpecs(app, {
|
||||||
@@ -41,6 +42,18 @@ app.get("/", (c) => {
|
|||||||
return c.json({ message: "Welcome to the Ironmount API" });
|
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";
|
const socketPath = "/run/docker/plugins/ironmount.sock";
|
||||||
|
|
||||||
(async () => {
|
(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 fs from "node:fs/promises";
|
||||||
import * as os from "node:os";
|
import * as os from "node:os";
|
||||||
import * as npath from "node:path";
|
import * as npath from "node:path";
|
||||||
@@ -9,6 +9,7 @@ import { promisify } from "node:util";
|
|||||||
import { withTimeout } from "../../../utils/timeout";
|
import { withTimeout } from "../../../utils/timeout";
|
||||||
import { OPERATION_TIMEOUT } from "../../../core/constants";
|
import { OPERATION_TIMEOUT } from "../../../core/constants";
|
||||||
import { toMessage } from "../../../utils/errors";
|
import { toMessage } from "../../../utils/errors";
|
||||||
|
import { getMountForPath } from "../../../utils/mountinfo";
|
||||||
|
|
||||||
const execFile = promisify(execFileCb);
|
const execFile = promisify(execFileCb);
|
||||||
|
|
||||||
@@ -110,6 +111,12 @@ const checkHealth = async (path: string) => {
|
|||||||
logger.debug(`Checking health of NFS volume at ${path}...`);
|
logger.debug(`Checking health of NFS volume at ${path}...`);
|
||||||
await fs.access(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)}`);
|
const testFilePath = npath.join(path, `.healthcheck-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
|
||||||
|
|
||||||
await fs.writeFile(testFilePath, "healthcheck");
|
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 { db } from "../../db/db";
|
||||||
import { logger } from "../../utils/logger";
|
import { logger } from "../../utils/logger";
|
||||||
import { volumesTable } from "../../db/schema";
|
import { volumesTable } from "../../db/schema";
|
||||||
@@ -7,7 +7,10 @@ import { volumeService } from "../volumes/volume.service";
|
|||||||
|
|
||||||
export const startup = async () => {
|
export const startup = async () => {
|
||||||
const volumes = await db.query.volumesTable.findMany({
|
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) {
|
for (const volume of volumes) {
|
||||||
@@ -21,7 +24,7 @@ export const startup = async () => {
|
|||||||
logger.info("Running health check for all volumes...");
|
logger.info("Running health check for all volumes...");
|
||||||
|
|
||||||
const volumes = await db.query.volumesTable.findMany({
|
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) {
|
for (const volume of volumes) {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { validator } from "hono-openapi/arktype";
|
import { validator } from "hono-openapi/arktype";
|
||||||
import { handleServiceError } from "../../utils/errors";
|
|
||||||
import {
|
import {
|
||||||
createVolumeBody,
|
createVolumeBody,
|
||||||
createVolumeDto,
|
createVolumeDto,
|
||||||
@@ -37,12 +36,7 @@ export const volumeController = new Hono()
|
|||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
const res = await volumeService.createVolume(body.name, body.config);
|
const res = await volumeService.createVolume(body.name, body.config);
|
||||||
|
|
||||||
if (res.error) {
|
return c.json({ message: "Volume created", volume: res.volume }, 201);
|
||||||
const { message, status } = handleServiceError(res.error);
|
|
||||||
return c.json(message, status);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ message: "Volume created", volume: res.volume });
|
|
||||||
})
|
})
|
||||||
.post("/test-connection", testConnectionDto, validator("json", testConnectionBody), async (c) => {
|
.post("/test-connection", testConnectionDto, validator("json", testConnectionBody), async (c) => {
|
||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
@@ -52,24 +46,14 @@ export const volumeController = new Hono()
|
|||||||
})
|
})
|
||||||
.delete("/:name", deleteVolumeDto, async (c) => {
|
.delete("/:name", deleteVolumeDto, async (c) => {
|
||||||
const { name } = c.req.param();
|
const { name } = c.req.param();
|
||||||
const res = await volumeService.deleteVolume(name);
|
await volumeService.deleteVolume(name);
|
||||||
|
|
||||||
if (res.error) {
|
return c.json({ message: "Volume deleted" }, 200);
|
||||||
const { message, status } = handleServiceError(res.error);
|
|
||||||
return c.json(message, status);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ message: "Volume deleted" });
|
|
||||||
})
|
})
|
||||||
.get("/:name", getVolumeDto, async (c) => {
|
.get("/:name", getVolumeDto, async (c) => {
|
||||||
const { name } = c.req.param();
|
const { name } = c.req.param();
|
||||||
const res = await volumeService.getVolume(name);
|
const res = await volumeService.getVolume(name);
|
||||||
|
|
||||||
if (res.error) {
|
|
||||||
const { message, status } = handleServiceError(res.error);
|
|
||||||
return c.json(message, status);
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = {
|
const response = {
|
||||||
...res.volume,
|
...res.volume,
|
||||||
createdAt: res.volume.createdAt.getTime(),
|
createdAt: res.volume.createdAt.getTime(),
|
||||||
@@ -84,11 +68,6 @@ export const volumeController = new Hono()
|
|||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
const res = await volumeService.updateVolume(name, body.config);
|
const res = await volumeService.updateVolume(name, body.config);
|
||||||
|
|
||||||
if (res.error) {
|
|
||||||
const { message, status } = handleServiceError(res.error);
|
|
||||||
return c.json(message, status);
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = {
|
const response = {
|
||||||
message: "Volume updated",
|
message: "Volume updated",
|
||||||
volume: {
|
volume: {
|
||||||
@@ -105,23 +84,13 @@ export const volumeController = new Hono()
|
|||||||
})
|
})
|
||||||
.post("/:name/mount", mountVolumeDto, async (c) => {
|
.post("/:name/mount", mountVolumeDto, async (c) => {
|
||||||
const { name } = c.req.param();
|
const { name } = c.req.param();
|
||||||
const res = await volumeService.mountVolume(name);
|
const { error, status } = await volumeService.mountVolume(name);
|
||||||
|
|
||||||
if (res.error) {
|
return c.json({ error, status }, error ? 500 : 200);
|
||||||
const { message, status } = handleServiceError(res.error);
|
|
||||||
return c.json(message, status);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ message: "Volume mounted successfully" }, 200);
|
|
||||||
})
|
})
|
||||||
.post("/:name/unmount", unmountVolumeDto, async (c) => {
|
.post("/:name/unmount", unmountVolumeDto, async (c) => {
|
||||||
const { name } = c.req.param();
|
const { name } = c.req.param();
|
||||||
const res = await volumeService.unmountVolume(name);
|
const { error, status } = await volumeService.unmountVolume(name);
|
||||||
|
|
||||||
if (res.error) {
|
return c.json({ error, status }, error ? 500 : 200);
|
||||||
const { message, status } = handleServiceError(res.error);
|
|
||||||
return c.json(message, status);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ message: "Volume unmounted successfully" }, 200);
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ const volumeSchema = type({
|
|||||||
updatedAt: "number",
|
updatedAt: "number",
|
||||||
lastHealthCheck: "number",
|
lastHealthCheck: "number",
|
||||||
config: volumeConfigSchema,
|
config: volumeConfigSchema,
|
||||||
|
autoRemount: "0 | 1",
|
||||||
});
|
});
|
||||||
|
|
||||||
export type VolumeDto = typeof volumeSchema.infer;
|
export type VolumeDto = typeof volumeSchema.infer;
|
||||||
@@ -55,7 +56,6 @@ export const createVolumeResponse = type({
|
|||||||
volume: type({
|
volume: type({
|
||||||
name: "string",
|
name: "string",
|
||||||
path: "string",
|
path: "string",
|
||||||
createdAt: "number",
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -195,7 +195,8 @@ export const testConnectionDto = describeRoute({
|
|||||||
* Mount volume
|
* Mount volume
|
||||||
*/
|
*/
|
||||||
export const mountVolumeResponse = type({
|
export const mountVolumeResponse = type({
|
||||||
message: "string",
|
error: "string?",
|
||||||
|
status: type.enumerated("mounted", "unmounted", "error"),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const mountVolumeDto = describeRoute({
|
export const mountVolumeDto = describeRoute({
|
||||||
@@ -222,7 +223,8 @@ export const mountVolumeDto = describeRoute({
|
|||||||
* Unmount volume
|
* Unmount volume
|
||||||
*/
|
*/
|
||||||
export const unmountVolumeResponse = type({
|
export const unmountVolumeResponse = type({
|
||||||
message: "string",
|
error: "string?",
|
||||||
|
status: type.enumerated("mounted", "unmounted", "error"),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const unmountVolumeDto = describeRoute({
|
export const unmountVolumeDto = describeRoute({
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { config } from "../../core/config";
|
|||||||
import { db } from "../../db/db";
|
import { db } from "../../db/db";
|
||||||
import { volumesTable } from "../../db/schema";
|
import { volumesTable } from "../../db/schema";
|
||||||
import { createVolumeBackend } from "../backends/backend";
|
import { createVolumeBackend } from "../backends/backend";
|
||||||
import { logger } from "../../utils/logger";
|
|
||||||
import { toMessage } from "../../utils/errors";
|
import { toMessage } from "../../utils/errors";
|
||||||
|
|
||||||
const listVolumes = async () => {
|
const listVolumes = async () => {
|
||||||
@@ -26,7 +25,7 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
return { error: new ConflictError("Volume already exists") };
|
throw new ConflictError("Volume already exists");
|
||||||
}
|
}
|
||||||
|
|
||||||
const volumePathHost = path.join(config.volumeRootHost);
|
const volumePathHost = path.join(config.volumeRootHost);
|
||||||
@@ -45,82 +44,54 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const deleteVolume = async (name: string) => {
|
const deleteVolume = async (name: string) => {
|
||||||
try {
|
|
||||||
const volume = await db.query.volumesTable.findFirst({
|
const volume = await db.query.volumesTable.findFirst({
|
||||||
where: eq(volumesTable.name, name),
|
where: eq(volumesTable.name, name),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!volume) {
|
if (!volume) {
|
||||||
return { error: new NotFoundError("Volume not found") };
|
throw new NotFoundError("Volume not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const backend = createVolumeBackend(volume);
|
const backend = createVolumeBackend(volume);
|
||||||
await backend.unmount();
|
await backend.unmount();
|
||||||
await db.delete(volumesTable).where(eq(volumesTable.name, name));
|
await db.delete(volumesTable).where(eq(volumesTable.name, name));
|
||||||
return { status: 200 };
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
error: new InternalServerError("Failed to delete volume", {
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const mountVolume = async (name: string) => {
|
const mountVolume = async (name: string) => {
|
||||||
try {
|
|
||||||
const volume = await db.query.volumesTable.findFirst({
|
const volume = await db.query.volumesTable.findFirst({
|
||||||
where: eq(volumesTable.name, name),
|
where: eq(volumesTable.name, name),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!volume) {
|
if (!volume) {
|
||||||
return { error: new NotFoundError("Volume not found") };
|
throw new NotFoundError("Volume not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const backend = createVolumeBackend(volume);
|
const backend = createVolumeBackend(volume);
|
||||||
await backend.mount();
|
const { error, status } = await backend.mount();
|
||||||
|
|
||||||
await db
|
await db
|
||||||
.update(volumesTable)
|
.update(volumesTable)
|
||||||
.set({ status: "mounted", lastHealthCheck: new Date(), lastError: null })
|
.set({ status, lastError: error, lastHealthCheck: new Date() })
|
||||||
.where(eq(volumesTable.name, name));
|
.where(eq(volumesTable.name, name));
|
||||||
|
|
||||||
return { status: 200 };
|
return { error, status };
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
error: new InternalServerError("Failed to mount volume", {
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const unmountVolume = async (name: string) => {
|
const unmountVolume = async (name: string) => {
|
||||||
try {
|
|
||||||
const volume = await db.query.volumesTable.findFirst({
|
const volume = await db.query.volumesTable.findFirst({
|
||||||
where: eq(volumesTable.name, name),
|
where: eq(volumesTable.name, name),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!volume) {
|
if (!volume) {
|
||||||
return { error: new NotFoundError("Volume not found") };
|
throw new NotFoundError("Volume not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const backend = createVolumeBackend(volume);
|
const backend = createVolumeBackend(volume);
|
||||||
await backend.unmount();
|
const { status, error } = await backend.unmount();
|
||||||
|
|
||||||
await db
|
await db.update(volumesTable).set({ status }).where(eq(volumesTable.name, name));
|
||||||
.update(volumesTable)
|
|
||||||
.set({ status: "unmounted", lastHealthCheck: new Date() })
|
|
||||||
.where(eq(volumesTable.name, name));
|
|
||||||
|
|
||||||
return { status: 200 };
|
return { error, status };
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
error: new InternalServerError("Failed to unmount volume", {
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getVolume = async (name: string) => {
|
const getVolume = async (name: string) => {
|
||||||
@@ -129,20 +100,19 @@ const getVolume = async (name: string) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!volume) {
|
if (!volume) {
|
||||||
return { error: new NotFoundError("Volume not found") };
|
throw new NotFoundError("Volume not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
return { volume };
|
return { volume };
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateVolume = async (name: string, backendConfig: BackendConfig) => {
|
const updateVolume = async (name: string, backendConfig: BackendConfig) => {
|
||||||
try {
|
|
||||||
const existing = await db.query.volumesTable.findFirst({
|
const existing = await db.query.volumesTable.findFirst({
|
||||||
where: eq(volumesTable.name, name),
|
where: eq(volumesTable.name, name),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
return { error: new NotFoundError("Volume not found") };
|
throw new NotFoundError("Volume not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const [updated] = await db
|
const [updated] = await db
|
||||||
@@ -157,24 +127,14 @@ const updateVolume = async (name: string, backendConfig: BackendConfig) => {
|
|||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
if (!updated) {
|
if (!updated) {
|
||||||
return { error: new InternalServerError("Failed to update volume") };
|
throw new InternalServerError("Failed to update volume");
|
||||||
}
|
}
|
||||||
|
|
||||||
return { volume: updated };
|
return { volume: updated };
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
error: new InternalServerError("Failed to update volume", {
|
|
||||||
cause: error,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const testConnection = async (backendConfig: BackendConfig) => {
|
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 = {
|
const mockVolume = {
|
||||||
id: 0,
|
id: 0,
|
||||||
@@ -187,63 +147,41 @@ const testConnection = async (backendConfig: BackendConfig) => {
|
|||||||
type: backendConfig.backend,
|
type: backendConfig.backend,
|
||||||
status: "unmounted" as const,
|
status: "unmounted" as const,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
autoRemount: 0,
|
autoRemount: 0 as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
const backend = createVolumeBackend(mockVolume);
|
const backend = createVolumeBackend(mockVolume);
|
||||||
|
const { error } = await backend.mount();
|
||||||
|
|
||||||
await backend.mount();
|
|
||||||
await backend.unmount();
|
await backend.unmount();
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
message: "Connection successful",
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
message: toMessage(error),
|
|
||||||
};
|
|
||||||
} finally {
|
|
||||||
if (tempDir) {
|
|
||||||
try {
|
|
||||||
await fs.access(tempDir);
|
await fs.access(tempDir);
|
||||||
await fs.rm(tempDir, { recursive: true, force: true });
|
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) => {
|
const checkHealth = async (name: string) => {
|
||||||
try {
|
|
||||||
const volume = await db.query.volumesTable.findFirst({
|
const volume = await db.query.volumesTable.findFirst({
|
||||||
where: eq(volumesTable.name, name),
|
where: eq(volumesTable.name, name),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!volume) {
|
if (!volume) {
|
||||||
return { error: new NotFoundError("Volume not found") };
|
throw new NotFoundError("Volume not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const backend = createVolumeBackend(volume);
|
const backend = createVolumeBackend(volume);
|
||||||
const { error } = await backend.checkHealth();
|
const { error, status } = await backend.checkHealth();
|
||||||
|
|
||||||
if (error) {
|
|
||||||
await db
|
await db
|
||||||
.update(volumesTable)
|
.update(volumesTable)
|
||||||
.set({ status: "error", lastError: error, lastHealthCheck: new Date() })
|
.set({ lastHealthCheck: new Date(), status, lastError: error })
|
||||||
.where(eq(volumesTable.name, volume.name));
|
.where(eq(volumesTable.name, volume.name));
|
||||||
|
|
||||||
return { error };
|
return { status, 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 }) };
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const volumeService = {
|
export const volumeService = {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { ConflictError, NotFoundError } from "http-errors-enhanced";
|
import { ConflictError, NotFoundError } from "http-errors-enhanced";
|
||||||
import { logger } from "./logger";
|
|
||||||
|
|
||||||
export const handleServiceError = (error: unknown) => {
|
export const handleServiceError = (error: unknown) => {
|
||||||
if (error instanceof ConflictError) {
|
if (error instanceof ConflictError) {
|
||||||
@@ -10,8 +9,7 @@ export const handleServiceError = (error: unknown) => {
|
|||||||
return { message: error.message, status: 404 as const };
|
return { message: error.message, status: 404 as const };
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.error("Unhandled service error:", error);
|
return { message: toMessage(error), status: 500 as const };
|
||||||
return { message: "Internal Server Error", status: 500 as const };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const toMessage = (err: unknown): string => {
|
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