Container stats and actions

This commit is contained in:
2025-12-30 13:40:36 +01:00
parent baddd5e4a2
commit 7dd0dca73c
7 changed files with 198 additions and 24 deletions
+54
View File
@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from "next/server";
import testAuth from "../../auth";
import { StatusCodes } from "http-status-codes";
import { startContainer, stopContainer } from "@/core/server/docker";
export async function POST(req: NextRequest): Promise<NextResponse> {
const auth = await testAuth(req);
const id = req.nextUrl.searchParams.get("containerId");
if (!id) {
return NextResponse.json(
{ message: "Invalid containerId param" },
{ status: StatusCodes.BAD_REQUEST }
);
}
if (auth) {
return NextResponse.json(
{ message: auth },
{ status: StatusCodes.UNAUTHORIZED }
);
}
await startContainer(id);
return NextResponse.json({
message: "ok",
});
}
export async function DELETE(req: NextRequest): Promise<NextResponse> {
const auth = await testAuth(req);
const id = req.nextUrl.searchParams.get("containerId");
if (!id) {
return NextResponse.json(
{ message: "Invalid containerId param" },
{ status: StatusCodes.BAD_REQUEST }
);
}
if (auth) {
return NextResponse.json(
{ message: auth },
{ status: StatusCodes.UNAUTHORIZED }
);
}
await stopContainer(id);
return NextResponse.json({
message: "ok",
});
}
+33
View File
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import testAuth from "../../auth";
import { StatusCodes } from "http-status-codes";
import { getContainerStats } from "@/core/server/docker";
export async function GET(req: NextRequest): Promise<NextResponse> {
const auth = await testAuth(req);
const id = req.nextUrl.searchParams.get("containerId");
if (!id) {
return NextResponse.json(
{ message: "Invalid containerId param" },
{ status: StatusCodes.BAD_REQUEST }
);
}
if (auth) {
return NextResponse.json(
{ message: auth },
{ status: StatusCodes.UNAUTHORIZED }
);
}
const stats = await getContainerStats(id);
return NextResponse.json({
message: "ok",
stats: {
cpu_stats: stats?.cpu_stats,
memory_stats: stats?.memory_stats,
},
});
}
+35 -20
View File
@@ -4,18 +4,17 @@ import { DashboardLayout } from "@/components/dashboard/DashboardLayout";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import { MoreVertical, Play, Square, Trash2, Container } from "lucide-react";
MoreVertical,
Play,
Square,
Trash2,
Container,
} from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Docker } from "@/lib/types";
import { getDocker } from "@/core/docker"; import { getDocker } from "@/core/docker";
import { getNodes } from "@/core/node"; import { getNodes } from "@/core/node";
import { ContainerInfo } from "dockerode"; import { ContainerInfo } from "dockerode";
import { formatBytes } from "@/lib/format";
import {
getContainerStats,
startContainer,
stopContainer,
} from "@/core/docker";
type ContainerSummary = { type ContainerSummary = {
id: string; id: string;
@@ -24,16 +23,16 @@ type ContainerSummary = {
node: string; node: string;
status: "running" | "stopped"; status: "running" | "stopped";
uptime: string; uptime: string;
cpu: string; cpu: number;
memory: string; memory: string;
}; };
function summarizeContainer( async function summarizeContainer(
container: ContainerInfo, container: ContainerInfo,
nodeName: string nodeName: string
): ContainerSummary { ): Promise<ContainerSummary> {
// 1. Shorten the long container ID // 1. Shorten the long container ID
const shortId = container.Id.slice(0, 12); const shortId = container.Id;
// 2. Clean the name // 2. Clean the name
const name = container.Names[0]?.replace(/^\//, "") ?? "unknown"; const name = container.Names[0]?.replace(/^\//, "") ?? "unknown";
@@ -44,9 +43,13 @@ function summarizeContainer(
// 4. Compute uptime from Status string (if available) // 4. Compute uptime from Status string (if available)
const uptime = container.Status?.replace(/^Up\s*/, "") ?? "unknown"; const uptime = container.Status?.replace(/^Up\s*/, "") ?? "unknown";
// 5. Placeholder for CPU and memory const stats = await getContainerStats(container.Id);
const cpu = "4%";
const memory = "64MB / 128MB"; // 5. CPU and memory
const cpu = stats?.cpu_stats?.cpu_usage?.total_usage || 0;
const memory = `${formatBytes(
stats?.memory_stats?.usage || 0
)} / ${formatBytes(stats?.memory_stats?.max_usage || 0)}`;
return { return {
id: shortId, id: shortId,
@@ -69,8 +72,12 @@ export default function ContainersPage() {
const dockerNodes = await getDocker(nodes); const dockerNodes = await getDocker(nodes);
setContainers( setContainers(
nodes.flatMap((node, i) => await Promise.all(
dockerNodes[i].containers.map((c) => summarizeContainer(c, node.name)) nodes.flatMap((node, i) =>
dockerNodes[i].containers.map((c) =>
summarizeContainer(c, node.name)
)
)
) )
); );
}; };
@@ -131,7 +138,7 @@ export default function ContainersPage() {
{container.name} {container.name}
</div> </div>
<div className="text-[10px] text-muted-foreground font-mono"> <div className="text-[10px] text-muted-foreground font-mono">
{container.id} {container.id.slice(0, 12)}
</div> </div>
</div> </div>
</div> </div>
@@ -160,11 +167,19 @@ export default function ContainersPage() {
<td className="py-3 px-4"> <td className="py-3 px-4">
<div className="flex justify-end gap-1"> <div className="flex justify-end gap-1">
{container.status === "running" ? ( {container.status === "running" ? (
<Button variant="ghost" size="icon-sm"> <Button
variant="ghost"
size="icon-sm"
onClick={() => stopContainer(container.id)}
>
<Square className="w-3 h-3" /> <Square className="w-3 h-3" />
</Button> </Button>
) : ( ) : (
<Button variant="ghost" size="icon-sm"> <Button
variant="ghost"
size="icon-sm"
onClick={() => startContainer(container.id)}
>
<Play className="w-3 h-3" /> <Play className="w-3 h-3" />
</Button> </Button>
)} )}
+5 -1
View File
@@ -120,7 +120,11 @@ export default function OverviewPage() {
/> />
<StatCard <StatCard
title="Containers" title="Containers"
value={dockerNodes.reduce((sum, n) => sum + n.containers.length, 0)} value={dockerNodes.reduce(
(sum, n) =>
sum + n.containers.filter((c) => c.State === "running").length,
0
)}
subtitle="running" subtitle="running"
icon={<Container className="w-4 h-4" />} icon={<Container className="w-4 h-4" />}
/> />
+55 -1
View File
@@ -3,6 +3,8 @@
import axios from "axios"; import axios from "axios";
import { Docker, Node } from "@/lib/types"; import { Docker, Node } from "@/lib/types";
import { verifySession } from "./auth/session"; import { verifySession } from "./auth/session";
import { ContainerStats } from "dockerode";
import { getNodes } from "./node";
export async function getDocker(nodes: Node[]): Promise<Docker[]> { export async function getDocker(nodes: Node[]): Promise<Docker[]> {
if (await verifySession()) return []; if (await verifySession()) return [];
@@ -10,7 +12,7 @@ export async function getDocker(nodes: Node[]): Promise<Docker[]> {
return await Promise.all( return await Promise.all(
nodes.map(async (node) => { nodes.map(async (node) => {
const data = await ( const data = await (
await axios.get(`http://${node.ip}:3000/api/get-docker`, { await axios.get(`http://${node.ip}:3000/api/container/`, {
headers: { Authorization: `ApiKey ${node.key}` }, headers: { Authorization: `ApiKey ${node.key}` },
}) })
).data; ).data;
@@ -19,3 +21,55 @@ export async function getDocker(nodes: Node[]): Promise<Docker[]> {
}) })
); );
} }
export async function getContainerStats(
containerId: string
): Promise<ContainerStats | undefined> {
const nodes = await getNodes();
return (
await Promise.all(
nodes.map(
async (n) =>
await (
await axios.get(`http://${n.ip}:3000/api/container/stats`, {
headers: { Authorization: `ApiKey ${n.key}` },
params: { containerId },
})
).data
)
)
).find((s) => s);
}
export async function startContainer(containerId: string) {
const nodes = await getNodes();
nodes.forEach(
async (n) =>
await (
await axios.post(
`http://${n.ip}:3000/api/container/start`,
{ containerId },
{
headers: { Authorization: `ApiKey ${n.key}` },
params: { containerId },
}
)
).data
);
}
export async function stopContainer(containerId: string) {
const nodes = await getNodes();
nodes.forEach(
async (n) =>
await (
await axios.delete(`http://${n.ip}:3000/api/container/start`, {
headers: { Authorization: `ApiKey ${n.key}` },
params: { containerId },
})
).data
);
}
+16 -2
View File
@@ -1,11 +1,25 @@
"use server"; "use server";
import Docker from "dockerode"; import Docker, { ContainerStats } from "dockerode";
const docker = new Docker(); const docker = new Docker();
export async function getDocker() { export async function getDocker() {
const version = await docker.version(); const version = await docker.version();
const containers = await docker.listContainers(); const containers = await docker.listContainers({ all: true });
return { version, containers }; return { version, containers };
} }
export async function getContainerStats(
containerId: string
): Promise<ContainerStats | undefined> {
return await (await docker.getContainer(containerId)).stats();
}
export async function startContainer(containerId: string) {
await docker.getContainer(containerId).start();
}
export async function stopContainer(containerId: string) {
await docker.getContainer(containerId).stop();
}