mirror of
https://github.com/Dokploy/dokploy.git
synced 2026-07-22 22:35:23 +02:00
feat(networks): enhance network management with server filtering and synchronization
- Added server filtering capability to the dashboard, allowing users to manage networks specific to selected servers. - Introduced SyncNetworks component for synchronizing Docker networks with Dokploy, enabling import of new networks and cleanup of stale records. - Updated HandleNetwork and ShowNetworks components to support server-specific operations, improving user experience and functionality. - Enhanced API to support network synchronization and importing, ensuring accurate data handling for network management.
This commit is contained in:
@@ -40,9 +40,6 @@ import { api } from "@/utils/api";
|
||||
// singletons and macvlan/ipvlan need driver options we don't expose.
|
||||
const networkDriverEnum = ["bridge", "overlay"] as const;
|
||||
|
||||
/** Sentinel for the local Dokploy server (no serverId) */
|
||||
const SERVER_LOCAL = "__server_local__";
|
||||
|
||||
const ipamConfigEntrySchema = z.object({
|
||||
subnet: z.string().optional(),
|
||||
ipRange: z.string().optional(),
|
||||
@@ -53,7 +50,6 @@ const networkFormSchema = z
|
||||
.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
driver: z.enum(networkDriverEnum),
|
||||
serverId: z.string().optional(),
|
||||
internal: z.boolean(),
|
||||
attachable: z.boolean(),
|
||||
enableIPv4: z.boolean(),
|
||||
@@ -85,7 +81,6 @@ type NetworkFormValues = z.infer<typeof networkFormSchema>;
|
||||
const defaultValues: NetworkFormValues = {
|
||||
name: "",
|
||||
driver: "bridge",
|
||||
serverId: undefined,
|
||||
internal: false,
|
||||
attachable: false,
|
||||
enableIPv4: true,
|
||||
@@ -119,17 +114,17 @@ const toggleOptions = [
|
||||
] as const;
|
||||
|
||||
interface HandleNetworkProps {
|
||||
/** Target server; undefined creates on the local Dokploy server */
|
||||
serverId?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
// Docker networks are immutable, so this dialog only creates them;
|
||||
// changing a network means deleting and recreating it.
|
||||
export const HandleNetwork = ({ children }: HandleNetworkProps) => {
|
||||
export const HandleNetwork = ({ serverId, children }: HandleNetworkProps) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const { data: isCloud } = api.settings.isCloud.useQuery();
|
||||
const utils = api.useUtils();
|
||||
|
||||
const { data: servers } = api.server.all.useQuery();
|
||||
const { mutateAsync, isPending } = api.network.create.useMutation();
|
||||
|
||||
const form = useForm<NetworkFormValues>({
|
||||
@@ -147,7 +142,7 @@ export const HandleNetwork = ({ children }: HandleNetworkProps) => {
|
||||
await mutateAsync({
|
||||
name: data.name,
|
||||
driver: data.driver,
|
||||
serverId: data.serverId || undefined,
|
||||
serverId,
|
||||
internal: data.internal,
|
||||
attachable: data.attachable,
|
||||
enableIPv4: data.enableIPv4,
|
||||
@@ -238,48 +233,6 @@ export const HandleNetwork = ({ children }: HandleNetworkProps) => {
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="serverId"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Server</FormLabel>
|
||||
<Select
|
||||
onValueChange={(value) =>
|
||||
field.onChange(value === SERVER_LOCAL ? undefined : value)
|
||||
}
|
||||
value={field.value ?? (isCloud ? undefined : SERVER_LOCAL)}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select server" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{!isCloud && (
|
||||
<SelectItem value={SERVER_LOCAL}>
|
||||
Dokploy server
|
||||
</SelectItem>
|
||||
)}
|
||||
{servers?.map((server) => (
|
||||
<SelectItem
|
||||
key={server.serverId}
|
||||
value={server.serverId}
|
||||
>
|
||||
{server.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription className="text-muted-foreground">
|
||||
{isCloud
|
||||
? "Server where this network will be created."
|
||||
: "Dokploy server is the default local server."}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{toggleOptions.map((option) => (
|
||||
<FormField
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Loader2, Network, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { HandleNetwork } from "@/components/dashboard/networks/handle-network";
|
||||
import { ShowNetworkConfig } from "@/components/dashboard/networks/show-network-config";
|
||||
import { SyncNetworks } from "@/components/dashboard/networks/sync-networks";
|
||||
import { DialogAction } from "@/components/shared/dialog-action";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -25,9 +26,14 @@ import {
|
||||
} from "@/components/ui/table";
|
||||
import { api } from "@/utils/api";
|
||||
|
||||
export const ShowNetworks = () => {
|
||||
interface Props {
|
||||
/** Selected server; undefined shows the local Dokploy server */
|
||||
serverId?: string;
|
||||
}
|
||||
|
||||
export const ShowNetworks = ({ serverId }: Props) => {
|
||||
const utils = api.useUtils();
|
||||
const { data: networks, isLoading } = api.network.all.useQuery();
|
||||
const { data: networks, isLoading } = api.network.all.useQuery({ serverId });
|
||||
const { mutateAsync: removeNetwork } = api.network.remove.useMutation();
|
||||
|
||||
return (
|
||||
@@ -40,14 +46,16 @@ export const ShowNetworks = () => {
|
||||
Networks
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Manage Docker networks for your organization. Networks can be
|
||||
scoped to a server (optional).
|
||||
Manage the Docker networks of the selected server.
|
||||
</CardDescription>
|
||||
{networks && networks.length > 0 && (
|
||||
<CardAction className="self-center">
|
||||
<HandleNetwork />
|
||||
</CardAction>
|
||||
)}
|
||||
<CardAction className="self-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<SyncNetworks serverId={serverId} />
|
||||
{networks && networks.length > 0 && (
|
||||
<HandleNetwork serverId={serverId} />
|
||||
)}
|
||||
</div>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-2 py-8 border-t">
|
||||
@@ -69,7 +77,7 @@ export const ShowNetworks = () => {
|
||||
started.
|
||||
</p>
|
||||
</div>
|
||||
<HandleNetwork />
|
||||
<HandleNetwork serverId={serverId} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-md border overflow-x-auto">
|
||||
@@ -78,9 +86,9 @@ export const ShowNetworks = () => {
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Driver</TableHead>
|
||||
<TableHead>Subnet</TableHead>
|
||||
<TableHead>Internal</TableHead>
|
||||
<TableHead>Attachable</TableHead>
|
||||
<TableHead>Server</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead className="w-[100px] text-right">
|
||||
Actions
|
||||
@@ -88,67 +96,99 @@ export const ShowNetworks = () => {
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{networks.map((n) => (
|
||||
<TableRow key={n.networkId}>
|
||||
<TableCell className="font-medium">{n.name}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">{n.driver}</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{n.driver === "overlay" ? "swarm" : "local"}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{n.internal ? "Yes" : "No"}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{n.attachable ? "Yes" : "No"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{n.server?.name ?? "Dokploy Server"}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{new Date(n.createdAt).toLocaleDateString()}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
<ShowNetworkConfig
|
||||
networkId={n.networkId}
|
||||
networkName={n.name}
|
||||
/>
|
||||
<DialogAction
|
||||
title="Delete network"
|
||||
description={`The network "${n.name}" will be removed from Docker and Dokploy. This action cannot be undone.`}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await removeNetwork({
|
||||
networkId: n.networkId,
|
||||
});
|
||||
toast.success("Network deleted");
|
||||
await utils.network.all.invalidate();
|
||||
} catch (error) {
|
||||
toast.error("Error deleting network", {
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Unknown error",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Delete network"
|
||||
{networks.map((n) => {
|
||||
const ipamEntries = (n.ipam?.config ?? []).filter(
|
||||
(c) => c.subnet || c.gateway || c.ipRange,
|
||||
);
|
||||
return (
|
||||
<TableRow key={n.networkId}>
|
||||
<TableCell className="font-medium">
|
||||
{n.name}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">{n.driver}</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{n.driver === "overlay" ? "swarm" : "local"}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{ipamEntries.length > 0 ? (
|
||||
<div className="flex flex-col gap-1">
|
||||
{ipamEntries.map((c, index) => (
|
||||
<div
|
||||
key={`${n.networkId}-ipam-${index}`}
|
||||
className="flex flex-col"
|
||||
>
|
||||
<span>{c.subnet ?? "—"}</span>
|
||||
{(c.gateway || c.ipRange) && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{[
|
||||
c.gateway && `gw ${c.gateway}`,
|
||||
c.ipRange && `range ${c.ipRange}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted-foreground">
|
||||
Auto
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{n.internal ? "Yes" : "No"}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{n.attachable ? "Yes" : "No"}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{new Date(n.createdAt).toLocaleDateString()}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
<ShowNetworkConfig
|
||||
networkId={n.networkId}
|
||||
networkName={n.name}
|
||||
/>
|
||||
<DialogAction
|
||||
title="Delete network"
|
||||
description={`The network "${n.name}" will be removed from Docker and Dokploy. This action cannot be undone.`}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await removeNetwork({
|
||||
networkId: n.networkId,
|
||||
});
|
||||
toast.success("Network deleted");
|
||||
await utils.network.all.invalidate();
|
||||
} catch (error) {
|
||||
toast.error("Error deleting network", {
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Unknown error",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</DialogAction>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Delete network"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</DialogAction>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
225
apps/dokploy/components/dashboard/networks/sync-networks.tsx
Normal file
225
apps/dokploy/components/dashboard/networks/sync-networks.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2, RefreshCw, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { AlertBlock } from "@/components/shared/alert-block";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { api } from "@/utils/api";
|
||||
|
||||
interface Props {
|
||||
/** Target server; undefined syncs the local Dokploy server */
|
||||
serverId?: string;
|
||||
}
|
||||
|
||||
// Compares the Docker daemon's networks against Dokploy's records:
|
||||
// networks that only exist in Docker can be imported, and records whose
|
||||
// network no longer exists in Docker can be cleaned up.
|
||||
export const SyncNetworks = ({ serverId }: Props) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const utils = api.useUtils();
|
||||
|
||||
const { data, isLoading, error, refetch } =
|
||||
api.network.networksToSync.useQuery({ serverId }, { enabled: open });
|
||||
|
||||
const importMutation = api.network.import.useMutation();
|
||||
const removeMutation = api.network.remove.useMutation();
|
||||
|
||||
const toggleSelected = (name: string) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(name)) {
|
||||
next.delete(name);
|
||||
} else {
|
||||
next.add(name);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const onImport = async () => {
|
||||
try {
|
||||
const result = await importMutation.mutateAsync({
|
||||
serverId,
|
||||
names: Array.from(selected),
|
||||
});
|
||||
|
||||
if (result.imported.length > 0) {
|
||||
toast.success(`Imported ${result.imported.length} network(s)`);
|
||||
}
|
||||
for (const failure of result.errors) {
|
||||
toast.error(`Could not import "${failure.name}"`, {
|
||||
description: failure.error,
|
||||
});
|
||||
}
|
||||
|
||||
setSelected(new Set());
|
||||
await utils.network.all.invalidate();
|
||||
|
||||
setOpen(false);
|
||||
await refetch();
|
||||
} catch (error) {
|
||||
toast.error("Error importing networks", {
|
||||
description: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onRemoveStale = async (networkId: string, name: string) => {
|
||||
try {
|
||||
await removeMutation.mutateAsync({ networkId });
|
||||
toast.success(`Removed stale record "${name}"`);
|
||||
await utils.network.all.invalidate();
|
||||
await refetch();
|
||||
} catch (error) {
|
||||
toast.error("Error removing record", {
|
||||
description: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(value) => {
|
||||
setOpen(value);
|
||||
if (!value) setSelected(new Set());
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline">
|
||||
<RefreshCw className="size-4" />
|
||||
Sync
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<RefreshCw className="size-5 text-muted-foreground" />
|
||||
Sync networks
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Import networks that exist in Docker but not in Dokploy, and clean
|
||||
up records whose network no longer exists.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{error ? (
|
||||
<AlertBlock type="error">{error.message}</AlertBlock>
|
||||
) : isLoading ? (
|
||||
<div className="flex flex-row gap-2 items-center justify-center py-10 text-sm text-muted-foreground">
|
||||
<span>Scanning Docker networks...</span>
|
||||
<Loader2 className="animate-spin size-4" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm font-medium">
|
||||
Found in Docker ({data?.importable.length ?? 0})
|
||||
</span>
|
||||
{data?.importable.length ? (
|
||||
data.importable.map((dockerNetwork) => (
|
||||
<label
|
||||
key={dockerNetwork.name}
|
||||
htmlFor={`import-network-${dockerNetwork.name}`}
|
||||
className="flex cursor-pointer items-center justify-between gap-3 rounded-lg border p-3"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Checkbox
|
||||
id={`import-network-${dockerNetwork.name}`}
|
||||
checked={selected.has(dockerNetwork.name)}
|
||||
onCheckedChange={() =>
|
||||
toggleSelected(dockerNetwork.name)
|
||||
}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-medium">
|
||||
{dockerNetwork.name}
|
||||
</span>
|
||||
{dockerNetwork.subnets.length > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{dockerNetwork.subnets.join(" · ")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="outline">{dockerNetwork.driver}</Badge>
|
||||
</label>
|
||||
))
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Nothing to import — everything is in sync.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!!data?.missing.length && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm font-medium">
|
||||
Missing in Docker ({data.missing.length})
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
These records exist in Dokploy but their network is gone
|
||||
from Docker.
|
||||
</span>
|
||||
{data.missing.map((stale) => (
|
||||
<div
|
||||
key={stale.networkId}
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-dashed p-3"
|
||||
>
|
||||
<span className="text-sm">{stale.name}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={`Remove stale record ${stale.name}`}
|
||||
isLoading={removeMutation.isPending}
|
||||
onClick={() =>
|
||||
onRemoveStale(stale.networkId, stale.name)
|
||||
}
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Close
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={selected.size === 0}
|
||||
isLoading={importMutation.isPending}
|
||||
onClick={onImport}
|
||||
>
|
||||
Import selected ({selected.size})
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -6,10 +6,15 @@ import type { ReactElement } from "react";
|
||||
import superjson from "superjson";
|
||||
import { ShowNetworks } from "@/components/dashboard/networks/show-networks";
|
||||
import { DashboardLayout } from "@/components/layouts/dashboard-layout";
|
||||
import { ServerFilter } from "@/components/shared/server-filter";
|
||||
import { appRouter } from "@/server/api/root";
|
||||
|
||||
const Dashboard = () => {
|
||||
return <ShowNetworks />;
|
||||
return (
|
||||
<ServerFilter>
|
||||
{(serverId) => <ShowNetworks serverId={serverId} />}
|
||||
</ServerFilter>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
@@ -69,7 +74,7 @@ export async function getServerSideProps(
|
||||
}
|
||||
}
|
||||
|
||||
await helpers.network.all.prefetch();
|
||||
await helpers.network.all.prefetch({});
|
||||
|
||||
return {
|
||||
props: {
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import {
|
||||
createNetwork,
|
||||
findNetworkById,
|
||||
findNetworksToSync,
|
||||
importDockerNetworks,
|
||||
inspectNetwork,
|
||||
removeNetwork,
|
||||
} from "@dokploy/server";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
|
||||
import { db } from "@/server/db";
|
||||
import {
|
||||
@@ -16,21 +19,20 @@ import {
|
||||
} from "@/server/db/schema";
|
||||
|
||||
export const networkRouter = createTRPCRouter({
|
||||
all: protectedProcedure.query(async ({ ctx }) => {
|
||||
const rows = await db.query.network.findMany({
|
||||
where: eq(networkTable.organizationId, ctx.session.activeOrganizationId),
|
||||
with: {
|
||||
server: {
|
||||
columns: {
|
||||
serverId: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: desc(networkTable.createdAt),
|
||||
});
|
||||
return rows;
|
||||
}),
|
||||
all: protectedProcedure
|
||||
.input(z.object({ serverId: z.string().optional() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const rows = await db.query.network.findMany({
|
||||
where: and(
|
||||
eq(networkTable.organizationId, ctx.session.activeOrganizationId),
|
||||
input.serverId
|
||||
? eq(networkTable.serverId, input.serverId)
|
||||
: isNull(networkTable.serverId),
|
||||
),
|
||||
orderBy: desc(networkTable.createdAt),
|
||||
});
|
||||
return rows;
|
||||
}),
|
||||
|
||||
one: protectedProcedure
|
||||
.input(apiFindOneNetwork)
|
||||
@@ -49,6 +51,30 @@ export const networkRouter = createTRPCRouter({
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return createNetwork(input, ctx.session.activeOrganizationId);
|
||||
}),
|
||||
networksToSync: protectedProcedure
|
||||
.input(z.object({ serverId: z.string().optional() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
return findNetworksToSync(
|
||||
ctx.session.activeOrganizationId,
|
||||
input.serverId ?? null,
|
||||
);
|
||||
}),
|
||||
|
||||
import: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
serverId: z.string().optional(),
|
||||
names: z.array(z.string().min(1)).min(1),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return importDockerNetworks(
|
||||
ctx.session.activeOrganizationId,
|
||||
input.serverId ?? null,
|
||||
input.names,
|
||||
);
|
||||
}),
|
||||
|
||||
inspect: protectedProcedure
|
||||
.input(apiFindOneNetwork)
|
||||
.query(async ({ ctx, input }) => {
|
||||
|
||||
@@ -1,11 +1,183 @@
|
||||
import { db } from "@dokploy/server/db";
|
||||
import { type apiCreateNetwork, network } from "@dokploy/server/db/schema";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import type { z } from "zod";
|
||||
import { IS_CLOUD } from "../constants";
|
||||
import { getRemoteDocker } from "../utils/servers/remote-docker";
|
||||
|
||||
// Networks managed by Docker/Dokploy itself that must never be imported
|
||||
// or deleted through the networks UI
|
||||
const RESERVED_NETWORKS = [
|
||||
"bridge",
|
||||
"host",
|
||||
"none",
|
||||
"ingress",
|
||||
"docker_gwbridge",
|
||||
"dokploy-network",
|
||||
];
|
||||
|
||||
type DockerNetworkInfo = {
|
||||
Name: string;
|
||||
Driver: string;
|
||||
Internal?: boolean;
|
||||
Attachable?: boolean;
|
||||
Ingress?: boolean;
|
||||
EnableIPv4?: boolean;
|
||||
EnableIPv6?: boolean;
|
||||
IPAM?: {
|
||||
Driver?: string;
|
||||
Config?: Array<{
|
||||
Subnet?: string;
|
||||
Gateway?: string;
|
||||
IPRange?: string;
|
||||
}> | null;
|
||||
};
|
||||
};
|
||||
|
||||
const isImportableDockerNetwork = (dockerNetwork: DockerNetworkInfo) =>
|
||||
!RESERVED_NETWORKS.includes(dockerNetwork.Name) &&
|
||||
!dockerNetwork.Ingress &&
|
||||
(dockerNetwork.Driver === "bridge" || dockerNetwork.Driver === "overlay");
|
||||
|
||||
const mapDockerNetworkToRow = (
|
||||
dockerNetwork: DockerNetworkInfo,
|
||||
organizationId: string,
|
||||
serverId: string | null,
|
||||
) => ({
|
||||
name: dockerNetwork.Name,
|
||||
driver: dockerNetwork.Driver as "bridge" | "overlay",
|
||||
internal: dockerNetwork.Internal ?? false,
|
||||
attachable: dockerNetwork.Attachable ?? false,
|
||||
// Older daemons don't report EnableIPv4; IPv4 is always on there
|
||||
enableIPv4: dockerNetwork.EnableIPv4 ?? true,
|
||||
enableIPv6: dockerNetwork.EnableIPv6 ?? false,
|
||||
ipam: {
|
||||
driver: dockerNetwork.IPAM?.Driver,
|
||||
config: (dockerNetwork.IPAM?.Config ?? []).map((c) => ({
|
||||
subnet: c.Subnet,
|
||||
gateway: c.Gateway,
|
||||
ipRange: c.IPRange,
|
||||
})),
|
||||
},
|
||||
organizationId,
|
||||
serverId,
|
||||
});
|
||||
|
||||
const findNetworksByServer = async (
|
||||
organizationId: string,
|
||||
serverId: string | null,
|
||||
) => {
|
||||
return await db.query.network.findMany({
|
||||
where: and(
|
||||
eq(network.organizationId, organizationId),
|
||||
serverId ? eq(network.serverId, serverId) : isNull(network.serverId),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
export const findNetworksToSync = async (
|
||||
organizationId: string,
|
||||
serverId: string | null,
|
||||
) => {
|
||||
if (IS_CLOUD && !serverId) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Server is required",
|
||||
});
|
||||
}
|
||||
|
||||
const docker = await getRemoteDocker(serverId);
|
||||
let dockerNetworks: DockerNetworkInfo[] = [];
|
||||
try {
|
||||
dockerNetworks = (await docker.listNetworks()) as DockerNetworkInfo[];
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to list Docker networks",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const existing = await findNetworksByServer(organizationId, serverId);
|
||||
const existingNames = new Set(existing.map((row) => row.name));
|
||||
const dockerNames = new Set(dockerNetworks.map((d) => d.Name));
|
||||
|
||||
const importable = dockerNetworks
|
||||
.filter(
|
||||
(dockerNetwork) =>
|
||||
isImportableDockerNetwork(dockerNetwork) &&
|
||||
!existingNames.has(dockerNetwork.Name),
|
||||
)
|
||||
.map((dockerNetwork) => ({
|
||||
name: dockerNetwork.Name,
|
||||
driver: dockerNetwork.Driver,
|
||||
internal: dockerNetwork.Internal ?? false,
|
||||
attachable: dockerNetwork.Attachable ?? false,
|
||||
subnets: (dockerNetwork.IPAM?.Config ?? [])
|
||||
.map((c) => c.Subnet)
|
||||
.filter((s): s is string => !!s),
|
||||
}));
|
||||
|
||||
// Rows in Dokploy whose network no longer exists in Docker
|
||||
const missing = existing
|
||||
.filter((row) => !dockerNames.has(row.name))
|
||||
.map((row) => ({ networkId: row.networkId, name: row.name }));
|
||||
|
||||
return { importable, missing };
|
||||
};
|
||||
|
||||
export const importDockerNetworks = async (
|
||||
organizationId: string,
|
||||
serverId: string | null,
|
||||
names: string[],
|
||||
) => {
|
||||
if (IS_CLOUD && !serverId) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Server is required",
|
||||
});
|
||||
}
|
||||
|
||||
const docker = await getRemoteDocker(serverId);
|
||||
const existing = await findNetworksByServer(organizationId, serverId);
|
||||
const existingNames = new Set(existing.map((row) => row.name));
|
||||
|
||||
const imported: string[] = [];
|
||||
const errors: { name: string; error: string }[] = [];
|
||||
|
||||
for (const name of names) {
|
||||
if (existingNames.has(name)) {
|
||||
errors.push({ name, error: "Already imported" });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const info = (await docker
|
||||
.getNetwork(name)
|
||||
.inspect()) as DockerNetworkInfo;
|
||||
if (!isImportableDockerNetwork(info)) {
|
||||
errors.push({ name, error: "Network is reserved or not supported" });
|
||||
continue;
|
||||
}
|
||||
await db
|
||||
.insert(network)
|
||||
.values(mapDockerNetworkToRow(info, organizationId, serverId));
|
||||
imported.push(name);
|
||||
} catch (error) {
|
||||
errors.push({
|
||||
name,
|
||||
error:
|
||||
error instanceof Error ? error.message : "Failed to inspect network",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { imported, errors };
|
||||
};
|
||||
|
||||
export const findNetworkById = async (networkId: string) => {
|
||||
const [row] = await db
|
||||
.select()
|
||||
|
||||
Reference in New Issue
Block a user