Skip to content

Commit dd2937a

Browse files
feat: add docker container table (#520)
* WIP On docker integration * WIP on adding docker support * WIP on adding docker support * chore: Add cacheTime parameter to createCacheChannel function * bugfix: Add node-loader npm dependency for webpack configuration * revert changes * chore: Add node-loader npm dependency for webpack configuration * feat: Add Docker container list to DockerPage * chore: apply pr suggestions * fix: fix printing issue using a Date objext * chore: Update npm dependencies * feat: Create DockerTable component for displaying Docker container list * feat: Refactor DockerPage to use DockerTable component * feat: Refactor DockerPage to use DockerTable component * feat: Add useTimeAgo hook for displaying relative timestamps * feat: Add hooks module to common package * refactor: Update DockerTable component Include container actions and state badges * feat: add information about instance for docker containers * feat: Add OverflowBadge component for displaying overflowed data * feat: Refactor DockerSingleton to use host and instance properties This commit refactors the DockerSingleton class in the `docker.ts` file to use the `host` and `instance` properties instead of the previous `key` and `remoteApi` properties. This change improves clarity and consistency in the codebase. * feat: Add OverflowBadge component for displaying overflowed data * feat: Improve DockerTable component with Avatar and Name column This commit enhances the DockerTable component in the `DockerTable.tsx` file by adding an Avatar and Name column. The Avatar column displays an icon based on the Docker container's image, while the Name column shows the container's name. This improvement provides better visual representation and identification of the containers in the table. * feat: Enhance DockerTable component with Avatar and Name columns * refactor: improve docker table and icon resolution * chore: address pull request feedback * fix: format issues * chore: add missing translations * refactor: remove black background --------- Co-authored-by: Meier Lukas <[email protected]>
1 parent e030e06 commit dd2937a

File tree

19 files changed

+1057
-77
lines changed

19 files changed

+1057
-77
lines changed

apps/nextjs/next.config.mjs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Importing env files here to validate on build
2-
import "./src/env.mjs";
32
import "@homarr/auth/env.mjs";
3+
import "./src/env.mjs";
44

55
/** @type {import("next").NextConfig} */
66
const config = {
@@ -9,6 +9,15 @@ const config = {
99
/** We already do linting and typechecking as separate tasks in CI */
1010
eslint: { ignoreDuringBuilds: true },
1111
typescript: { ignoreBuildErrors: true },
12+
webpack: (config) => {
13+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
14+
config.module.rules.push({
15+
test: /\.node$/,
16+
loader: "node-loader",
17+
});
18+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
19+
return config;
20+
},
1221
experimental: {
1322
optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"],
1423
},

apps/nextjs/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,13 @@
4848
"@xterm/addon-fit": "0.10.0",
4949
"@xterm/xterm": "^5.5.0",
5050
"chroma-js": "^2.4.2",
51+
"clsx": "^2.1.1",
5152
"dayjs": "^1.11.11",
5253
"dotenv": "^16.4.5",
5354
"flag-icons": "^7.2.3",
5455
"glob": "^10.4.1",
5556
"jotai": "^2.8.2",
57+
"mantine-react-table": "2.0.0-beta.3",
5658
"next": "^14.2.3",
5759
"postcss-preset-mantine": "^1.15.0",
5860
"react": "18.3.1",
@@ -72,6 +74,7 @@
7274
"@types/react-dom": "^18.3.0",
7375
"concurrently": "^8.2.2",
7476
"eslint": "^8.57.0",
77+
"node-loader": "^2.0.0",
7578
"prettier": "^3.2.5",
7679
"tsx": "4.11.0",
7780
"typescript": "^5.4.5"
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
"use client";
2+
3+
import type { ButtonProps, MantineColor } from "@mantine/core";
4+
import { Avatar, Badge, Box, Button, Group, Text } from "@mantine/core";
5+
import { IconPlayerPlay, IconPlayerStop, IconRotateClockwise, IconTrash } from "@tabler/icons-react";
6+
import type { MRT_ColumnDef } from "mantine-react-table";
7+
import { MantineReactTable, useMantineReactTable } from "mantine-react-table";
8+
9+
import type { RouterOutputs } from "@homarr/api";
10+
import { useTimeAgo } from "@homarr/common";
11+
import type { DockerContainerState } from "@homarr/definitions";
12+
import type { TranslationFunction } from "@homarr/translation";
13+
import { useI18n, useScopedI18n } from "@homarr/translation/client";
14+
import { OverflowBadge } from "@homarr/ui";
15+
16+
const createColumns = (
17+
t: TranslationFunction,
18+
): MRT_ColumnDef<RouterOutputs["docker"]["getContainers"]["containers"][number]>[] => [
19+
{
20+
accessorKey: "name",
21+
header: t("docker.field.name.label"),
22+
Cell({ renderedCellValue, row }) {
23+
return (
24+
<Group gap="xs">
25+
<Avatar variant="outline" radius="lg" size="md" src={row.original.iconUrl}>
26+
{row.original.name.at(0)?.toUpperCase()}
27+
</Avatar>
28+
<Text>{renderedCellValue}</Text>
29+
</Group>
30+
);
31+
},
32+
},
33+
{
34+
accessorKey: "state",
35+
header: t("docker.field.state.label"),
36+
size: 120,
37+
Cell({ cell }) {
38+
return <ContainerStateBadge state={cell.row.original.state} />;
39+
},
40+
},
41+
{
42+
accessorKey: "image",
43+
header: t("docker.field.containerImage.label"),
44+
maxSize: 200,
45+
Cell({ renderedCellValue }) {
46+
return (
47+
<Box maw={200}>
48+
<Text truncate="end">{renderedCellValue}</Text>
49+
</Box>
50+
);
51+
},
52+
},
53+
{
54+
accessorKey: "ports",
55+
header: t("docker.field.ports.label"),
56+
Cell({ cell }) {
57+
return (
58+
<OverflowBadge overflowCount={1} data={cell.row.original.ports.map((port) => port.PrivatePort.toString())} />
59+
);
60+
},
61+
},
62+
];
63+
64+
export function DockerTable({ containers, timestamp }: RouterOutputs["docker"]["getContainers"]) {
65+
const t = useI18n();
66+
const tDocker = useScopedI18n("docker");
67+
const relativeTime = useTimeAgo(timestamp);
68+
const table = useMantineReactTable({
69+
data: containers,
70+
enableDensityToggle: false,
71+
enableColumnActions: false,
72+
enableColumnFilters: false,
73+
enablePagination: false,
74+
enableRowSelection: true,
75+
positionToolbarAlertBanner: "top",
76+
enableTableFooter: false,
77+
enableBottomToolbar: false,
78+
positionGlobalFilter: "right",
79+
mantineSearchTextInputProps: {
80+
placeholder: tDocker("table.search", { count: containers.length }),
81+
style: { minWidth: 300 },
82+
autoFocus: true,
83+
},
84+
85+
initialState: { density: "xs", showGlobalFilter: true },
86+
renderToolbarAlertBannerContent: ({ groupedAlert, table }) => {
87+
return (
88+
<Group gap={"sm"}>
89+
{groupedAlert}
90+
<Text fw={500}>
91+
{tDocker("table.selected", {
92+
selectCount: table.getSelectedRowModel().rows.length,
93+
totalCount: table.getRowCount(),
94+
})}
95+
</Text>
96+
<ContainerActionBar />
97+
</Group>
98+
);
99+
},
100+
101+
columns: createColumns(t),
102+
});
103+
return (
104+
<>
105+
<Text>{tDocker("table.updated", { when: relativeTime })}</Text>
106+
<MantineReactTable table={table} />
107+
</>
108+
);
109+
}
110+
111+
const ContainerActionBar = () => {
112+
const t = useScopedI18n("docker.action");
113+
const sharedButtonProps = {
114+
variant: "light",
115+
radius: "md",
116+
} satisfies Partial<ButtonProps>;
117+
118+
return (
119+
<Group gap="xs">
120+
<Button leftSection={<IconPlayerPlay />} color="green" {...sharedButtonProps}>
121+
{t("start")}
122+
</Button>
123+
<Button leftSection={<IconPlayerStop />} color="red" {...sharedButtonProps}>
124+
{t("stop")}
125+
</Button>
126+
<Button leftSection={<IconRotateClockwise />} color="orange" {...sharedButtonProps}>
127+
{t("restart")}
128+
</Button>
129+
<Button leftSection={<IconTrash />} color="red" {...sharedButtonProps}>
130+
{t("remove")}
131+
</Button>
132+
</Group>
133+
);
134+
};
135+
136+
const containerStates = {
137+
created: "cyan",
138+
running: "green",
139+
paused: "yellow",
140+
restarting: "orange",
141+
exited: "red",
142+
removing: "pink",
143+
dead: "dark",
144+
} satisfies Record<DockerContainerState, MantineColor>;
145+
146+
const ContainerStateBadge = ({ state }: { state: DockerContainerState }) => {
147+
const t = useScopedI18n("docker.field.state.option");
148+
149+
return (
150+
<Badge size="lg" radius="sm" variant="light" w={120} color={containerStates[state]}>
151+
{t(state)}
152+
</Badge>
153+
);
154+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { Stack, Title } from "@mantine/core";
2+
3+
import { api } from "@homarr/api/server";
4+
import { getScopedI18n } from "@homarr/translation/server";
5+
6+
import { DockerTable } from "./DockerTable";
7+
8+
export default async function DockerPage() {
9+
const { containers, timestamp } = await api.docker.getContainers();
10+
const tDocker = await getScopedI18n("docker");
11+
12+
return (
13+
<Stack>
14+
<Title order={1}>{tDocker("title")}</Title>
15+
<DockerTable containers={containers} timestamp={timestamp} />
16+
</Stack>
17+
);
18+
}

apps/nextjs/src/env.mjs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ export const env = createEnv({
2727
DB_USER: isUsingDbCredentials ? z.string() : z.string().optional(),
2828
DB_PASSWORD: isUsingDbCredentials ? z.string() : z.string().optional(),
2929
DB_NAME: isUsingDbUrl ? z.string().optional() : z.string(),
30+
// Comma separated list of docker hostnames that can be used to connect to query the docker endpoints (localhost:2375,host.docker.internal:2375, ...)
31+
DOCKER_HOSTNAMES: z.string().optional(),
32+
DOCKER_PORTS: z.number().optional(),
3033
},
3134
/**
3235
* Specify your client-side environment variables schema here.
@@ -49,6 +52,8 @@ export const env = createEnv({
4952
DB_PORT: process.env.DB_PORT,
5053
DB_DRIVER: process.env.DB_DRIVER,
5154
NODE_ENV: process.env.NODE_ENV,
55+
DOCKER_HOSTNAMES: process.env.DOCKER_HOSTNAMES,
56+
DOCKER_PORTS: process.env.DOCKER_PORTS,
5257
// NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
5358
},
5459
skipValidation:

apps/websocket/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"type": "module",
99
"scripts": {
1010
"dev": "pnpm with-env tsx ./src/main.ts",
11-
"build": "esbuild src/main.ts --bundle --platform=node --outfile=wssServer.cjs --external:bcrypt --loader:.html=text",
11+
"build": "esbuild src/main.ts --bundle --platform=node --outfile=wssServer.cjs --external:bcrypt --loader:.html=text --loader:.node=text",
1212
"clean": "rm -rf .turbo node_modules",
1313
"lint": "eslint .",
1414
"format": "prettier --check . --ignore-path ../../.gitignore",

packages/api/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,14 @@
3131
"@homarr/server-settings": "workspace:^0.1.0",
3232
"@trpc/client": "next",
3333
"@trpc/server": "next",
34+
"dockerode": "^4.0.2",
3435
"superjson": "2.2.1"
3536
},
3637
"devDependencies": {
3738
"@homarr/eslint-config": "workspace:^0.2.0",
3839
"@homarr/prettier-config": "workspace:^0.1.0",
3940
"@homarr/tsconfig": "workspace:^0.1.0",
41+
"@types/dockerode": "^3.3.29",
4042
"eslint": "^8.57.0",
4143
"prettier": "^3.2.5",
4244
"typescript": "^5.4.5"

packages/api/src/root.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { appRouter as innerAppRouter } from "./router/app";
22
import { boardRouter } from "./router/board";
3+
import { dockerRouter } from "./router/docker/docker-router";
34
import { groupRouter } from "./router/group";
45
import { homeRouter } from "./router/home";
56
import { iconsRouter } from "./router/icons";
@@ -24,6 +25,7 @@ export const appRouter = createTRPCRouter({
2425
log: logRouter,
2526
icon: iconsRouter,
2627
home: homeRouter,
28+
docker: dockerRouter,
2729
serverSettings: serverSettingsRouter,
2830
});
2931

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import type Docker from "dockerode";
2+
3+
import { db, like, or } from "@homarr/db";
4+
import { icons } from "@homarr/db/schema/sqlite";
5+
import type { DockerContainerState } from "@homarr/definitions";
6+
import { createCacheChannel } from "@homarr/redis";
7+
8+
import { createTRPCRouter, publicProcedure } from "../../trpc";
9+
import { DockerSingleton } from "./docker-singleton";
10+
11+
const dockerCache = createCacheChannel<{
12+
containers: (Docker.ContainerInfo & { instance: string; iconUrl: string | null })[];
13+
}>("docker-containers", 5 * 60 * 1000);
14+
15+
export const dockerRouter = createTRPCRouter({
16+
getContainers: publicProcedure.query(async () => {
17+
const { timestamp, data } = await dockerCache.consumeAsync(async () => {
18+
const dockerInstances = DockerSingleton.getInstance();
19+
const containers = await Promise.all(
20+
// Return all the containers of all the instances into only one item
21+
dockerInstances.map(({ instance, host: key }) =>
22+
instance.listContainers({ all: true }).then((containers) =>
23+
containers.map((container) => ({
24+
...container,
25+
instance: key,
26+
})),
27+
),
28+
),
29+
).then((containers) => containers.flat());
30+
31+
const extractImage = (container: Docker.ContainerInfo) =>
32+
container.Image.split("/").at(-1)?.split(":").at(0) ?? "";
33+
const likeQueries = containers.map((container) => like(icons.name, `%${extractImage(container)}%`));
34+
const dbIcons =
35+
likeQueries.length >= 1
36+
? await db.query.icons.findMany({
37+
where: or(...likeQueries),
38+
})
39+
: [];
40+
41+
return {
42+
containers: containers.map((container) => ({
43+
...container,
44+
iconUrl:
45+
dbIcons.find((icon) => {
46+
const extractedImage = extractImage(container);
47+
if (!extractedImage) return false;
48+
return icon.name.toLowerCase().includes(extractedImage.toLowerCase());
49+
})?.url ?? null,
50+
})),
51+
};
52+
});
53+
54+
return {
55+
containers: sanitizeContainers(data.containers),
56+
timestamp,
57+
};
58+
}),
59+
});
60+
61+
interface DockerContainer {
62+
name: string;
63+
id: string;
64+
state: DockerContainerState;
65+
image: string;
66+
ports: Docker.Port[];
67+
iconUrl: string | null;
68+
}
69+
70+
function sanitizeContainers(
71+
containers: (Docker.ContainerInfo & { instance: string; iconUrl: string | null })[],
72+
): DockerContainer[] {
73+
return containers.map((container) => {
74+
return {
75+
name: container.Names[0]?.split("/")[1] || "Unknown",
76+
id: container.Id,
77+
instance: container.instance,
78+
state: container.State as DockerContainerState,
79+
image: container.Image,
80+
ports: container.Ports,
81+
iconUrl: container.iconUrl,
82+
};
83+
});
84+
}

0 commit comments

Comments
 (0)