Deployment port configuration and log fix

This commit is contained in:
2026-01-03 22:16:32 +01:00
parent 8f2ebaeab7
commit 21f9f1bb56
8 changed files with 158 additions and 38 deletions
+7 -3
View File
@@ -2,11 +2,15 @@ import { NextRequest, NextResponse } from "next/server";
import testAuth from "../auth";
import { StatusCodes } from "http-status-codes";
import { deployApp } from "@/core/deployment";
import { Application } from "@/lib/types";
import { Application, Port } from "@/lib/types";
export async function POST(req: NextRequest): Promise<NextResponse> {
const auth = await testAuth(req);
const { name, app }: { name: string; app: Application } = await req.json();
const {
name,
app,
ports,
}: { name: string; app: Application; ports: Port[] } = await req.json();
if (auth) {
return NextResponse.json(
@@ -22,7 +26,7 @@ export async function POST(req: NextRequest): Promise<NextResponse> {
);
}
const deployId = await deployApp(name, app);
const deployId = await deployApp(name, app, ports);
return NextResponse.json({
message: "ok",
+1 -1
View File
@@ -20,7 +20,7 @@ export default function LogsPage() {
const { value: logs, setValue: setLogs } = useAsyncInterval(
[],
async () => (isPaused ? ([] as Log[]) : getAllContainerLogs()),
100
1000
);
const filteredLogs = logs.filter((log) =>
+83 -3
View File
@@ -17,8 +17,9 @@ import { getLiveNodes } from "@/lib/dockship/node";
import { Combobox } from "../ui/combobox";
import { deployApp } from "@/lib/dockship/deploy";
import { useAsync } from "@/hooks/use-async";
import { Application } from "@/lib/types";
import { Application, Port } from "@/lib/types";
import { getApps } from "@/lib/dockship/application";
import { Plus } from "lucide-react";
export default function DeployAppDialog({
defaultApp,
@@ -33,9 +34,26 @@ export default function DeployAppDialog({
const [app, setApp] = useState(defaultApp || "");
const [node, setNode] = useState("");
const [ports, setPorts] = useState<Port[]>([]);
const [newPort, setNewPort] = useState<Port>({
containerPort: "",
hostPort: "",
protocol: "tcp",
});
const addPort = () => {
if (!newPort.containerPort || !newPort.hostPort) return;
setPorts([...ports, newPort]);
setNewPort({ containerPort: "", hostPort: "", protocol: "tcp" });
};
const removePort = (index: number) => {
setPorts(ports.filter((_, i) => i !== index));
};
const deploy = async () => {
console.log(name, app, node);
await deployApp(name, app, node);
console.log("Deploying:", { name, app, node, ports });
await deployApp(name, app, node, ports);
};
return (
@@ -48,6 +66,7 @@ export default function DeployAppDialog({
</DialogHeader>
<div className="grid gap-4">
{/* Name */}
<div className="grid gap-3">
<Label htmlFor="name">
Deployment name <span className="text-destructive">*</span>
@@ -60,6 +79,7 @@ export default function DeployAppDialog({
/>
</div>
{/* Application */}
<div className="grid gap-3">
<Label htmlFor="repo">
Application <span className="text-destructive">*</span>
@@ -76,6 +96,7 @@ export default function DeployAppDialog({
/>
</div>
{/* Node */}
<div className="grid gap-3">
<Label htmlFor="node">
Node <span className="text-destructive">*</span>
@@ -90,6 +111,65 @@ export default function DeployAppDialog({
listPlaceholder="No nodes found :("
/>
</div>
{/* Ports */}
<div className="grid gap-3">
<Label>Ports</Label>
<div className="flex gap-2 items-end">
<Input
placeholder="Container Port"
value={newPort.containerPort}
onChange={(e) =>
setNewPort({ ...newPort, containerPort: e.target.value })
}
/>
<Input
placeholder="Host Port"
value={newPort.hostPort}
onChange={(e) =>
setNewPort({ ...newPort, hostPort: e.target.value })
}
/>
<Combobox
value={newPort.protocol}
setValue={(v) =>
setNewPort({
...newPort,
protocol: v as "tcp" | "udp",
})
}
data={[
{ label: "TCP", value: "tcp" },
{ label: "UDP", value: "udp" },
]}
placeholder="Select protocol..."
listPlaceholder="No protocols found :("
/>
<Button onClick={addPort} variant="ghost">
<Plus />
</Button>
</div>
{ports.length > 0 && (
<ul className="mt-2 space-y-1">
{ports.map((p, i) => (
<li key={i} className="flex justify-between items-center">
<span>
{p.containerPort} → {p.hostPort} (
{p.protocol.toUpperCase()})
</span>
<Button
variant="destructive"
size="sm"
onClick={() => removePort(i)}
>
Remove
</Button>
</li>
))}
</ul>
)}
</div>
</div>
<DialogFooter>
+2 -2
View File
@@ -43,13 +43,13 @@ export function Combobox({
variant="outline"
role="combobox"
aria-expanded={open}
className="w-50 justify-between"
className="justify-between"
>
{value ? data.find((itm) => itm.value === value)?.label : placeholder}
<ChevronsUpDown className="opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-50 p-0">
<PopoverContent className="w-[--radix-popover-trigger-width] p-0">
<Command>
<CommandInput placeholder="Search framework..." className="h-9" />
<CommandList>
+18 -5
View File
@@ -1,7 +1,7 @@
"use server";
import Docker from "dockerode";
import { Application, Deployment } from "@/lib/types";
import { Application, Deployment, Port } from "@/lib/types";
import { CPUusage } from "@/lib/server/calc";
import path from "path";
import fs from "fs";
@@ -20,6 +20,20 @@ function sanitizeString(str: string): string {
);
}
function formatPorts(ports: Port[]) {
const dockerPorts: Record<string, { HostPort: string }[]> = {};
ports.forEach(({ containerPort, hostPort, protocol }) => {
const key = `${containerPort}/${protocol}`;
if (!dockerPorts[key]) {
dockerPorts[key] = [];
}
dockerPorts[key].push({ HostPort: hostPort });
});
return dockerPorts;
}
export async function getDeployments(
apps: Application[]
): Promise<Deployment[]> {
@@ -96,7 +110,8 @@ export async function getDeployments(
export async function deployApp(
name: string,
app: Application
app: Application,
ports: Port[]
): Promise<string | undefined> {
const deployId = randomUUID();
const deployPath = path.join("data", "deploys", deployId);
@@ -134,9 +149,7 @@ export async function deployApp(
Tty: true,
HostConfig: {
RestartPolicy: { Name: "unless-stopped" },
PortBindings: {
"3000/tcp": [{ HostPort: "3800" }],
},
PortBindings: formatPorts(ports),
},
Env: Object.entries(app.env).map(
([key, { value }]) => `${key}="${value.replaceAll('"', '\\"')}"`
+37 -21
View File
@@ -67,36 +67,52 @@ function demuxLogs(buffer: Buffer): string {
return output;
}
async function getContainerLogs(
containerId: string,
name: string
): Promise<Log[]> {
const container = docker.getContainer(containerId);
const raw = await container.logs({
stdout: true,
stderr: true,
timestamps: true,
});
// Inspect the container to check the logging driver
const info = await container.inspect();
const driver = info.HostConfig.LogConfig?.Type;
const text = demuxLogs(raw);
if (driver !== "json-file" && driver !== "journald") {
// Skip containers with unsupported logging drivers
return [];
}
return text
.split("\n")
.filter(Boolean)
.map((line) => {
const firstSpace = line.indexOf(" ");
const timestamp = line.slice(0, firstSpace);
const message = line.slice(firstSpace + 1);
return {
timestamp,
level: inferLevel(message),
source: name,
message,
} satisfies Log;
try {
const raw = await container.logs({
stdout: true,
stderr: true,
timestamps: true,
});
const text = demuxLogs(raw);
return text
.split("\n")
.filter(Boolean)
.map((line) => {
const firstSpace = line.indexOf(" ");
const timestamp = line.slice(0, firstSpace);
const message = line.slice(firstSpace + 1);
return {
timestamp,
level: inferLevel(message),
source: name,
message,
} satisfies Log;
});
} catch (err: any) {
if (err.statusCode === 501) {
// Logging driver does not support reading
return [];
}
throw err; // rethrow any other error
}
}
export async function getAllContainerLogs(): Promise<Log[]> {
+4 -3
View File
@@ -1,6 +1,6 @@
"use server";
import { Deployment } from "@/lib/types";
import { Deployment, Port } from "@/lib/types";
import { getNodes } from "./node";
import axios from "axios";
import { editApp, getApp, getApps } from "./application";
@@ -26,7 +26,8 @@ export async function getDeployments(): Promise<Deployment[]> {
export async function deployApp(
name: string,
appId: string,
nodeId: string
nodeId: string,
ports: Port[]
): Promise<string | undefined> {
const nodes = await getNodes();
@@ -40,7 +41,7 @@ export async function deployApp(
const deployId = await (
await axios.post(
`http://${node.ip}:3000/api/deploy`,
{ name, app },
{ name, app, ports },
{
headers: { Authorization: `ApiKey ${node.key}` },
}
+6
View File
@@ -88,3 +88,9 @@ export interface Env {
name: string;
variables: Record<string, EnvVariable>;
}
export interface Port {
containerPort: string;
hostPort: string;
protocol: "tcp" | "udp";
}