refactor: migration

This commit is contained in:
Mauricio Siu
2024-10-24 21:25:45 -06:00
parent 4309939fd5
commit 823dbe608f
58 changed files with 7647 additions and 29 deletions

View File

@@ -0,0 +1,141 @@
import type http from "node:http";
import { findServerById, validateWebSocketRequest } from "@dokploy/server";
import { spawn } from "node-pty";
import { Client } from "ssh2";
import { WebSocketServer } from "ws";
import { getShell } from "./utils";
export const setupDockerContainerLogsWebSocketServer = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
) => {
const wssTerm = new WebSocketServer({
noServer: true,
path: "/docker-container-logs",
});
server.on("upgrade", (req, socket, head) => {
const { pathname } = new URL(req.url || "", `http://${req.headers.host}`);
if (pathname === "/_next/webpack-hmr") {
return;
}
if (pathname === "/docker-container-logs") {
wssTerm.handleUpgrade(req, socket, head, function done(ws) {
wssTerm.emit("connection", ws, req);
});
}
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
wssTerm.on("connection", async (ws, req) => {
const url = new URL(req.url || "", `http://${req.headers.host}`);
const containerId = url.searchParams.get("containerId");
const tail = url.searchParams.get("tail");
const serverId = url.searchParams.get("serverId");
const { user, session } = await validateWebSocketRequest(req);
if (!containerId) {
ws.close(4000, "containerId no provided");
return;
}
if (!user || !session) {
ws.close();
return;
}
try {
if (serverId) {
const server = await findServerById(serverId);
if (!server.sshKeyId) return;
const client = new Client();
client
.once("ready", () => {
const command = `
bash -c "docker container logs --tail ${tail} --follow ${containerId}"
`;
client.exec(command, (err, stream) => {
if (err) {
console.error("Execution error:", err);
ws.close();
client.end();
return;
}
stream
.on("close", () => {
console.log("Connection closed ✅ Container Logs");
client.end();
ws.close();
})
.on("data", (data: string) => {
ws.send(data.toString());
})
.stderr.on("data", (data) => {
ws.send(data.toString());
});
});
})
.on("error", (err) => {
console.error("SSH connection error:", err);
ws.send(`SSH error: ${err.message}`);
ws.close(); // Cierra el WebSocket si hay un error con SSH
client.end();
})
.connect({
host: server.ipAddress,
port: server.port,
username: server.username,
privateKey: server.sshKey?.privateKey,
});
ws.on("close", () => {
console.log("Connection closed ✅, From Container Logs WS");
client.end();
});
} else {
const shell = getShell();
const ptyProcess = spawn(
shell,
[
"-c",
`docker container logs --tail ${tail} --follow ${containerId}`,
],
{
name: "xterm-256color",
cwd: process.env.HOME,
env: process.env,
encoding: "utf8",
cols: 80,
rows: 30,
},
);
ptyProcess.onData((data) => {
ws.send(data);
});
ws.on("close", () => {
ptyProcess.kill();
});
ws.on("message", (message) => {
try {
let command: string | Buffer[] | Buffer | ArrayBuffer;
if (Buffer.isBuffer(message)) {
command = message.toString("utf8");
} else {
command = message;
}
ptyProcess.write(command.toString());
} catch (error) {
// @ts-ignore
const errorMessage = error?.message as unknown as string;
ws.send(errorMessage);
}
});
}
} catch (error) {
// @ts-ignore
const errorMessage = error?.message as unknown as string;
ws.send(errorMessage);
}
});
};

View File

@@ -0,0 +1,154 @@
import type http from "node:http";
import { findServerById, validateWebSocketRequest } from "@dokploy/server";
import { spawn } from "node-pty";
import { Client } from "ssh2";
import { WebSocketServer } from "ws";
import { getShell } from "./utils";
export const setupDockerContainerTerminalWebSocketServer = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
) => {
const wssTerm = new WebSocketServer({
noServer: true,
path: "/docker-container-terminal",
});
server.on("upgrade", (req, socket, head) => {
const { pathname } = new URL(req.url || "", `http://${req.headers.host}`);
if (pathname === "/_next/webpack-hmr") {
return;
}
if (pathname === "/docker-container-terminal") {
wssTerm.handleUpgrade(req, socket, head, function done(ws) {
wssTerm.emit("connection", ws, req);
});
}
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
wssTerm.on("connection", async (ws, req) => {
const url = new URL(req.url || "", `http://${req.headers.host}`);
const containerId = url.searchParams.get("containerId");
const activeWay = url.searchParams.get("activeWay");
const serverId = url.searchParams.get("serverId");
const { user, session } = await validateWebSocketRequest(req);
if (!containerId) {
ws.close(4000, "containerId no provided");
return;
}
if (!user || !session) {
ws.close();
return;
}
try {
if (serverId) {
const server = await findServerById(serverId);
if (!server.sshKeyId)
throw new Error("No SSH key available for this server");
const conn = new Client();
let stdout = "";
let stderr = "";
conn
.once("ready", () => {
conn.exec(
`docker exec -it ${containerId} ${activeWay}`,
{ pty: true },
(err, stream) => {
if (err) throw err;
stream
.on("close", (code: number, signal: string) => {
console.log(
`Stream :: close :: code: ${code}, signal: ${signal}`,
);
ws.send(`\nContainer closed with code: ${code}\n`);
conn.end();
})
.on("data", (data: string) => {
stdout += data.toString();
ws.send(data.toString());
})
.stderr.on("data", (data) => {
stderr += data.toString();
ws.send(data.toString());
console.error("Error: ", data.toString());
});
ws.on("message", (message) => {
try {
let command: string | Buffer[] | Buffer | ArrayBuffer;
if (Buffer.isBuffer(message)) {
command = message.toString("utf8");
} else {
command = message;
}
stream.write(command.toString());
} catch (error) {
// @ts-ignore
const errorMessage = error?.message as unknown as string;
ws.send(errorMessage);
}
});
ws.on("close", () => {
stream.end();
});
},
);
})
.connect({
host: server.ipAddress,
port: server.port,
username: server.username,
privateKey: server.sshKey?.privateKey,
timeout: 99999,
});
} else {
const shell = getShell();
const ptyProcess = spawn(
shell,
["-c", `docker exec -it ${containerId} ${activeWay}`],
{
name: "xterm-256color",
cwd: process.env.HOME,
env: process.env,
encoding: "utf8",
cols: 80,
rows: 30,
},
);
ptyProcess.onData((data) => {
ws.send(data);
});
ws.on("close", () => {
ptyProcess.kill();
});
ws.on("message", (message) => {
try {
let command: string | Buffer[] | Buffer | ArrayBuffer;
if (Buffer.isBuffer(message)) {
command = message.toString("utf8");
} else {
command = message;
}
ptyProcess.write(command.toString());
} catch (error) {
// @ts-ignore
const errorMessage = error?.message as unknown as string;
ws.send(errorMessage);
}
});
}
} catch (error) {
// @ts-ignore
const errorMessage = error?.message as unknown as string;
ws.send(errorMessage);
}
});
};

View File

@@ -0,0 +1,96 @@
import type http from "node:http";
import {
docker,
getLastAdvancedStatsFile,
recordAdvancedStats,
validateWebSocketRequest,
} from "@dokploy/server";
import { WebSocketServer } from "ws";
export const setupDockerStatsMonitoringSocketServer = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
) => {
const wssTerm = new WebSocketServer({
noServer: true,
path: "/listen-docker-stats-monitoring",
});
server.on("upgrade", (req, socket, head) => {
const { pathname } = new URL(req.url || "", `http://${req.headers.host}`);
if (pathname === "/_next/webpack-hmr") {
return;
}
if (pathname === "/listen-docker-stats-monitoring") {
wssTerm.handleUpgrade(req, socket, head, function done(ws) {
wssTerm.emit("connection", ws, req);
});
}
});
wssTerm.on("connection", async (ws, req) => {
const url = new URL(req.url || "", `http://${req.headers.host}`);
const appName = url.searchParams.get("appName");
const appType = (url.searchParams.get("appType") || "application") as
| "application"
| "stack"
| "docker-compose";
const { user, session } = await validateWebSocketRequest(req);
if (!appName) {
ws.close(4000, "appName no provided");
return;
}
if (!user || !session) {
ws.close();
return;
}
const intervalId = setInterval(async () => {
try {
const filter = {
status: ["running"],
...(appType === "application" && {
label: [`com.docker.swarm.service.name=${appName}`],
}),
...(appType === "stack" && {
label: [`com.docker.swarm.task.name=${appName}`],
}),
...(appType === "docker-compose" && {
name: [appName],
}),
};
const containers = await docker.listContainers({
filters: JSON.stringify(filter),
});
const container = containers[0];
if (!container || container?.State !== "running") {
ws.close(4000, "Container not running");
return;
}
const stats = await docker.getContainer(container.Id).stats({
stream: false,
});
await recordAdvancedStats(stats, appName);
const data = await getLastAdvancedStatsFile(appName);
ws.send(
JSON.stringify({
data,
}),
);
} catch (error) {
// @ts-ignore
ws.close(4000, `Error: ${error.message}`);
}
}, 1300);
ws.on("close", () => {
clearInterval(intervalId);
});
});
};

View File

@@ -0,0 +1,112 @@
import { spawn } from "node:child_process";
import type http from "node:http";
import { findServerById, validateWebSocketRequest } from "@dokploy/server";
import { Client } from "ssh2";
import { WebSocketServer } from "ws";
export const setupDeploymentLogsWebSocketServer = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
) => {
const wssTerm = new WebSocketServer({
noServer: true,
path: "/listen-deployment",
});
server.on("upgrade", (req, socket, head) => {
const { pathname } = new URL(req.url || "", `http://${req.headers.host}`);
if (pathname === "/_next/webpack-hmr") {
return;
}
if (pathname === "/listen-deployment") {
wssTerm.handleUpgrade(req, socket, head, function done(ws) {
wssTerm.emit("connection", ws, req);
});
}
});
wssTerm.on("connection", async (ws, req) => {
const url = new URL(req.url || "", `http://${req.headers.host}`);
const logPath = url.searchParams.get("logPath");
const serverId = url.searchParams.get("serverId");
const { user, session } = await validateWebSocketRequest(req);
if (!logPath) {
console.log("logPath no provided");
ws.close(4000, "logPath no provided");
return;
}
if (!user || !session) {
ws.close();
return;
}
try {
if (serverId) {
const server = await findServerById(serverId);
if (!server.sshKeyId) return;
const client = new Client();
client
.on("ready", () => {
const command = `
tail -n +1 -f ${logPath};
`;
client.exec(command, (err, stream) => {
if (err) {
console.error("Execution error:", err);
ws.close();
return;
}
stream
.on("close", () => {
console.log("Connection closed ✅");
client.end();
ws.close();
})
.on("data", (data: string) => {
ws.send(data.toString());
})
.stderr.on("data", (data) => {
ws.send(data.toString());
});
});
})
.on("error", (err) => {
console.error("SSH connection error:", err);
ws.send(`SSH error: ${err.message}`);
ws.close(); // Cierra el WebSocket si hay un error con SSH
})
.connect({
host: server.ipAddress,
port: server.port,
username: server.username,
privateKey: server.sshKey?.privateKey,
});
ws.on("close", () => {
console.log("Connection closed ✅, From WS");
client.end();
});
} else {
const tail = spawn("tail", ["-n", "+1", "-f", logPath]);
tail.stdout.on("data", (data) => {
ws.send(data.toString());
});
tail.stderr.on("data", (data) => {
ws.send(new Error(`tail error: ${data.toString()}`).message);
});
tail.on("close", () => {
ws.close();
});
}
} catch (error) {
// @ts-ignore
// const errorMessage = error?.message as unknown as string;
// ws.send(errorMessage);
}
});
};

View File

@@ -0,0 +1,140 @@
import type http from "node:http";
import { findServerById, validateWebSocketRequest } from "@dokploy/server";
import { publicIpv4, publicIpv6 } from "public-ip";
import { Client } from "ssh2";
import { WebSocketServer } from "ws";
export const getPublicIpWithFallback = async () => {
// @ts-ignore
let ip = null;
try {
ip = await publicIpv4();
} catch (error) {
console.log(
"Error to obtain public IPv4 address, falling back to IPv6",
// @ts-ignore
error.message,
);
try {
ip = await publicIpv6();
} catch (error) {
// @ts-ignore
console.error("Error to obtain public IPv6 address", error.message);
ip = null;
}
}
return ip;
};
export const setupTerminalWebSocketServer = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
) => {
const wssTerm = new WebSocketServer({
noServer: true,
path: "/terminal",
});
server.on("upgrade", (req, socket, head) => {
const { pathname } = new URL(req.url || "", `http://${req.headers.host}`);
if (pathname === "/_next/webpack-hmr") {
return;
}
if (pathname === "/terminal") {
wssTerm.handleUpgrade(req, socket, head, function done(ws) {
wssTerm.emit("connection", ws, req);
});
}
});
wssTerm.on("connection", async (ws, req) => {
const url = new URL(req.url || "", `http://${req.headers.host}`);
const serverId = url.searchParams.get("serverId");
const { user, session } = await validateWebSocketRequest(req);
if (!user || !session || !serverId) {
ws.close();
return;
}
const server = await findServerById(serverId);
if (!server) {
ws.close();
return;
}
if (!server.sshKeyId)
throw new Error("No SSH key available for this server");
const conn = new Client();
let stdout = "";
let stderr = "";
conn
.once("ready", () => {
conn.shell(
{
term: "terminal",
cols: 80,
rows: 30,
height: 30,
width: 80,
},
(err, stream) => {
if (err) throw err;
stream
.on("close", (code: number, signal: string) => {
ws.send(`\nContainer closed with code: ${code}\n`);
conn.end();
})
.on("data", (data: string) => {
stdout += data.toString();
ws.send(data.toString());
})
.stderr.on("data", (data) => {
stderr += data.toString();
ws.send(data.toString());
console.error("Error: ", data.toString());
});
ws.on("message", (message) => {
try {
let command: string | Buffer[] | Buffer | ArrayBuffer;
if (Buffer.isBuffer(message)) {
command = message.toString("utf8");
} else {
command = message;
}
stream.write(command.toString());
} catch (error) {
// @ts-ignore
const errorMessage = error?.message as unknown as string;
ws.send(errorMessage);
}
});
ws.on("close", () => {
console.log("Connection closed ✅");
stream.end();
});
},
);
})
.on("error", (err) => {
if (err.level === "client-authentication") {
ws.send(
`Authentication failed: Invalid SSH private key. ❌ Error: ${err.message} ${err.level}`,
);
} else {
ws.send(`SSH connection error: ${err.message}`);
}
conn.end();
})
.connect({
host: server.ipAddress,
port: server.port,
username: server.username,
privateKey: server.sshKey?.privateKey,
timeout: 99999,
});
});
};

View File

@@ -0,0 +1,12 @@
import os from "node:os";
export const getShell = () => {
switch (os.platform()) {
case "win32":
return "powershell.exe";
case "darwin":
return "zsh";
default:
return "bash";
}
};