Compare commits
14
Commits
5c56208c8b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b96c4f79b | ||
|
|
aea8eff656 | ||
|
|
048a869c30 | ||
|
|
25b2ad1b3f | ||
|
|
57d63f5bf4 | ||
|
|
8354d94cbc | ||
|
|
268734275a | ||
|
|
984992541c | ||
|
|
6d22275a1f | ||
|
|
4855bb882c | ||
|
|
5fd48d1971 | ||
|
|
7dde7378b8 | ||
|
|
3827f803c5 | ||
|
|
e93524c403 |
+6
-1
@@ -1,7 +1,12 @@
|
||||
node_modules/
|
||||
dist/
|
||||
build/
|
||||
.env
|
||||
|
||||
*.log
|
||||
|
||||
.env
|
||||
|
||||
*-state.json
|
||||
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,70 @@
|
||||
# Server Manager
|
||||
|
||||
Dynamic Dedicated Server Management System.
|
||||
|
||||
## Components
|
||||
|
||||
* Manager
|
||||
* Wrapper
|
||||
* Shared
|
||||
* Dashboard
|
||||
|
||||
## Build
|
||||
|
||||
Build all workspaces:
|
||||
|
||||
```bash
|
||||
npm run build --workspaces
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Manager
|
||||
|
||||
```bash
|
||||
npm start --workspace manager
|
||||
```
|
||||
|
||||
### Dashboard
|
||||
|
||||
```bash
|
||||
npm run dev --workspace dashboard
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Manager
|
||||
|
||||
Responsible for:
|
||||
|
||||
* Server lifecycle management
|
||||
* Dynamic scaling
|
||||
* Wrapper communication
|
||||
* Server registry
|
||||
|
||||
### Wrapper
|
||||
|
||||
Responsible for:
|
||||
|
||||
* Process management
|
||||
* Dedicated server control
|
||||
* Server monitoring
|
||||
* Status reporting
|
||||
|
||||
### Shared
|
||||
|
||||
Contains:
|
||||
|
||||
* Common types
|
||||
* Shared interfaces
|
||||
* Communication contracts
|
||||
|
||||
## Project Structure
|
||||
|
||||
```text
|
||||
server-manager/
|
||||
├── manager/
|
||||
├── wrapper/
|
||||
├── shared/
|
||||
└── dashboard/
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Server Manager</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "server-manager-dashboard",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.1",
|
||||
"vite": "^5.4.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
export interface DashboardData {
|
||||
managerStatus: string;
|
||||
rabbitMqStatus: string;
|
||||
wrapperCount: number;
|
||||
onlineWrapperCount: number;
|
||||
serverCount: number;
|
||||
runningServerCount: number;
|
||||
totalPlayers: number;
|
||||
totalCapacity: number;
|
||||
utilizationPercent: number;
|
||||
desiredServers: number;
|
||||
activeServers: number;
|
||||
}
|
||||
|
||||
export interface Wrapper {
|
||||
id: string; hostname: string; online: boolean; cpu: number; ram: number;
|
||||
ramFree: number; lastHeartbeat: number; serverCount: number;
|
||||
}
|
||||
|
||||
export interface Server {
|
||||
id: string; name: string; status: string; wrapperId: string; port: number;
|
||||
pid?: number; queryPort: number; players: number; maxPlayers: number; created: number;
|
||||
startedAt?: number; emptySince?: number; alive?: boolean; started?: number;
|
||||
}
|
||||
|
||||
async function request<T>(path: string): Promise<T> {
|
||||
const response = await fetch(`/api${path}`);
|
||||
if (!response.ok) throw new Error(`API request failed (${response.status})`);
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
dashboard: () => request<DashboardData>("/dashboard"),
|
||||
wrappers: () => request<Wrapper[]>("/wrappers"),
|
||||
wrapper: (id: string) => request<Wrapper & { servers: Server[] }>(`/wrappers/${encodeURIComponent(id)}`),
|
||||
servers: () => request<Server[]>("/servers"),
|
||||
server: (id: string) => request<Server>(`/servers/${encodeURIComponent(id)}`)
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { NavLink, Outlet } from "react-router-dom";
|
||||
|
||||
export function Layout() {
|
||||
return <main className="shell">
|
||||
<header><NavLink to="/" className="brand">Server Manager</NavLink><nav>
|
||||
<NavLink to="/">Dashboard</NavLink><NavLink to="/wrappers">Wrapper</NavLink><NavLink to="/servers">Server</NavLink>
|
||||
</nav></header>
|
||||
<Outlet />
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function PageState({ error }: { error?: Error }) {
|
||||
return <p className={error ? "error" : "loading"}>{error ? error.message : "Daten werden geladen …"}</p>;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export function StatusBadge({ status }: { status: string | boolean }) {
|
||||
const label = typeof status === "boolean" ? (status ? "ONLINE" : "OFFLINE") : status;
|
||||
const tone = ["RUNNING", "ONLINE", "CONNECTED"].includes(label) ? "good"
|
||||
: ["STARTING", "STOPPING"].includes(label) ? "pending" : "bad";
|
||||
return <span className={`status status--${tone}`}>{label}</span>;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { createBrowserRouter, RouterProvider } from "react-router-dom";
|
||||
import { Layout } from "./components/Layout";
|
||||
import { Dashboard } from "./pages/Dashboard";
|
||||
import { ServerDetail } from "./pages/ServerDetail";
|
||||
import { Servers } from "./pages/Servers";
|
||||
import { WrapperDetail } from "./pages/WrapperDetail";
|
||||
import { Wrappers } from "./pages/Wrappers";
|
||||
import "./styles.css";
|
||||
|
||||
const router = createBrowserRouter([{ path: "/", element: <Layout />, children: [
|
||||
{ index: true, element: <Dashboard /> }, { path: "wrappers", element: <Wrappers /> },
|
||||
{ path: "wrappers/:id", element: <WrapperDetail /> }, { path: "servers", element: <Servers /> },
|
||||
{ path: "servers/:id", element: <ServerDetail /> }
|
||||
] }]);
|
||||
createRoot(document.getElementById("root")!).render(<StrictMode><RouterProvider router={router} /></StrictMode>);
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, DashboardData } from "../api/client";
|
||||
import { PageState } from "../components/PageState";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
|
||||
export function Dashboard() {
|
||||
const [data, setData] = useState<DashboardData>(); const [error, setError] = useState<Error>();
|
||||
useEffect(() => { api.dashboard().then(setData).catch(setError); }, []);
|
||||
if (!data) return <PageState error={error} />;
|
||||
return <><section className="title"><div><h1>Dashboard</h1><p>Aktueller Zustand des Managers</p></div><button onClick={() => location.reload()}>Aktualisieren</button></section>
|
||||
<section className="cards"><article><small>Manager</small><StatusBadge status={data.managerStatus} /></article><article><small>RabbitMQ</small><StatusBadge status={data.rabbitMqStatus} /></article><article><small>Wrapper online</small><strong>{data.onlineWrapperCount} / {data.wrapperCount}</strong></article><article><small>Server laufend</small><strong>{data.runningServerCount} / {data.serverCount}</strong></article><article><small>Spieler / Kapazität</small><strong>{data.totalPlayers} / {data.totalCapacity}</strong></article><article><small>Auslastung</small><strong>{data.utilizationPercent}%</strong></article><article><small>Soll-Server</small><strong>{data.desiredServers}</strong></article><article><small>Aktive Server</small><strong>{data.activeServers}</strong></article></section>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { api, Server } from "../api/client";
|
||||
import { PageState } from "../components/PageState";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
|
||||
const date = (value?: number) => value ? new Date(value).toLocaleString("de-DE") : "–";
|
||||
|
||||
export function ServerDetail() {
|
||||
const { id = "" } = useParams();
|
||||
const [item, setItem] = useState<Server>();
|
||||
const [error, setError] = useState<Error>();
|
||||
|
||||
useEffect(() => { api.server(id).then(setItem).catch(setError); }, [id]);
|
||||
|
||||
if (!item) return <PageState error={error} />;
|
||||
|
||||
return <>
|
||||
<section className="title"><div><p><Link to="/servers">← Server</Link></p><h1>{item.name}</h1><StatusBadge status={item.status} /></div></section>
|
||||
<section className="details">
|
||||
<div><small>ID</small><span>{item.id}</span></div>
|
||||
<div><small>Wrapper</small><span>{item.wrapperId}</span></div>
|
||||
<div><small>PID</small><span>{item.pid ?? "–"}</span></div>
|
||||
<div><small>Spieler / Kapazität</small><span>{item.players} / {item.maxPlayers}</span></div>
|
||||
<div><small>Port / Query Port</small><span>{item.port} / {item.queryPort}</span></div>
|
||||
<div><small>Erstellt</small><span>{date(item.created)}</span></div>
|
||||
<div><small>Gestartet</small><span>{date(item.startedAt)}</span></div>
|
||||
<div><small>Leer seit</small><span>{date(item.emptySince)}</span></div>
|
||||
</section>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, Server } from "../api/client";
|
||||
import { PageState } from "../components/PageState";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
|
||||
export function Servers() { const [items, setItems] = useState<Server[]>(); const [error, setError] = useState<Error>(); useEffect(() => { api.servers().then(setItems).catch(setError); }, []); if (!items) return <PageState error={error} />;
|
||||
return <><section className="title"><div><h1>Server</h1><p>{items.length} registriert</p></div></section><section className="table-wrap"><table><thead><tr><th>ID</th><th>Name</th><th>Status</th><th>Spieler</th><th>Kapazität</th><th>Port</th><th>Query Port</th><th>Wrapper</th></tr></thead><tbody>{items.map(item => <tr key={item.id}><td><Link to={`/servers/${item.id}`}>{item.id}</Link></td><td>{item.name}</td><td><StatusBadge status={item.status} /></td><td>{item.players}</td><td>{item.maxPlayers}</td><td>{item.port}</td><td>{item.queryPort}</td><td>{item.wrapperId}</td></tr>)}</tbody></table></section></>;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { api, Server, Wrapper } from "../api/client";
|
||||
import { PageState } from "../components/PageState";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
|
||||
export function WrapperDetail() {
|
||||
const { id = "" } = useParams(); const [item, setItem] = useState<(Wrapper & { servers: Server[] })>(); const [error, setError] = useState<Error>();
|
||||
useEffect(() => { api.wrapper(id).then(setItem).catch(setError); }, [id]); if (!item) return <PageState error={error} />;
|
||||
return <><section className="title"><div><p><Link to="/wrappers">← Wrapper</Link></p><h1>{item.hostname}</h1><StatusBadge status={item.online} /></div></section><section className="details"><div><small>ID</small><span>{item.id}</span></div><div><small>CPU</small><span>{item.cpu}%</span></div><div><small>RAM frei / gesamt</small><span>{item.ramFree} / {item.ram}</span></div><div><small>Letzter Heartbeat</small><span>{item.lastHeartbeat ? new Date(item.lastHeartbeat).toLocaleString("de-DE") : "–"}</span></div></section><h2>Zugeordnete Server</h2><section className="table-wrap"><table><thead><tr><th>Name</th><th>Port</th><th>Spieler</th><th>Status</th></tr></thead><tbody>{item.servers.map(server => <tr key={server.id}><td><Link to={`/servers/${server.id}`}>{server.name}</Link></td><td>{server.port}</td><td>{server.players} / {server.maxPlayers}</td><td><StatusBadge status={server.alive ? "RUNNING" : "OFFLINE"} /></td></tr>)}</tbody></table></section></>;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, Wrapper } from "../api/client";
|
||||
import { PageState } from "../components/PageState";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
|
||||
export function Wrappers() { const [items, setItems] = useState<Wrapper[]>(); const [error, setError] = useState<Error>(); useEffect(() => { api.wrappers().then(setItems).catch(setError); }, []); if (!items) return <PageState error={error} />;
|
||||
return <><section className="title"><div><h1>Wrapper</h1><p>{items.length} registriert</p></div></section><section className="table-wrap"><table><thead><tr><th>ID</th><th>Hostname</th><th>Status</th><th>CPU</th><th>RAM frei / gesamt</th><th>Heartbeat</th><th>Server</th></tr></thead><tbody>{items.map(item => <tr key={item.id}><td><Link to={`/wrappers/${item.id}`}>{item.id}</Link></td><td>{item.hostname}</td><td><StatusBadge status={item.online} /></td><td>{item.cpu}%</td><td>{item.ramFree} / {item.ram}</td><td>{item.lastHeartbeat ? new Date(item.lastHeartbeat).toLocaleString("de-DE") : "–"}</td><td>{item.serverCount}</td></tr>)}</tbody></table></section></>;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
:root { color: #e7edf6; background: #0e1521; font-family: Inter, ui-sans-serif, system-ui, sans-serif; }
|
||||
* { box-sizing: border-box; } body { margin: 0; } a { color: #a9ccff; text-decoration: none; } a:hover { text-decoration: underline; }
|
||||
.shell { max-width: 1240px; padding: 0 28px 48px; margin: auto; } header { min-height: 70px; display:flex; align-items:center; justify-content:space-between; border-bottom: 1px solid #263446; margin-bottom: 44px; } .brand { color:#fff; font-weight:700; font-size:18px; } nav { display:flex; gap:24px; } nav a { color:#91a2b8; padding:24px 0; } nav a.active { color:#fff; border-bottom:2px solid #58a6ff; }
|
||||
.title { display:flex; justify-content:space-between; align-items:center; margin-bottom:28px; } h1 { margin:0; font-size:28px; } h2 { margin:38px 0 14px; font-size:18px; } p { color:#91a2b8; margin:7px 0 0; } button { border:1px solid #3c6d9d; color:#dbeafe; background:#17395b; border-radius:6px; padding:9px 13px; cursor:pointer; }
|
||||
.cards { display:grid; grid-template-columns:repeat(4, minmax(0, 1fr)); gap:14px; } .cards article, .details > div { background:#151f2e; border:1px solid #263446; border-radius:8px; padding:18px; min-height:94px; display:flex; flex-direction:column; justify-content:space-between; gap:10px; } small { color:#91a2b8; font-size:12px; } strong { font-size:23px; }
|
||||
.status { display:inline-flex; width:max-content; align-items:center; gap:6px; border-radius:999px; padding:4px 9px; font-size:11px; font-weight:700; letter-spacing:.03em; } .status--good { color:#8ee6bb; background:#123c2c; } .status--pending { color:#ffd98a; background:#493718; } .status--bad { color:#ffabb0; background:#48232b; }
|
||||
.table-wrap { overflow-x:auto; border:1px solid #263446; border-radius:8px; background:#151f2e; } table { width:100%; border-collapse:collapse; min-width:750px; } th,td { padding:14px 16px; text-align:left; border-bottom:1px solid #263446; font-size:14px; } th { color:#91a2b8; font-size:11px; text-transform:uppercase; letter-spacing:.05em; } tbody tr:last-child td { border-bottom:0; } .details { display:grid; grid-template-columns:repeat(3, 1fr); gap:14px; } .details span { word-break:break-word; } .loading,.error { padding:20px; background:#151f2e; border-radius:8px; } .error { color:#ffabb0; }
|
||||
@media (max-width: 760px) { .shell { padding:0 16px 32px; } header { margin-bottom:28px; } .cards,.details { grid-template-columns:repeat(2, 1fr); } nav { gap:12px; } } @media (max-width: 440px) { .cards,.details { grid-template-columns:1fr; } }
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"root":["./src/main.tsx","./src/api/client.ts","./src/components/layout.tsx","./src/components/pagestate.tsx","./src/components/statusbadge.tsx","./src/pages/dashboard.tsx","./src/pages/serverdetail.tsx","./src/pages/servers.tsx","./src/pages/wrapperdetail.tsx","./src/pages/wrappers.tsx"],"version":"5.9.3"}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
declare const _default: import("vite").UserConfig;
|
||||
export default _default;
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
"/api": "http://localhost:3000"
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
"/api": "http://localhost:3000"
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,10 +1,12 @@
|
||||
{
|
||||
"name": "manager",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"description": "Server Manager for dedicated game servers",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "ts-node src/index.ts"
|
||||
"dev": "ts-node src/index.ts",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import * as amqp from "amqplib";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
const logger = getLogger("CommandService");
|
||||
|
||||
export class CommandService {
|
||||
|
||||
@@ -27,8 +29,8 @@ export class CommandService {
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
"Command gesendet:",
|
||||
logger.debug(
|
||||
"Command sent",
|
||||
command
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export const RABBITMQ_URL = "amqp://manager:gigi1337@192.168.1.74";
|
||||
|
||||
// Lifecycle
|
||||
export const LIFECYCLE_CHECK_INTERVAL = 10000; // Alle 10 Sekunden prüfen
|
||||
|
||||
// Scale Down
|
||||
export const LIFECYCLE_EMPTY_TIMEOUT = 300000; // 5 Minuten leer
|
||||
export const LIFECYCLE_MIN_UPTIME = 600000; // 10 Minuten Mindestlaufzeit
|
||||
export const LIFECYCLE_SCALE_DOWN_THRESHOLD = 0.30; // Unter 30% Gesamtauslastung darf abgebaut werden
|
||||
|
||||
// Scale Up
|
||||
export const LIFECYCLE_STARTUP_GRACE_PERIOD = 60000; // 1 Minute Schutz nach Start
|
||||
export const LIFECYCLE_SCALE_COOLDOWN = 120000; // 2 Minuten zwischen Scale-Up Aktionen
|
||||
|
||||
// Crash Detection
|
||||
export const LIFECYCLE_CRASH_TIMEOUT = 120000; // 2 Minuten ohne Status -> Crash
|
||||
export const LIFECYCLE_CRASH_RETENTION = 300000; // 5 Minuten sichtbar nach Crash
|
||||
|
||||
// Default
|
||||
export const DEFAULT_DESIRED_SERVERS = 1;
|
||||
|
||||
// Ports
|
||||
export const GAME_PORT_START = 7777;
|
||||
export const QUERY_PORT_START = 27015;
|
||||
+24
-5
@@ -1,4 +1,4 @@
|
||||
import { Rabbit } from "./rabbit";
|
||||
import { Rabbit } from "./rabbit";
|
||||
import { WrapperManager } from "./wrapperManager";
|
||||
import { WrapperRegistry } from "./wrapperRegistry";
|
||||
import { ServerRegistry } from "./serverRegistry";
|
||||
@@ -6,6 +6,10 @@ import { ServerManager } from "./serverManager";
|
||||
import { PortManager } from "./portManager";
|
||||
import { ServerStatusManager } from "./serverStatusManager";
|
||||
import { ServerLifecycle } from "./serverLifecycle";
|
||||
import { getLogger } from "./logger";
|
||||
import { createWebServer } from "./web/server";
|
||||
|
||||
const logger = getLogger("Index");
|
||||
|
||||
|
||||
const wrapperRegistry =
|
||||
@@ -34,8 +38,16 @@ async function main(){
|
||||
|
||||
|
||||
await rabbit.connect();
|
||||
logger.info("RabbitMQ-Verbindung hergestellt");
|
||||
|
||||
await portManager.init();
|
||||
logger.info("Persistenz initialisiert");
|
||||
|
||||
await wrapperRegistry.init();
|
||||
logger.debug("WrapperRegistry initialisiert");
|
||||
|
||||
await serverRegistry.init();
|
||||
logger.debug("ServerRegistry initialisiert");
|
||||
|
||||
const wrapperManager =
|
||||
new WrapperManager(
|
||||
@@ -51,6 +63,7 @@ async function main(){
|
||||
|
||||
|
||||
await wrapperManager.start();
|
||||
logger.info("WrapperManager erfolgreich gestartet");
|
||||
|
||||
|
||||
const serverManager =
|
||||
@@ -77,6 +90,7 @@ async function main(){
|
||||
|
||||
|
||||
lifecycle.start();
|
||||
logger.debug("ServerLifecycle gestartet");
|
||||
|
||||
const statusManager =
|
||||
new ServerStatusManager(
|
||||
@@ -90,12 +104,17 @@ async function main(){
|
||||
|
||||
await statusManager.start();
|
||||
|
||||
const webServer = createWebServer({
|
||||
wrapperRegistry,
|
||||
serverRegistry,
|
||||
lifecycle,
|
||||
rabbitMqStatus: "connected",
|
||||
managerStatus: "running"
|
||||
}, 3000);
|
||||
|
||||
logger.info("Manager gestartet");
|
||||
|
||||
|
||||
console.log(
|
||||
"Manager gestartet"
|
||||
);
|
||||
void webServer;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
declare const process: {
|
||||
env: Record<string, string | undefined>;
|
||||
};
|
||||
|
||||
type LogLevel = "DEBUG" | "INFO" | "WARN" | "ERROR";
|
||||
|
||||
const LEVELS: Record<LogLevel, number> = {
|
||||
DEBUG: 0,
|
||||
INFO: 1,
|
||||
WARN: 2,
|
||||
ERROR: 3,
|
||||
};
|
||||
|
||||
const DEFAULT_LOG_LEVEL: LogLevel = "INFO";
|
||||
|
||||
const configuredLevel =
|
||||
(process.env.LOG_LEVEL ?? "").toUpperCase() as LogLevel;
|
||||
|
||||
const currentLogLevel: LogLevel =
|
||||
configuredLevel in LEVELS ? configuredLevel : DEFAULT_LOG_LEVEL;
|
||||
|
||||
const currentLogLevelValue = LEVELS[currentLogLevel];
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVELS[level] >= currentLogLevelValue;
|
||||
}
|
||||
|
||||
function formatMessage(
|
||||
level: LogLevel,
|
||||
component: string,
|
||||
message: unknown
|
||||
): string {
|
||||
return `${new Date().toISOString()} ${level} [${component}] ${message}`;
|
||||
}
|
||||
|
||||
class Logger {
|
||||
constructor(private component: string) {}
|
||||
|
||||
debug(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("DEBUG")) return;
|
||||
console.log(formatMessage("DEBUG", this.component, message), ...args);
|
||||
}
|
||||
|
||||
info(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("INFO")) return;
|
||||
console.log(formatMessage("INFO", this.component, message), ...args);
|
||||
}
|
||||
|
||||
warn(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("WARN")) return;
|
||||
console.warn(formatMessage("WARN", this.component, message), ...args);
|
||||
}
|
||||
|
||||
error(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("ERROR")) return;
|
||||
console.error(formatMessage("ERROR", this.component, message), ...args);
|
||||
}
|
||||
}
|
||||
|
||||
export function getLogger(component: string): Logger {
|
||||
return new Logger(component);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { promises as fs } from "fs";
|
||||
import { PersistenceStore } from "./persistenceStore";
|
||||
import { getLogger } from "../logger";
|
||||
|
||||
const logger = getLogger("JsonFileStore");
|
||||
|
||||
export class JsonFileStore<T> implements PersistenceStore<T> {
|
||||
constructor(
|
||||
private readonly filePath: string
|
||||
) {}
|
||||
|
||||
async load(): Promise<T | null> {
|
||||
try {
|
||||
const fileContents = await fs.readFile(this.filePath, "utf-8");
|
||||
return JSON.parse(fileContents) as T;
|
||||
}
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return null;
|
||||
}
|
||||
logger.error(
|
||||
`Fehler beim Laden der Persistenzdatei ${this.filePath}:`,
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async save(data: T): Promise<void> {
|
||||
try {
|
||||
const fileContents = JSON.stringify(data, null, 4);
|
||||
await fs.writeFile(this.filePath, fileContents, "utf-8");
|
||||
}
|
||||
catch (error) {
|
||||
logger.error(
|
||||
`Fehler beim Speichern der Persistenzdatei ${this.filePath}:`,
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface PersistenceStore<T> {
|
||||
load(): Promise<T | null>;
|
||||
save(data: T): Promise<void>;
|
||||
}
|
||||
+56
-50
@@ -1,118 +1,124 @@
|
||||
import { GAME_PORT_START, QUERY_PORT_START } from "./config";
|
||||
import { JsonFileStore } from "./persistence/jsonFileStore";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
const logger = getLogger("PortManager");
|
||||
|
||||
interface PortManagerState {
|
||||
usedPorts: number[];
|
||||
usedQueryPorts: number[];
|
||||
}
|
||||
|
||||
export class PortManager {
|
||||
|
||||
|
||||
|
||||
private usedPorts =
|
||||
new Set<number>();
|
||||
|
||||
|
||||
|
||||
private usedQueryPorts =
|
||||
new Set<number>();
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private gamePortStart =
|
||||
7777;
|
||||
|
||||
GAME_PORT_START;
|
||||
|
||||
private queryPortStart =
|
||||
27015;
|
||||
QUERY_PORT_START;
|
||||
|
||||
private readonly persistence =
|
||||
new JsonFileStore<PortManagerState>(
|
||||
"portManager-state.json"
|
||||
);
|
||||
|
||||
async init(){
|
||||
const state = await this.persistence.load();
|
||||
|
||||
if(!state)
|
||||
return;
|
||||
|
||||
this.usedPorts =
|
||||
new Set(state.usedPorts);
|
||||
|
||||
this.usedQueryPorts =
|
||||
new Set(state.usedQueryPorts);
|
||||
}
|
||||
|
||||
allocate(){
|
||||
|
||||
|
||||
|
||||
let port =
|
||||
this.gamePortStart;
|
||||
|
||||
|
||||
|
||||
while(
|
||||
this.usedPorts.has(port)
|
||||
){
|
||||
|
||||
port++;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
let queryPort =
|
||||
this.queryPortStart;
|
||||
|
||||
|
||||
|
||||
while(
|
||||
this.usedQueryPorts.has(queryPort)
|
||||
){
|
||||
|
||||
queryPort++;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
this.usedPorts.add(
|
||||
port
|
||||
);
|
||||
|
||||
|
||||
this.usedQueryPorts.add(
|
||||
queryPort
|
||||
);
|
||||
|
||||
logger.debug(`Port erfolgreich reserviert: ${port}`);
|
||||
logger.debug(`Query-Port erfolgreich reserviert: ${queryPort}`);
|
||||
|
||||
|
||||
this.saveState();
|
||||
|
||||
return {
|
||||
|
||||
|
||||
port,
|
||||
|
||||
|
||||
queryPort
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
release(
|
||||
port:number,
|
||||
queryPort:number
|
||||
){
|
||||
|
||||
|
||||
this.usedPorts.delete(
|
||||
const removedPort = this.usedPorts.delete(
|
||||
port
|
||||
);
|
||||
|
||||
|
||||
this.usedQueryPorts.delete(
|
||||
const removedQueryPort = this.usedQueryPorts.delete(
|
||||
queryPort
|
||||
);
|
||||
|
||||
if (!removedPort || !removedQueryPort) {
|
||||
logger.warn(
|
||||
`Unerwarteter Port-Zustand während der Freigabe: port=${port}, queryPort=${queryPort}`
|
||||
);
|
||||
} else {
|
||||
logger.debug(`Port wieder freigegeben: ${port}`);
|
||||
logger.debug(`Query-Port wieder freigegeben: ${queryPort}`);
|
||||
}
|
||||
|
||||
this.saveState();
|
||||
|
||||
}
|
||||
|
||||
private saveState(){
|
||||
const state: PortManagerState = {
|
||||
usedPorts: Array.from(this.usedPorts),
|
||||
usedQueryPorts: Array.from(this.usedQueryPorts)
|
||||
};
|
||||
|
||||
|
||||
|
||||
this.persistence
|
||||
.save(state)
|
||||
.catch(error => {
|
||||
logger.error(
|
||||
"Fehler beim Speichern des PortManager-Zustands:",
|
||||
error
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import * as amqp from "amqplib";
|
||||
import { RABBITMQ_URL } from "./config";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
const logger = getLogger("Rabbit");
|
||||
|
||||
export class Rabbit {
|
||||
|
||||
@@ -12,7 +15,7 @@ export class Rabbit {
|
||||
|
||||
this.connection =
|
||||
await amqp.connect(
|
||||
"amqp://manager:gigi1337@192.168.1.74"
|
||||
RABBITMQ_URL
|
||||
);
|
||||
|
||||
|
||||
@@ -20,8 +23,8 @@ export class Rabbit {
|
||||
await this.connection.createChannel();
|
||||
|
||||
|
||||
console.log(
|
||||
"RabbitMQ verbunden"
|
||||
logger.info(
|
||||
"Connected to RabbitMQ"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+141
-25
@@ -1,20 +1,34 @@
|
||||
import { getLogger } from "./logger";
|
||||
import { ServerRegistry } from "./serverRegistry";
|
||||
import { ServerManager } from "./serverManager";
|
||||
import {
|
||||
LIFECYCLE_CHECK_INTERVAL,
|
||||
LIFECYCLE_EMPTY_TIMEOUT,
|
||||
LIFECYCLE_STARTUP_GRACE_PERIOD,
|
||||
LIFECYCLE_MIN_UPTIME,
|
||||
LIFECYCLE_SCALE_DOWN_THRESHOLD,
|
||||
LIFECYCLE_SCALE_COOLDOWN,
|
||||
LIFECYCLE_CRASH_TIMEOUT,
|
||||
LIFECYCLE_CRASH_RETENTION,
|
||||
DEFAULT_DESIRED_SERVERS
|
||||
} from "./config";
|
||||
|
||||
|
||||
const logger = getLogger("ServerLifecycle");
|
||||
|
||||
export class ServerLifecycle {
|
||||
|
||||
|
||||
private creatingServers = 0;
|
||||
|
||||
|
||||
private emptyTimeout = 300000; // 5 Minuten
|
||||
private emptyTimeout = LIFECYCLE_EMPTY_TIMEOUT;
|
||||
|
||||
|
||||
private lastScaleUp = 0;
|
||||
|
||||
|
||||
private scaleCooldown = 60000; // 1 Minute
|
||||
private scaleCooldown = LIFECYCLE_SCALE_COOLDOWN;
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +39,7 @@ export class ServerLifecycle {
|
||||
|
||||
private serverManager: ServerManager,
|
||||
|
||||
private desiredServers:number = 1
|
||||
private desiredServers:number = DEFAULT_DESIRED_SERVERS
|
||||
|
||||
){}
|
||||
|
||||
@@ -36,7 +50,7 @@ export class ServerLifecycle {
|
||||
start(){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
"Server Lifecycle gestartet"
|
||||
);
|
||||
|
||||
@@ -47,7 +61,7 @@ export class ServerLifecycle {
|
||||
this.checkServers();
|
||||
|
||||
|
||||
},10000);
|
||||
},LIFECYCLE_CHECK_INTERVAL);
|
||||
|
||||
|
||||
}
|
||||
@@ -59,7 +73,7 @@ export class ServerLifecycle {
|
||||
setDesiredServers(count:number){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Neue Soll Server Anzahl:",
|
||||
count
|
||||
);
|
||||
@@ -72,6 +86,17 @@ export class ServerLifecycle {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Exposes the configured target for monitoring consumers.
|
||||
* It deliberately does not influence lifecycle behaviour.
|
||||
*/
|
||||
getDesiredServers(): number {
|
||||
|
||||
return this.desiredServers;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -110,13 +135,19 @@ export class ServerLifecycle {
|
||||
server.status =
|
||||
"RUNNING";
|
||||
|
||||
server.startedAt =
|
||||
Date.now();
|
||||
|
||||
server.emptySince =
|
||||
undefined;
|
||||
|
||||
|
||||
this.serverRegistry.update(
|
||||
server
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
"Server RUNNING:",
|
||||
server.name,
|
||||
"PID:",
|
||||
@@ -134,6 +165,43 @@ export class ServerLifecycle {
|
||||
|
||||
|
||||
|
||||
case "RECOVERING":
|
||||
|
||||
|
||||
if(
|
||||
Date.now() -
|
||||
server.lastSeen
|
||||
>
|
||||
LIFECYCLE_CRASH_TIMEOUT
|
||||
){
|
||||
|
||||
|
||||
server.status =
|
||||
"CRASHED";
|
||||
|
||||
server.crashedAt =
|
||||
Date.now();
|
||||
|
||||
|
||||
this.serverRegistry.update(
|
||||
server
|
||||
);
|
||||
|
||||
|
||||
logger.error(
|
||||
"Server-Recovery fehlgeschlagen:",
|
||||
server.name
|
||||
);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
break;
|
||||
|
||||
|
||||
|
||||
|
||||
case "RUNNING":
|
||||
|
||||
|
||||
@@ -147,20 +215,23 @@ export class ServerLifecycle {
|
||||
Date.now() -
|
||||
server.lastSeen
|
||||
>
|
||||
30000
|
||||
LIFECYCLE_CRASH_TIMEOUT
|
||||
){
|
||||
|
||||
|
||||
server.status =
|
||||
"CRASHED";
|
||||
|
||||
server.crashedAt =
|
||||
Date.now();
|
||||
|
||||
|
||||
this.serverRegistry.update(
|
||||
server
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
logger.error(
|
||||
"Server abgestürzt:",
|
||||
server.name
|
||||
);
|
||||
@@ -186,17 +257,23 @@ export class ServerLifecycle {
|
||||
|
||||
if(!server.emptySince){
|
||||
|
||||
if(
|
||||
server.startedAt &&
|
||||
Date.now() -
|
||||
server.startedAt <
|
||||
LIFECYCLE_STARTUP_GRACE_PERIOD
|
||||
){
|
||||
break;
|
||||
}
|
||||
|
||||
server.emptySince =
|
||||
Date.now();
|
||||
|
||||
|
||||
this.serverRegistry.update(
|
||||
server
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Server leer:",
|
||||
server.name
|
||||
);
|
||||
@@ -213,7 +290,7 @@ export class ServerLifecycle {
|
||||
if(server.emptySince){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Server wieder aktiv:",
|
||||
server.name
|
||||
);
|
||||
@@ -247,12 +324,43 @@ export class ServerLifecycle {
|
||||
case "CRASHED":
|
||||
|
||||
|
||||
if(!server.crashedAt){
|
||||
|
||||
console.log(
|
||||
server.crashedAt =
|
||||
Date.now();
|
||||
|
||||
this.serverRegistry.update(
|
||||
server
|
||||
);
|
||||
|
||||
logger.error(
|
||||
"Server abgestürzt erkannt:",
|
||||
server.name
|
||||
);
|
||||
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
|
||||
if(
|
||||
Date.now() -
|
||||
server.crashedAt
|
||||
>
|
||||
LIFECYCLE_CRASH_RETENTION
|
||||
){
|
||||
|
||||
logger.info(
|
||||
"Entferne abgestürzten Server nach Grace-Zeit:",
|
||||
server.name
|
||||
);
|
||||
|
||||
this.serverRegistry.remove(
|
||||
server.id
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
|
||||
break;
|
||||
|
||||
@@ -282,7 +390,8 @@ export class ServerLifecycle {
|
||||
|
||||
server =>
|
||||
server.status === "RUNNING" ||
|
||||
server.status === "STARTING"
|
||||
server.status === "STARTING" ||
|
||||
server.status === "RECOVERING"
|
||||
|
||||
);
|
||||
|
||||
@@ -359,7 +468,7 @@ export class ServerLifecycle {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
|
||||
"Kapazität:",
|
||||
|
||||
@@ -452,7 +561,7 @@ export class ServerLifecycle {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
|
||||
"Auslastung hoch - starte zusätzlichen Server"
|
||||
|
||||
@@ -501,11 +610,20 @@ export class ServerLifecycle {
|
||||
|
||||
server.emptySince &&
|
||||
|
||||
server.startedAt &&
|
||||
|
||||
Date.now() -
|
||||
server.startedAt
|
||||
>=
|
||||
LIFECYCLE_MIN_UPTIME &&
|
||||
|
||||
Date.now() -
|
||||
server.emptySince
|
||||
>
|
||||
this.emptyTimeout
|
||||
this.emptyTimeout &&
|
||||
|
||||
usage <
|
||||
LIFECYCLE_SCALE_DOWN_THRESHOLD
|
||||
|
||||
|
||||
)
|
||||
@@ -537,7 +655,8 @@ export class ServerLifecycle {
|
||||
|
||||
s =>
|
||||
s.status === "RUNNING" ||
|
||||
s.status === "STARTING"
|
||||
s.status === "STARTING" ||
|
||||
s.status === "RECOVERING"
|
||||
|
||||
)
|
||||
.length;
|
||||
@@ -559,12 +678,9 @@ export class ServerLifecycle {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
logger.info(
|
||||
"Stoppe leeren Server:",
|
||||
|
||||
server.name
|
||||
|
||||
);
|
||||
|
||||
|
||||
@@ -597,7 +713,7 @@ export class ServerLifecycle {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
|
||||
"Starte Server:",
|
||||
|
||||
@@ -647,7 +763,7 @@ export class ServerLifecycle {
|
||||
|
||||
|
||||
|
||||
console.error(
|
||||
logger.error(
|
||||
|
||||
"Server Erstellung fehlgeschlagen:",
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getLogger } from "./logger";
|
||||
import { Rabbit } from "./rabbit";
|
||||
import { WrapperRegistry } from "./wrapperRegistry";
|
||||
import { ServerRegistry, ServerInfo } from "./serverRegistry";
|
||||
@@ -6,6 +7,8 @@ import { generateServerName } from "./nameGenerator";
|
||||
import { PortManager } from "./portManager";
|
||||
import { ServerStartCommand, ServerStopCommand } from "server-manager-shared";
|
||||
|
||||
const logger = getLogger("ServerManager");
|
||||
|
||||
|
||||
export class ServerManager {
|
||||
|
||||
@@ -39,7 +42,7 @@ export class ServerManager {
|
||||
|
||||
if(!wrapper){
|
||||
|
||||
console.log(
|
||||
logger.warn(
|
||||
"Kein Wrapper verfügbar"
|
||||
);
|
||||
|
||||
@@ -208,11 +211,11 @@ export class ServerManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
|
||||
"Server Start gesendet:",
|
||||
"Starting server:",
|
||||
|
||||
server
|
||||
server.id
|
||||
|
||||
);
|
||||
|
||||
@@ -232,8 +235,8 @@ export class ServerManager {
|
||||
|
||||
if(!server){
|
||||
|
||||
console.log(
|
||||
"Server nicht gefunden:",
|
||||
logger.warn(
|
||||
"Server not found:",
|
||||
serverId
|
||||
);
|
||||
|
||||
@@ -251,8 +254,8 @@ export class ServerManager {
|
||||
|
||||
if(!wrapper){
|
||||
|
||||
console.log(
|
||||
"Wrapper nicht gefunden:",
|
||||
logger.warn(
|
||||
"Wrapper not found:",
|
||||
server.wrapperId
|
||||
);
|
||||
|
||||
@@ -298,9 +301,9 @@ export class ServerManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
"Server Stop gesendet:",
|
||||
server.name
|
||||
logger.info(
|
||||
"Stopping server:",
|
||||
serverId
|
||||
);
|
||||
|
||||
|
||||
|
||||
+131
-23
@@ -1,3 +1,9 @@
|
||||
import { getLogger } from "./logger";
|
||||
import { WrapperStatusMessage } from "server-manager-shared";
|
||||
import { JsonFileStore } from "./persistence/jsonFileStore";
|
||||
|
||||
const logger = getLogger("ServerRegistry");
|
||||
|
||||
export interface ServerInfo {
|
||||
|
||||
|
||||
@@ -10,6 +16,7 @@ export interface ServerInfo {
|
||||
|
||||
status:
|
||||
| "STARTING"
|
||||
| "RECOVERING"
|
||||
| "RUNNING"
|
||||
| "STOPPING"
|
||||
| "CRASHED";
|
||||
@@ -19,6 +26,8 @@ export interface ServerInfo {
|
||||
|
||||
queryPort:number;
|
||||
|
||||
created:number;
|
||||
|
||||
|
||||
pid?:number;
|
||||
|
||||
@@ -31,9 +40,9 @@ export interface ServerInfo {
|
||||
|
||||
emptySince?:number;
|
||||
|
||||
startedAt?:number;
|
||||
|
||||
created:number;
|
||||
|
||||
crashedAt?:number;
|
||||
|
||||
lastSeen:number;
|
||||
|
||||
@@ -41,16 +50,84 @@ export interface ServerInfo {
|
||||
}
|
||||
|
||||
|
||||
interface ServerRegistryState {
|
||||
servers: Array<{
|
||||
id:string;
|
||||
name:string;
|
||||
wrapperId:string;
|
||||
port:number;
|
||||
queryPort:number;
|
||||
created:number;
|
||||
}>;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export class ServerRegistry {
|
||||
|
||||
|
||||
|
||||
private servers =
|
||||
new Map<string, ServerInfo>();
|
||||
|
||||
private readonly persistence =
|
||||
new JsonFileStore<ServerRegistryState>(
|
||||
"serverRegistry-state.json"
|
||||
);
|
||||
|
||||
|
||||
async init(): Promise<void> {
|
||||
const state = await this.persistence.load();
|
||||
|
||||
if (!state)
|
||||
return;
|
||||
|
||||
for (const serverData of state.servers) {
|
||||
this.servers.set(
|
||||
serverData.id,
|
||||
{
|
||||
id: serverData.id,
|
||||
name: serverData.name,
|
||||
wrapperId: serverData.wrapperId,
|
||||
port: serverData.port,
|
||||
queryPort: serverData.queryPort,
|
||||
created: serverData.created,
|
||||
status: "RECOVERING",
|
||||
players: 0,
|
||||
maxPlayers: 0,
|
||||
lastSeen: Date.now()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private toState(): ServerRegistryState {
|
||||
return {
|
||||
servers: Array.from(this.servers.values()).map(
|
||||
server => ({
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
wrapperId: server.wrapperId,
|
||||
port: server.port,
|
||||
queryPort: server.queryPort,
|
||||
created: server.created
|
||||
})
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
private async saveState(): Promise<void> {
|
||||
await this.persistence.save(
|
||||
this.toState()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private persist(): void {
|
||||
void this.saveState();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -67,12 +144,13 @@ export class ServerRegistry {
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
"Server registriert:",
|
||||
server
|
||||
logger.info(
|
||||
"Server added:",
|
||||
server.id
|
||||
);
|
||||
|
||||
|
||||
this.persist();
|
||||
}
|
||||
|
||||
|
||||
@@ -126,6 +204,7 @@ export class ServerRegistry {
|
||||
);
|
||||
|
||||
|
||||
this.persist();
|
||||
}
|
||||
|
||||
|
||||
@@ -142,12 +221,13 @@ export class ServerRegistry {
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
"Server entfernt:",
|
||||
logger.info(
|
||||
"Server removed:",
|
||||
id
|
||||
);
|
||||
|
||||
|
||||
this.persist();
|
||||
}
|
||||
|
||||
|
||||
@@ -160,8 +240,8 @@ export class ServerRegistry {
|
||||
list(){
|
||||
|
||||
|
||||
console.log(
|
||||
"\n=== SERVER ÜBERSICHT ==="
|
||||
logger.info(
|
||||
"Server list output"
|
||||
);
|
||||
|
||||
|
||||
@@ -175,7 +255,7 @@ export class ServerRegistry {
|
||||
if(servers.length === 0){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
"Keine Server vorhanden"
|
||||
);
|
||||
|
||||
@@ -190,7 +270,7 @@ export class ServerRegistry {
|
||||
for(const server of servers){
|
||||
|
||||
|
||||
console.log({
|
||||
logger.info({
|
||||
|
||||
|
||||
id:
|
||||
@@ -230,7 +310,7 @@ export class ServerRegistry {
|
||||
}
|
||||
|
||||
|
||||
syncWrapperStatus(data:any){
|
||||
syncWrapperStatus(data: WrapperStatusMessage){
|
||||
|
||||
if(!data.servers)
|
||||
return;
|
||||
@@ -240,7 +320,7 @@ export class ServerRegistry {
|
||||
const runningServerIds =
|
||||
new Set(
|
||||
data.servers.map(
|
||||
(srv:any)=>srv.id
|
||||
srv => srv.id
|
||||
)
|
||||
);
|
||||
|
||||
@@ -258,8 +338,8 @@ export class ServerRegistry {
|
||||
if(server.status === "STOPPING"){
|
||||
|
||||
|
||||
console.log(
|
||||
"Server sauber beendet:",
|
||||
logger.debug(
|
||||
"Server cleanly stopped:",
|
||||
server.name
|
||||
);
|
||||
|
||||
@@ -270,12 +350,22 @@ export class ServerRegistry {
|
||||
|
||||
|
||||
}
|
||||
else if(server.status === "RUNNING"){
|
||||
else if(
|
||||
server.status === "RUNNING" ||
|
||||
server.status === "RECOVERING"
|
||||
){
|
||||
|
||||
|
||||
server.status =
|
||||
"CRASHED";
|
||||
|
||||
if(!server.crashedAt){
|
||||
|
||||
server.crashedAt =
|
||||
Date.now();
|
||||
|
||||
}
|
||||
|
||||
|
||||
this.servers.set(
|
||||
server.id,
|
||||
@@ -283,8 +373,8 @@ export class ServerRegistry {
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
"Server abgestürzt:",
|
||||
logger.warn(
|
||||
"Server crashed:",
|
||||
server.name
|
||||
);
|
||||
|
||||
@@ -333,27 +423,45 @@ export class ServerRegistry {
|
||||
|
||||
|
||||
|
||||
if(srv.alive){
|
||||
if(srv.alive && server.status !== "STOPPING"){
|
||||
|
||||
server.crashedAt =
|
||||
undefined;
|
||||
|
||||
if(!server.startedAt){
|
||||
|
||||
server.startedAt =
|
||||
srv.started;
|
||||
|
||||
}
|
||||
|
||||
server.status =
|
||||
"RUNNING";
|
||||
|
||||
}
|
||||
else if(
|
||||
server.status === "RUNNING"
|
||||
server.status === "RUNNING" ||
|
||||
server.status === "RECOVERING"
|
||||
){
|
||||
|
||||
server.status =
|
||||
"CRASHED";
|
||||
|
||||
if(!server.crashedAt){
|
||||
|
||||
server.crashedAt =
|
||||
Date.now();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
if(oldStatus !== server.status){
|
||||
|
||||
console.log(
|
||||
"Status Änderung:",
|
||||
logger.debug(
|
||||
"Status change:",
|
||||
server.name,
|
||||
oldStatus,
|
||||
"->",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { getLogger } from "./logger";
|
||||
import { Rabbit } from "./rabbit";
|
||||
import { ServerRegistry } from "./serverRegistry";
|
||||
import { ServerStartedEvent, ServerStoppedEvent } from "server-manager-shared";
|
||||
|
||||
const logger = getLogger("ServerStatusManager");
|
||||
|
||||
|
||||
export class ServerStatusManager {
|
||||
@@ -35,7 +37,7 @@ export class ServerStatusManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
"Warte auf Server Status..."
|
||||
);
|
||||
|
||||
@@ -102,7 +104,7 @@ export class ServerStatusManager {
|
||||
default:
|
||||
|
||||
|
||||
console.log(
|
||||
logger.warn(
|
||||
"Unbekannter Server Status:",
|
||||
data
|
||||
);
|
||||
@@ -158,6 +160,17 @@ export class ServerStatusManager {
|
||||
server.status =
|
||||
"RUNNING";
|
||||
|
||||
server.crashedAt =
|
||||
undefined;
|
||||
|
||||
|
||||
if(!server.startedAt){
|
||||
|
||||
server.startedAt =
|
||||
Date.now();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -168,11 +181,11 @@ export class ServerStatusManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
|
||||
"Server läuft:",
|
||||
"Server started:",
|
||||
|
||||
server.name
|
||||
data.serverId
|
||||
|
||||
);
|
||||
|
||||
@@ -211,6 +224,13 @@ export class ServerStatusManager {
|
||||
server.status =
|
||||
"CRASHED";
|
||||
|
||||
if(!server.crashedAt){
|
||||
|
||||
server.crashedAt =
|
||||
Date.now();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -221,11 +241,11 @@ export class ServerStatusManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
|
||||
"Server crashed:",
|
||||
"Server stopped:",
|
||||
|
||||
server.name
|
||||
data.serverId
|
||||
|
||||
);
|
||||
|
||||
|
||||
@@ -15,10 +15,3 @@ export interface Wrapper {
|
||||
}
|
||||
|
||||
|
||||
export interface Message {
|
||||
|
||||
type: string;
|
||||
|
||||
[key:string]: any;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { ServerRegistry } from "../serverRegistry";
|
||||
import { WrapperRegistry } from "../wrapperRegistry";
|
||||
import { ServerLifecycle } from "../serverLifecycle";
|
||||
import {
|
||||
DashboardSummary,
|
||||
HealthResponse,
|
||||
ServerDetail,
|
||||
ServerSummary,
|
||||
WrapperDetail,
|
||||
WrapperSummary
|
||||
} from "./types";
|
||||
|
||||
export interface WebApiDependencies {
|
||||
wrapperRegistry: WrapperRegistry;
|
||||
serverRegistry: ServerRegistry;
|
||||
lifecycle: ServerLifecycle;
|
||||
rabbitMqStatus?: string;
|
||||
managerStatus?: string;
|
||||
}
|
||||
|
||||
export class WebApi {
|
||||
constructor(private deps: WebApiDependencies) {}
|
||||
|
||||
getHealth(): HealthResponse {
|
||||
return {
|
||||
status: this.deps.managerStatus ?? "running",
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
getDashboard(): DashboardSummary {
|
||||
const wrappers = this.deps.wrapperRegistry.getAll();
|
||||
const servers = this.deps.serverRegistry.getAll();
|
||||
|
||||
const runningServers = servers.filter(server => server.status === "RUNNING").length;
|
||||
const totalPlayers = servers.reduce((sum, server) => sum + server.players, 0);
|
||||
const totalCapacity = servers.reduce((sum, server) => sum + server.maxPlayers, 0);
|
||||
const utilizationPercent = totalCapacity > 0 ? Math.round((totalPlayers / totalCapacity) * 100) : 0;
|
||||
|
||||
return {
|
||||
managerStatus: this.deps.managerStatus ?? "running",
|
||||
rabbitMqStatus: this.deps.rabbitMqStatus ?? "connected",
|
||||
wrapperCount: wrappers.length,
|
||||
onlineWrapperCount: wrappers.filter(wrapper => wrapper.online).length,
|
||||
serverCount: servers.length,
|
||||
runningServerCount: runningServers,
|
||||
totalPlayers,
|
||||
totalCapacity,
|
||||
utilizationPercent,
|
||||
desiredServers: this.getDesiredServers(),
|
||||
activeServers: servers.filter(server =>
|
||||
server.status === "RUNNING" || server.status === "STARTING"
|
||||
).length
|
||||
};
|
||||
}
|
||||
|
||||
getWrappers(): WrapperSummary[] {
|
||||
return this.deps.wrapperRegistry.getAll().map(wrapper => ({
|
||||
id: wrapper.id,
|
||||
hostname: wrapper.hostname,
|
||||
online: wrapper.online,
|
||||
cpu: wrapper.cpu,
|
||||
ram: wrapper.ram,
|
||||
ramFree: wrapper.ramFree,
|
||||
lastHeartbeat: wrapper.lastHeartbeat,
|
||||
serverCount: wrapper.servers.length
|
||||
}));
|
||||
}
|
||||
|
||||
getWrapper(id: string): WrapperDetail | null {
|
||||
const wrapper = this.deps.wrapperRegistry.get(id);
|
||||
|
||||
if (!wrapper) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: wrapper.id,
|
||||
hostname: wrapper.hostname,
|
||||
online: wrapper.online,
|
||||
cpu: wrapper.cpu,
|
||||
ram: wrapper.ram,
|
||||
ramFree: wrapper.ramFree,
|
||||
lastHeartbeat: wrapper.lastHeartbeat,
|
||||
serverCount: wrapper.servers.length,
|
||||
servers: wrapper.servers.map(server => ({
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
port: server.port,
|
||||
queryPort: server.queryPort,
|
||||
players: server.players,
|
||||
maxPlayers: server.maxPlayers,
|
||||
alive: server.alive,
|
||||
started: server.started
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
getServers(): ServerSummary[] {
|
||||
return this.deps.serverRegistry.getAll().map(server => ({
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
status: server.status,
|
||||
wrapperId: server.wrapperId,
|
||||
pid: server.pid,
|
||||
port: server.port,
|
||||
queryPort: server.queryPort,
|
||||
players: server.players,
|
||||
maxPlayers: server.maxPlayers,
|
||||
created: server.created,
|
||||
startedAt: server.startedAt,
|
||||
emptySince: server.emptySince
|
||||
}));
|
||||
}
|
||||
|
||||
getServer(id: string): ServerDetail | null {
|
||||
const server = this.deps.serverRegistry.get(id);
|
||||
|
||||
if (!server) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
status: server.status,
|
||||
wrapperId: server.wrapperId,
|
||||
pid: server.pid,
|
||||
port: server.port,
|
||||
queryPort: server.queryPort,
|
||||
players: server.players,
|
||||
maxPlayers: server.maxPlayers,
|
||||
created: server.created,
|
||||
startedAt: server.startedAt,
|
||||
emptySince: server.emptySince
|
||||
};
|
||||
}
|
||||
|
||||
private getDesiredServers(): number {
|
||||
return this.deps.lifecycle.getDesiredServers();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { IncomingMessage, ServerResponse } from "http";
|
||||
import { parse as parseUrl } from "url";
|
||||
import { WebApi } from "./api";
|
||||
|
||||
export function registerRoutes(server: { on: (event: string, listener: (...args: any[]) => void) => void }, api: WebApi): void {
|
||||
server.on("request", (req: IncomingMessage, res: ServerResponse) => {
|
||||
const url = parseUrl(req.url ?? "/", true);
|
||||
const pathname = url.pathname ?? "/";
|
||||
|
||||
if (pathname === "/api/health") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(api.getHealth()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/api/dashboard") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(api.getDashboard()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/api/wrappers") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(api.getWrappers()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/api/wrappers/")) {
|
||||
const id = decodeURIComponent(pathname.split("/").pop() ?? "");
|
||||
const wrapper = api.getWrapper(id);
|
||||
|
||||
if (!wrapper) {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "Wrapper not found" }));
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(wrapper));
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/api/servers") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(api.getServers()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/api/servers/")) {
|
||||
const id = decodeURIComponent(pathname.split("/").pop() ?? "");
|
||||
const server = api.getServer(id);
|
||||
|
||||
if (!server) {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "Server not found" }));
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(server));
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "Not found" }));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { createServer, IncomingMessage, ServerResponse } from "http";
|
||||
import { registerRoutes } from "./routes";
|
||||
import { WebApi, WebApiDependencies } from "./api";
|
||||
|
||||
export function createWebServer(deps: WebApiDependencies, port = 3000) {
|
||||
const api = new WebApi(deps);
|
||||
const server = createServer();
|
||||
|
||||
registerRoutes(server, api);
|
||||
|
||||
server.listen(port, () => {
|
||||
// no-op: startup is handled by the manager
|
||||
});
|
||||
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
export interface HealthResponse {
|
||||
status: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface DashboardSummary {
|
||||
managerStatus: string;
|
||||
rabbitMqStatus: string;
|
||||
wrapperCount: number;
|
||||
onlineWrapperCount: number;
|
||||
serverCount: number;
|
||||
runningServerCount: number;
|
||||
totalPlayers: number;
|
||||
totalCapacity: number;
|
||||
utilizationPercent: number;
|
||||
desiredServers: number;
|
||||
activeServers: number;
|
||||
}
|
||||
|
||||
export interface WrapperSummary {
|
||||
id: string;
|
||||
hostname: string;
|
||||
online: boolean;
|
||||
cpu: number;
|
||||
ram: number;
|
||||
ramFree: number;
|
||||
lastHeartbeat: number;
|
||||
serverCount: number;
|
||||
}
|
||||
|
||||
export interface WrapperDetail extends WrapperSummary {
|
||||
servers: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
port: number;
|
||||
queryPort: number;
|
||||
players: number;
|
||||
maxPlayers: number;
|
||||
alive: boolean;
|
||||
started: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ServerSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
wrapperId: string;
|
||||
pid?: number;
|
||||
port: number;
|
||||
queryPort: number;
|
||||
players: number;
|
||||
maxPlayers: number;
|
||||
created: number;
|
||||
startedAt?: number;
|
||||
emptySince?: number;
|
||||
}
|
||||
|
||||
export type ServerDetail = ServerSummary;
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getLogger } from "./logger";
|
||||
import { Rabbit } from "./rabbit";
|
||||
import { randomUUID } from "crypto";
|
||||
import { WrapperRegistry, WrapperInfo } from "./wrapperRegistry";
|
||||
@@ -15,6 +16,8 @@ type WrapperMessage =
|
||||
| WrapperHeartbeatMessage
|
||||
| WrapperStatusMessage;
|
||||
|
||||
const logger = getLogger("WrapperManager");
|
||||
|
||||
|
||||
export class WrapperManager {
|
||||
|
||||
@@ -43,7 +46,7 @@ export class WrapperManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
"Warte auf Wrapper..."
|
||||
);
|
||||
|
||||
@@ -99,6 +102,11 @@ export class WrapperManager {
|
||||
case "wrapper.status":
|
||||
|
||||
|
||||
logger.debug(
|
||||
"Status update received from wrapper-id",
|
||||
data.wrapperId
|
||||
);
|
||||
|
||||
this.registry.updateStatus(
|
||||
data
|
||||
);
|
||||
@@ -115,7 +123,7 @@ export class WrapperManager {
|
||||
default:
|
||||
|
||||
|
||||
console.log(
|
||||
logger.warn(
|
||||
"Unbekannte Nachricht:",
|
||||
data
|
||||
);
|
||||
@@ -185,7 +193,7 @@ export class WrapperManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Neue Wrapper ID:",
|
||||
id
|
||||
);
|
||||
@@ -414,7 +422,7 @@ export class WrapperManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
|
||||
"Heartbeat:",
|
||||
|
||||
@@ -523,23 +531,9 @@ export class WrapperManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
|
||||
"\n======================"
|
||||
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
" WRAPPER ÜBERSICHT "
|
||||
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
"======================\n"
|
||||
"Wrapper Übersicht ausgegeben"
|
||||
|
||||
);
|
||||
|
||||
@@ -550,7 +544,7 @@ export class WrapperManager {
|
||||
if(wrappers.length===0){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
|
||||
"Keine Wrapper registriert"
|
||||
|
||||
@@ -571,7 +565,7 @@ export class WrapperManager {
|
||||
|
||||
|
||||
|
||||
console.log(`
|
||||
logger.info(`
|
||||
|
||||
ID:
|
||||
${wrapper.id}
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import { getLogger } from "./logger";
|
||||
import { WrapperStatusMessage } from "server-manager-shared";
|
||||
import { JsonFileStore } from "./persistence/jsonFileStore";
|
||||
|
||||
const logger = getLogger("WrapperRegistry");
|
||||
|
||||
export interface WrapperInfo {
|
||||
|
||||
id:string;
|
||||
@@ -19,39 +25,95 @@ export interface WrapperInfo {
|
||||
lastHeartbeat:number;
|
||||
|
||||
|
||||
servers:string[];
|
||||
servers: WrapperStatusMessage["servers"];
|
||||
|
||||
}
|
||||
|
||||
interface WrapperRegistryState {
|
||||
wrappers: Array<{
|
||||
id:string;
|
||||
hostname:string;
|
||||
commandQueue:string;
|
||||
cpu:number;
|
||||
ram:number;
|
||||
}>;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export class WrapperRegistry {
|
||||
|
||||
|
||||
private wrappers =
|
||||
new Map<string, WrapperInfo>();
|
||||
|
||||
private readonly persistence =
|
||||
new JsonFileStore<WrapperRegistryState>(
|
||||
"wrapperRegistry-state.json"
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
async init(): Promise<void> {
|
||||
const state = await this.persistence.load();
|
||||
|
||||
if (!state)
|
||||
return;
|
||||
|
||||
for (const wrapperData of state.wrappers) {
|
||||
this.wrappers.set(
|
||||
wrapperData.id,
|
||||
{
|
||||
id: wrapperData.id,
|
||||
hostname: wrapperData.hostname,
|
||||
commandQueue: wrapperData.commandQueue,
|
||||
cpu: wrapperData.cpu,
|
||||
ram: wrapperData.ram,
|
||||
ramFree: wrapperData.ram,
|
||||
online: false,
|
||||
lastHeartbeat: 0,
|
||||
servers: []
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private toState(): WrapperRegistryState {
|
||||
return {
|
||||
wrappers: Array.from(this.wrappers.values()).map(
|
||||
wrapper => ({
|
||||
id: wrapper.id,
|
||||
hostname: wrapper.hostname,
|
||||
commandQueue: wrapper.commandQueue,
|
||||
cpu: wrapper.cpu,
|
||||
ram: wrapper.ram
|
||||
})
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
private async saveState(): Promise<void> {
|
||||
await this.persistence.save(
|
||||
this.toState()
|
||||
);
|
||||
}
|
||||
|
||||
add(wrapper:WrapperInfo){
|
||||
|
||||
|
||||
this.wrappers.set(
|
||||
wrapper.id,
|
||||
wrapper
|
||||
);
|
||||
|
||||
|
||||
console.log(
|
||||
"Wrapper gespeichert:",
|
||||
logger.info(
|
||||
"Wrapper added:",
|
||||
wrapper.id
|
||||
);
|
||||
|
||||
|
||||
void this.saveState();
|
||||
}
|
||||
|
||||
|
||||
@@ -108,13 +170,12 @@ export class WrapperRegistry {
|
||||
|
||||
update(wrapper:WrapperInfo){
|
||||
|
||||
|
||||
this.wrappers.set(
|
||||
wrapper.id,
|
||||
wrapper
|
||||
);
|
||||
|
||||
|
||||
void this.saveState();
|
||||
}
|
||||
|
||||
|
||||
@@ -138,7 +199,7 @@ export class WrapperRegistry {
|
||||
wrapper.online = false;
|
||||
|
||||
|
||||
console.log(
|
||||
logger.warn(
|
||||
"Wrapper offline:",
|
||||
wrapper.id
|
||||
);
|
||||
@@ -152,8 +213,7 @@ export class WrapperRegistry {
|
||||
|
||||
}
|
||||
|
||||
updateStatus(data:any){
|
||||
|
||||
updateStatus(data: WrapperStatusMessage){
|
||||
|
||||
const wrapper =
|
||||
this.wrappers.get(
|
||||
|
||||
+14
-2
@@ -5,6 +5,18 @@
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
"skipLibCheck": true,
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src"
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"wrappers": [
|
||||
{
|
||||
"id": "wrp-8adcbbf2",
|
||||
"hostname": "anjuma-int-01",
|
||||
"commandQueue": "wrapper.wrp-8adcbbf2.commands",
|
||||
"cpu": 12,
|
||||
"ram": 7932
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+1579
-305
File diff suppressed because it is too large
Load Diff
+6
-2
@@ -4,6 +4,10 @@
|
||||
"workspaces": [
|
||||
"manager",
|
||||
"wrapper",
|
||||
"shared"
|
||||
]
|
||||
"shared",
|
||||
"dashboard"
|
||||
],
|
||||
"allowScripts": {
|
||||
"esbuild@0.21.5": true
|
||||
}
|
||||
}
|
||||
|
||||
+8
-2
@@ -4,9 +4,15 @@
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json"
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"clean": "rimraf dist"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"devDependencies": {
|
||||
"typescript": "^7.0.2"
|
||||
"@types/node": "^26.1.1",
|
||||
"typescript": "^5.7.3",
|
||||
"rimraf": "^6.0.1"
|
||||
}
|
||||
}
|
||||
@@ -28,3 +28,9 @@ export interface WrapperStatusMessage {
|
||||
}>;
|
||||
ramFree: number;
|
||||
}
|
||||
|
||||
export interface WrapperRegisteredMessage {
|
||||
type: "wrapper.registered";
|
||||
wrapperId: string;
|
||||
commandQueue: string;
|
||||
}
|
||||
|
||||
+13
-4
@@ -4,11 +4,20 @@
|
||||
"module": "CommonJS",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true
|
||||
"skipLibCheck": true,
|
||||
"types": [
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"include": ["src"]
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
{
|
||||
"name": "wrapper",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"description": "Server Manager Wrapper",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "ts-node src/index.ts"
|
||||
"dev": "ts-node src/index.ts",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
|
||||
@@ -10,6 +10,12 @@ export interface WrapperConfig {
|
||||
|
||||
}
|
||||
|
||||
export const RABBITMQ_URL = "amqp://manager:gigi1337@192.168.1.74";
|
||||
export const WRAPPER_HEARTBEAT_INTERVAL = 10000;
|
||||
export const WRAPPER_STATUS_INTERVAL = 10000;
|
||||
export const WRAPPER_QUERY_INTERVAL = 5000;
|
||||
export const SERVER_SCRIPT_PATH = "/home/heroes/HeroesOfValorServer.sh";
|
||||
export const SERVER_WORKING_DIRECTORY = "/home/heroes";
|
||||
|
||||
|
||||
export function loadConfig(): WrapperConfig {
|
||||
|
||||
+45
-37
@@ -1,6 +1,6 @@
|
||||
import * as amqp from "amqplib";
|
||||
import os from "os";
|
||||
import { loadConfig, saveConfig } from "./config";
|
||||
import { loadConfig, saveConfig, RABBITMQ_URL, WRAPPER_HEARTBEAT_INTERVAL } from "./config";
|
||||
import { ProcessManager } from "./processManager";
|
||||
import { StatusReporter } from "./statusReporter";
|
||||
import { QueryManager } from "./queryManager";
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
ServerStartCommand,
|
||||
ServerStopCommand
|
||||
} from "server-manager-shared";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
const logger = getLogger("Wrapper");
|
||||
|
||||
|
||||
class Wrapper {
|
||||
@@ -36,6 +39,7 @@ class Wrapper {
|
||||
const config =
|
||||
loadConfig();
|
||||
|
||||
logger.info("Konfiguration geladen");
|
||||
|
||||
|
||||
if(config.wrapperId){
|
||||
@@ -46,7 +50,7 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Starte mit vorhandener ID:",
|
||||
this.id
|
||||
);
|
||||
@@ -55,7 +59,7 @@ class Wrapper {
|
||||
}else{
|
||||
|
||||
|
||||
console.log(
|
||||
logger.warn(
|
||||
"Keine Wrapper ID vorhanden - neue Registrierung"
|
||||
);
|
||||
|
||||
@@ -67,7 +71,7 @@ class Wrapper {
|
||||
|
||||
this.connection =
|
||||
await amqp.connect(
|
||||
"amqp://manager:gigi1337@192.168.1.74"
|
||||
RABBITMQ_URL
|
||||
);
|
||||
|
||||
|
||||
@@ -77,8 +81,8 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
"RabbitMQ verbunden"
|
||||
logger.info(
|
||||
"RabbitMQ Verbindung hergestellt"
|
||||
);
|
||||
|
||||
|
||||
@@ -136,9 +140,9 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Antwort vom Manager:",
|
||||
data
|
||||
data.type
|
||||
);
|
||||
|
||||
|
||||
@@ -162,14 +166,17 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
"Registrierung beim Manager erfolgreich"
|
||||
);
|
||||
logger.debug(
|
||||
"Wrapper ID gespeichert:",
|
||||
this.id
|
||||
);
|
||||
|
||||
if(!this.id){
|
||||
|
||||
console.error(
|
||||
logger.error(
|
||||
"Keine Wrapper ID erhalten!"
|
||||
);
|
||||
|
||||
@@ -272,7 +279,7 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Registrierung gesendet",
|
||||
this.id ?? "ohne ID"
|
||||
);
|
||||
@@ -301,63 +308,64 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
const command =
|
||||
const rawCommand =
|
||||
JSON.parse(
|
||||
msg.content.toString()
|
||||
) as ServerStartCommand | ServerStopCommand | {
|
||||
) as unknown;
|
||||
|
||||
|
||||
|
||||
const commandType = (rawCommand as { type?: string }).type;
|
||||
switch(commandType){
|
||||
|
||||
|
||||
|
||||
case "test": {
|
||||
const command = rawCommand as {
|
||||
type: string;
|
||||
[key: string]: unknown;
|
||||
message?: unknown;
|
||||
};
|
||||
|
||||
|
||||
|
||||
switch(command.type){
|
||||
|
||||
|
||||
|
||||
case "test":
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"TEST COMMAND:",
|
||||
command.message
|
||||
);
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
case "server.start":
|
||||
|
||||
case "server.start": {
|
||||
const command = rawCommand as ServerStartCommand;
|
||||
|
||||
this.processManager.startServer(
|
||||
command
|
||||
);
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
case "server.stop":
|
||||
|
||||
case "server.stop": {
|
||||
const command = rawCommand as ServerStopCommand;
|
||||
|
||||
this.processManager.stopServer(
|
||||
command.serverId
|
||||
);
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
default:
|
||||
|
||||
|
||||
console.log(
|
||||
logger.warn(
|
||||
"Unbekannter Command:",
|
||||
command
|
||||
commandType
|
||||
);
|
||||
|
||||
|
||||
@@ -375,7 +383,7 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Warte auf Commands:",
|
||||
queue
|
||||
);
|
||||
@@ -391,7 +399,7 @@ class Wrapper {
|
||||
|
||||
heartbeat(){
|
||||
|
||||
console.log("Heartbeat gestartet");
|
||||
logger.debug("Heartbeat gestartet");
|
||||
setInterval(()=>{
|
||||
|
||||
|
||||
@@ -437,13 +445,13 @@ class Wrapper {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Heartbeat gesendet"
|
||||
);
|
||||
|
||||
|
||||
|
||||
},10000);
|
||||
},WRAPPER_HEARTBEAT_INTERVAL);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
declare const process: {
|
||||
env: Record<string, string | undefined>;
|
||||
};
|
||||
|
||||
type LogLevel = "DEBUG" | "INFO" | "WARN" | "ERROR";
|
||||
|
||||
const LEVELS: Record<LogLevel, number> = {
|
||||
DEBUG: 0,
|
||||
INFO: 1,
|
||||
WARN: 2,
|
||||
ERROR: 3,
|
||||
};
|
||||
|
||||
const DEFAULT_LOG_LEVEL: LogLevel = "INFO";
|
||||
|
||||
const configuredLevel =
|
||||
(process.env.LOG_LEVEL ?? "").toUpperCase() as LogLevel;
|
||||
|
||||
const currentLogLevel: LogLevel =
|
||||
configuredLevel in LEVELS ? configuredLevel : DEFAULT_LOG_LEVEL;
|
||||
|
||||
const currentLogLevelValue = LEVELS[currentLogLevel];
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVELS[level] >= currentLogLevelValue;
|
||||
}
|
||||
|
||||
function formatMessage(
|
||||
level: LogLevel,
|
||||
component: string,
|
||||
message: unknown
|
||||
): string {
|
||||
return `${new Date().toISOString()} ${level} [${component}] ${message}`;
|
||||
}
|
||||
|
||||
class Logger {
|
||||
constructor(private component: string) {}
|
||||
|
||||
debug(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("DEBUG")) return;
|
||||
console.log(formatMessage("DEBUG", this.component, message), ...args);
|
||||
}
|
||||
|
||||
info(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("INFO")) return;
|
||||
console.log(formatMessage("INFO", this.component, message), ...args);
|
||||
}
|
||||
|
||||
warn(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("WARN")) return;
|
||||
console.warn(formatMessage("WARN", this.component, message), ...args);
|
||||
}
|
||||
|
||||
error(message: unknown, ...args: unknown[]): void {
|
||||
if (!shouldLog("ERROR")) return;
|
||||
console.error(formatMessage("ERROR", this.component, message), ...args);
|
||||
}
|
||||
}
|
||||
|
||||
export function getLogger(component: string): Logger {
|
||||
return new Logger(component);
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { spawn, ChildProcess } from "child_process";
|
||||
import { ServerStartCommand } from "server-manager-shared";
|
||||
import { SERVER_SCRIPT_PATH, SERVER_WORKING_DIRECTORY } from "./config";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
const logger = getLogger("ProcessManager");
|
||||
|
||||
|
||||
interface ServerProcess {
|
||||
@@ -45,7 +49,7 @@ export class ProcessManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Starte Game Server:",
|
||||
data.name
|
||||
);
|
||||
@@ -68,10 +72,10 @@ export class ProcessManager {
|
||||
|
||||
|
||||
const process = spawn(
|
||||
"/home/heroes/HeroesOfValorServer.sh",
|
||||
SERVER_SCRIPT_PATH,
|
||||
args,
|
||||
{
|
||||
cwd:"/home/heroes",
|
||||
cwd: SERVER_WORKING_DIRECTORY,
|
||||
stdio:"pipe",
|
||||
detached:true
|
||||
}
|
||||
@@ -88,11 +92,9 @@ export class ProcessManager {
|
||||
data=>{
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
logger.debug(
|
||||
`[${data.name}]`,
|
||||
data.toString()
|
||||
|
||||
);
|
||||
|
||||
|
||||
@@ -111,7 +113,7 @@ export class ProcessManager {
|
||||
data=>{
|
||||
|
||||
|
||||
console.error(
|
||||
logger.error(
|
||||
|
||||
"SERVER ERROR:",
|
||||
data.toString()
|
||||
@@ -140,7 +142,7 @@ export class ProcessManager {
|
||||
if(server){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
"Server beendet:",
|
||||
server.name,
|
||||
code
|
||||
@@ -198,18 +200,12 @@ export class ProcessManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
logger.info(
|
||||
"Server gestartet:",
|
||||
|
||||
{
|
||||
|
||||
id:data.serverId,
|
||||
|
||||
pid:process.pid
|
||||
|
||||
}
|
||||
|
||||
);
|
||||
|
||||
|
||||
@@ -237,7 +233,7 @@ export class ProcessManager {
|
||||
if(!server){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.warn(
|
||||
|
||||
"Server nicht gefunden:",
|
||||
|
||||
@@ -255,12 +251,9 @@ export class ProcessManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
logger.debug(
|
||||
"Stoppe Server:",
|
||||
|
||||
server.name
|
||||
|
||||
);
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { queryGameServerInfo } from "steam-server-query";
|
||||
import { ProcessManager } from "./processManager";
|
||||
import { WRAPPER_QUERY_INTERVAL } from "./config";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
const logger = getLogger("QueryManager");
|
||||
|
||||
export class QueryManager {
|
||||
|
||||
@@ -15,7 +18,7 @@ export class QueryManager {
|
||||
start(){
|
||||
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Query Manager gestartet"
|
||||
);
|
||||
|
||||
@@ -27,7 +30,7 @@ export class QueryManager {
|
||||
this.updateQueries();
|
||||
|
||||
|
||||
},5000);
|
||||
},WRAPPER_QUERY_INTERVAL);
|
||||
|
||||
|
||||
}
|
||||
@@ -72,12 +75,10 @@ export class QueryManager {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
"Query:",
|
||||
logger.debug(
|
||||
"Query erfolgreich:",
|
||||
server.name,
|
||||
`${server.players}/${server.maxPlayers}`
|
||||
|
||||
);
|
||||
|
||||
|
||||
@@ -85,11 +86,9 @@ export class QueryManager {
|
||||
catch(err){
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
logger.warn(
|
||||
"Query fehlgeschlagen:",
|
||||
server.name
|
||||
|
||||
);
|
||||
|
||||
|
||||
|
||||
@@ -3,8 +3,10 @@ import { ProcessManager } from "./processManager";
|
||||
import os from "os";
|
||||
import { QueryManager } from "./queryManager";
|
||||
import { WrapperStatusMessage } from "server-manager-shared";
|
||||
import { WRAPPER_STATUS_INTERVAL } from "./config";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
|
||||
const logger = getLogger("StatusReporter");
|
||||
|
||||
export class StatusReporter {
|
||||
|
||||
@@ -25,7 +27,7 @@ export class StatusReporter {
|
||||
|
||||
start(){
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
"Status Reporter gestartet"
|
||||
);
|
||||
|
||||
@@ -36,7 +38,7 @@ export class StatusReporter {
|
||||
this.sendStatus();
|
||||
|
||||
|
||||
},10000);
|
||||
},WRAPPER_STATUS_INTERVAL);
|
||||
|
||||
|
||||
}
|
||||
@@ -147,12 +149,9 @@ export class StatusReporter {
|
||||
|
||||
|
||||
|
||||
console.log(
|
||||
|
||||
logger.debug(
|
||||
"Status gesendet:",
|
||||
|
||||
servers.length,
|
||||
|
||||
"Server"
|
||||
|
||||
);
|
||||
|
||||
+14
-2
@@ -5,6 +5,18 @@
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
"skipLibCheck": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"types": [
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user