cosmostat active host inventory file api

This commit is contained in:
2026-04-04 17:47:32 -07:00
parent be95ab7593
commit a89703c420
26 changed files with 1243 additions and 261 deletions

View File

@ -1,91 +1,47 @@
# ------------------------------------------------------------------
# 1. Base image
# ------------------------------------------------------------------
# We use a slim Debian base so we can use aptget to pull every
# component in one go. Debian Bookworm contains all the
# packages we need (nodejs 18, redis, nginx, php8fpm, etc.).
# ------------------------------------------------------------------
FROM php:8.0-apache
# ------------------------------------------------------------------
# 2. Build arguments handy if you want to change the port numbers
# without touching the Dockerfile
# ------------------------------------------------------------------
ARG REDIS_PORT=6379
ARG NODE_PORT=3000
ARG PHP_PORT=8080
ARG NGX_PORT=80
# Base image
FROM php:8.1-apache
ENV REDIS_PORT=${REDIS_PORT}
ENV NODE_PORT=${NODE_PORT}
ENV PHP_PORT=${PHP_PORT}
ENV NGX_PORT=${NGX_PORT}
# Install system packages
RUN apt-get update && apt-get install -y --no-install-recommends \
# Services
redis-server nginx \
# Process supervisor
supervisor \
# Clean up
&& rm -rf /var/lib/apt/lists/*
# ------------------------------------------------------------------
# 3. Install all the system packages we need
# ------------------------------------------------------------------
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive apt-get install -y \
curl gnupg ca-certificates \
nodejs npm \
redis-server \
nginx \
supervisor \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
# Install Node.js LTS 18.x
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
&& apt-get update && apt-get install -y nodejs \
&& rm -rf /var/lib/apt/lists/*
# ------------------------------------------------------------------
# 4. Prepare the working directories
# ------------------------------------------------------------------
# Node app
WORKDIR /app
COPY web/node_server/package.json ./
RUN npm install
COPY web/node_server/ ./
# Webdashboard static files
COPY web/html /var/www/html/
# API settings file
# copy the config file
COPY cosmostat_settings.yaml /app/cosmostat_settings.yaml
# Nginx config you can keep the same file you used for the
# proxy service in the compose file. It will proxy 3000 (WS)
# and 8080 (PHP) to the local container.
COPY web/proxy/nginx.conf /etc/nginx/nginx.conf
# Node on 3000
WORKDIR /usr/src/app
COPY web/node_server/ .
RUN npm install --only=production
# ------------------------------------------------------------------
# 5. Supervisord configuration
# ------------------------------------------------------------------
# Create a minimal supervisord.conf that will launch the four
# services from the same container.
RUN mkdir -p /etc/supervisor/conf.d && \
cat > /etc/supervisor/conf.d/supervisord.conf <<EOF
[supervisord]
nodaemon=true
# Apache on 8080
RUN sed -i 's/^Listen .*/Listen 8080/' /etc/apache2/ports.conf && \
sed -i 's/<VirtualHost \*:80>/<VirtualHost \*:8080>/' /etc/apache2/sites-enabled/000-default.conf
COPY web/html/ /var/www/html/
[program:redis]
command=/usr/bin/redis-server --port ${REDIS_PORT}
autostart=true
autorestart=true
user=root
# nginx on 80
RUN rm -rf /etc/nginx/sites-enabled/default
COPY web/proxy/nginx.conf /etc/nginx/conf.d/default.conf
[program:node]
command=npm run start
autostart=true
autorestart=true
user=root
# Add supervisord configuration
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
[program:nginx]
command=/usr/sbin/nginx -g 'daemon off;'
autostart=true
autorestart=true
user=root
EOF
# Expose ports
EXPOSE 80
EXPOSE 6379
# ------------------------------------------------------------------
# 6. Expose the ports
# ------------------------------------------------------------------
EXPOSE ${REDIS_PORT} ${NGX_PORT}
# healthcheck looks for apache
HEALTHCHECK CMD netstat -ltn | grep -c ":8080" > /dev/null; if [ 0 != $? ]; then exit 1; fi;
# 7. Default command start supervisord
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
# Start supervisord
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

View File

@ -1,48 +0,0 @@
FROM php:8.0-apache
RUN set -eux; \
apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
gnupg \
lsb-release \
wget \
curl \
sudo \
redis-server \
nginx \
supervisor \
&& curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Node application
COPY web/node_server/ .
RUN npm install --only=production
#RUN npm ci --production
# PHP static files (public web root)
COPY web/html/ /var/www/html/
# NGINX config (overwrites the default)
COPY web/proxy/nginx.conf /etc/nginx/conf.d/default.conf
# Shared settings file (readonly)
COPY cosmostat_settings.yaml /app/cosmostat_settings.yaml
# Supervisor configuration
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# Entrypoint script
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
EXPOSE 6379
EXPOSE 80
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

View File

@ -1,6 +0,0 @@
#!/bin/sh
# Ensure the shared config file is readable
chmod 644 /app/cosmostat_settings.yaml
# Let Supervisor do the heavy lifting
exec "$@"

View File

@ -1,22 +1,46 @@
[supervisord]
nodaemon=true
logfile=/dev/stdout
logfile_maxbytes=0
# ------------------------------------------------------------------
# 1. Apache (from the base image)
# ------------------------------------------------------------------
[program:apache2]
command=/usr/sbin/apache2ctl -D FOREGROUND
stdout_logfile=/dev/stdout
stderr_logfile=/dev/stderr
autorestart=true
priority=1
# ------------------------------------------------------------------
# 2. Redis
# ------------------------------------------------------------------
[program:redis]
command=/usr/bin/redis-server
stdout_logfile=/dev/stdout
stderr_logfile=/dev/stderr
[program:node]
command=sh -c "cd /app && node server.js"
stdout_logfile=/dev/stdout
stderr_logfile=/dev/stderr
[program:apache]
command=/usr/sbin/httpd -DFOREGROUND
command=/usr/bin/redis-server --daemonize no --protected-mode no
stdout_logfile=/dev/stdout
stderr_logfile=/dev/stderr
autorestart=true
priority=2
# ------------------------------------------------------------------
# 3. Nginx (will listen on 8080 by default)
# ------------------------------------------------------------------
[program:nginx]
command=nginx -g "daemon off;"
command=/usr/sbin/nginx -g 'daemon off;'
stdout_logfile=/dev/stdout
stderr_logfile=/dev/stderr
stderr_logfile=/dev/stderr
autorestart=true
priority=3
# ------------------------------------------------------------------
# 4. Node.js
# ------------------------------------------------------------------
# NOTE: Adjust the command/path to match your app
[program:node]
command=npm start
directory=/usr/src/app
stdout_logfile=/dev/stdout
stderr_logfile=/dev/stderr
autorestart=true
priority=4

View File

@ -0,0 +1,143 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cosmostat - <?php echo $_SERVER['SERVER_NAME'] ?></title>
<style>
.components {display:grid; grid-template-columns:repeat(auto-fill, minmax(280px, 1fr)); gap:1rem;}
.component {padding:10px; border:1px solid; border-radius:4px;}
.component h3{margin-top:0; margin-bottom:5px;}
.info-list {list-style:none; padding-left:0;}
.info-list li{margin-bottom:3px;}
.system-list {list-style:none; padding-left:0; margin-top:1em;}
.system-list li{margin-bottom:5px; font-weight:400;}
</style>
<link rel="stylesheet" href="src/styles.css">
</head>
<body>
<div class="card">
<h2>Matt-Cloud Cosmostat Dashboard</h2>
This dashboard shows the local Matt-Cloud system stats.<p>
<div class="help-link" id="helpToggle" >API</div>
</div>
<div id="helpText" class="card">
<strong>Component Desriptor</strong><p>
To view the component descriptor, you may <br>
<code>
curl -s https://<?php echo $_SERVER['SERVER_NAME'] ?>/descriptor<br>
</code>
This will return the entire JSON descriptor variable
</div>
<div class="card">
<div id="host_components" class="column">
<!-- PHP to render static components -->
<?php
# load API settings, this requires a simple yaml file
$raw_api_settings = file('/app/cosmostat_settings.yaml', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$api_settings = [];
foreach ($raw_api_settings as $line) {
if ($line[0] === '#') {
continue;
}
$pos = strpos($line, ':');
if ($pos === false) {
continue;
}
$key = trim(substr($line, 0, $pos));
$value = trim(substr($line, $pos + 1));
if ($value === '') {
$value = null;
}
$api_settings[$key] = $value;
}
$api_bind_ip = trim($api_settings['api_bind_ip'], "\"'") ?? null;
$customApiPort = trim($api_settings['custom_api_port'], "\"'") ?? null;
# load API data
$apiUrl = 'http://'.$api_bind_ip.':'.$customApiPort.'/php_summary';
echo "<!-- apiUrl - ".$apiUrl." -->";
$context = stream_context_create([
'http' => [
'timeout' => 5, // seconds
'header' => "User-Agent: PHP/" . PHP_VERSION . "\r\n"
]
]);
$json = @file_get_contents($apiUrl, false, $context);
if ($json === false) {
die('<p style="color:red;">Could not fetch data from the API.</p>');
}
$data = json_decode($json, true);
if ($data === null) {
die('<p style="color:red;">Malformed JSON returned from the API.</p>');
}
function h(string $s): string
{
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
?>
<?php if (isset($data[0]['system_properties'])): ?>
<h2>System Properties</h2>
<div class="system">
<table>
<tr><td>
<ul class="system-list">
<?php foreach ($data[0]['system_properties'] as $prop): ?>
<li><?= h($prop['Property']); ?></li>
<?php endforeach; ?>
</ul>
</td><td>
<!-- Javascript to render static components -->
<h2>Live System Metrics</h2>
<div id="host_metrics" class="column">Connecting...</div>
</td></tr>
</table>
</div>
<?php endif; ?>
<?php if (isset($data[0]['system_components'])): ?>
<h2>Components</h2>
<div class="components">
<?php foreach ($data[0]['system_components'] as $comp): ?>
<div class="component">
<h3><?= h($comp['component_name']); ?></h3>
<ul class="info-list">
<?php foreach ($comp['info_strings'] as $info): ?>
<li><?= h($info); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<!-- PHP rendered HTML ends here -->
</div>
</div>
<!-- Socket.IO client library -->
<script src="socket.io/socket.io.js"></script>
<!-- matt-cloud redis script -->
<script src="src/redis.js"></script>
<!-- Toggle the help text when the link is clicked -->
<script>
document.getElementById('helpToggle').addEventListener('click', function () {
const help = document.getElementById('helpText');
if (help.style.display === 'none' || help.style.display === '') {
help.style.display = 'block';
} else {
help.style.display = 'none';
}
});
</script>
</body>
</html>

View File

@ -0,0 +1,145 @@
/* ------------------------------------------------------------
1. Socket-IO connection & helper functions (unchanged)
------------------------------------------------------------ */
const socket = io();
socket.on('host_metrics', renderStatsTable);
socket.on('connect_error', err => {
safeSetText('host_metrics', `Could not connect to server - ${err.message}`);
});
socket.on('reconnect', attempt => {
safeSetText('host_metrics', `Re-connected (attempt ${attempt})`);
});
function safeSetText(id, txt) {
const el = document.getElementById(id);
if (el) el.textContent = txt;
}
/* ------------------------------------------------------------------
2. Table rendering - now orders rows before building the table
------------------------------------------------------------------ */
// helper function for table row ordering
function renderStatsTable(data) {
socket.emit('tableRendered');
renderGenericTable('host_metrics', data, 'No Stats available');
}
function renderGenericTable(containerId, data, emptyMsg) {
const container = document.getElementById(containerId);
if (!Array.isArray(data) || !data.length) {
container.textContent = emptyMsg;
return;
}
/* Merge rows by name (new logic) */
const mergedData = mergeRowsByName(data);
/* Order the merged rows priority first */
const orderedData = orderRows(mergedData);
/* Build the table from the ordered data */
const table = buildTable(orderedData);
table.id = 'host_metrics_table';
container.innerHTML = '';
container.appendChild(table);
}
/* ------------------------------------------------------------
3. Merge rows by name
------------------------------------------------------------ */
function mergeRowsByName(data) {
const groups = {}; // { source: { ... } }
data.forEach(row => {
const source = row.Source; // <-- changed
if (!source) return;
if (!groups[source]) {
groups[source] = { Metric: [], Data: [] };
}
if ('Metric' in row && 'Data' in row) {
groups[source].Metric.push(row.Metric);
groups[source].Data.push(row.Data);
}
});
const merged = [];
Object.entries(groups).forEach(([source, grp]) => {
merged.push({
Source: source, // <-- keep the original key
Metric: grp.Metric,
Data: grp.Data,
Property: grp.Property,
Value: grp.Value
});
});
return merged;
}
// 3b. Order rows put “System”, “CPU”, “RAM” first
function orderRows(rows) {
// Priority list can be updated later
const priority = ['System', 'CPU', 'RAM'];
// Map source → priority index
const priorityMap = {};
priority.forEach((src, idx) => {
priorityMap[src] = idx;
});
// Stable sort: keep original position if priorities are equal
return [...rows].sort((a, b) => {
const aIdx = priorityMap.hasOwnProperty(a.Source)
? priorityMap[a.Source]
: Infinity; // anything not in priority goes to the end
const bIdx = priorityMap.hasOwnProperty(b.Source)
? priorityMap[b.Source]
: Infinity;
// If both have the same priority (or both Infinity), keep original order
return aIdx - bIdx;
});
}
/* ------------------------------------------------------------
4. Build an HTML table from an array of objects
------------------------------------------------------------ */
function buildTable(data) {
const cols = ['Source', 'Metric', 'Data']; // explicit order
const table = document.createElement('table');
// Header
const thead = table.createTHead();
const headerRow = thead.insertRow();
cols.forEach(col => {
const th = document.createElement('th');
th.textContent = col;
headerRow.appendChild(th);
});
// Body
const tbody = table.createTBody();
data.forEach(item => {
const tr = tbody.insertRow();
cols.forEach(col => {
const td = tr.insertCell();
const val = item[col];
if (Array.isArray(val)) {
// Create a <span> for each item
val.forEach((v, idx) => {
td.id = 'host_metrics_column';
const span = document.createElement('span');
span.textContent = v;
td.appendChild(span);
// Insert a line break after every item except the last
if (idx < val.length - 1) td.appendChild(document.createElement('br'));
});
} else {
td.textContent = val !== undefined ? val : '';
}
});
});
return table;
}

View File

@ -0,0 +1,246 @@
/* -------------------------------------------------
1. Global settings & color palette
------------------------------------------------- */
:root {
/* Dark theme - body & card backgrounds */
--bg-body: #2c3e50; /* main page background */
--bg-card: #34495e; /* card / panel background */
--bg-sidebar: #3d566e; /* sidebar background (slightly lighter) */
/* Accent / link colour */
--clr-accent: #3498db; /* blue accent for links */
/* Text colour */
--clr-text: #ecf0f1; /* light whiteish text */
/* Borders / accents */
--clr-border: #1f2b38; /* dark border colour */
}
* { box-sizing: border-box; }
/* Body */
body {
margin: 0;
padding: 0;
background: var(--bg-body);
color: var(--clr-text);
font-family: Arial, Helvetica, sans-serif;
}
/* Links */
a { color: var(--clr-accent); text-decoration: none; }
a:hover { text-decoration: underline; }
/* -------------------------------------------------
2. Layout - wrapper, sidebar, main
------------------------------------------------- */
.wrapper { display: flex; min-height: 100vh; }
.sidebar {
position: fixed; /* keep sidebar visible during scroll */
top: 0; /* stick to the top of the viewport */
left: 0; /* align to the left edge */
height: 100vh; /* full viewport height */
/* ---- size & spacing ------------------------------------------- */
width: 200px; /* same as before */
padding: 1rem;
overflow-y: auto; /* allow sidebar content to scroll if needed */
/* ---- look ------------------------------------------------------- */
background: var(--bg-sidebar);
/* optional: keep it above other content */
z-index: 1000;
}
.sidebar h3 { margin: 0 0 .4rem 0; font-size: 1.1rem; }
.sidebar ul { list-style: none; padding: 0; margin: 0; }
.sidebar ol { list-style: none; padding: 0; margin: 0; }
.sidebar li { margin-bottom: .4rem; }
.sidebar a { color: var(--clr-accent); }
.sidebar a.active { font-weight: bold; }
.main{
flex: 1;
padding: 1rem;
padding-left: 200px; /* space for the fixed sidebar */
/* optional: avoid accidental horizontal overflow */
overflow-x: hidden;
}
/* -------------------------------------------------
3. Card component
------------------------------------------------- */
.card {
max-width: 950px;
margin: 20px auto 1rem auto;
padding: 20px;
background: var(--bg-card);
border: 1px solid var(--clr-border);
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,.3);
}
/* -------------------------------------------------
4. Tables
------------------------------------------------- */
table, th, td {
border: 2px solid var(--clr-border);
border-collapse: collapse;
}
th, td { padding: 10px; }
/* Alternate row colour for metrics table */
#host_metrics_table tbody tr td:nth-of-type(even) {
background: #3e5c78; /* slight contrast */
}
/* -------------------------------------------------
5. Lists & headings
------------------------------------------------- */
h1, h2, h3, h4 { color: var(--clr-text); margin: 0 0 .4rem 0; }
ul { list-style: none; padding: 0; }
ol { list-style: none; padding: 0; }
li { margin-bottom: 10px; color: var(--clr-text); }
/* System & component lists */
.system-list, .info-list {
list-style: none; padding: 0; margin: 0;
}
.system-list li, .info-list li { margin-bottom: 5px; color: var(--clr-text); }
/* -------------------------------------------------
6. Components grid
------------------------------------------------- */
.components {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1rem;
}
.component {
padding: 10px;
border: 1px solid var(--clr-border);
border-radius: 4px;
}
.component h3 { margin: 0 0 5px; }
/* -------------------------------------------------
7. Panel toggles / modal
------------------------------------------------- */
.help-link {
cursor: pointer;
user-select: none;
color: var(--clr-accent);
text-align: right;
}
.help-link:hover { text-decoration: underline; }
#helpText { display: none; }
.componentDetail-link {
cursor: pointer;
user-select: none;
color: var(--clr-accent);
text-align: left;
}
.componentDetail-link:hover { text-decoration: underline; }
#componentDetailText { display: none; }
/* -------------------------------------------------
8. Misc helpers
------------------------------------------------- */
/* Hide numeric markers in metric columns (if any) */
#host_metrics_column td { list-style: none; padding-left: 0; margin-left: 0; }
.host-status {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-left: 6px;
margin-right: 8px;
vertical-align: middle;
background: #808080; /* default unknown / no timestamp */
transition: background-color 1s linear; /* smooth fade */
}
/* -------------------------------------------------
9. Mobile adjustments
------------------------------------------------- */
@media (max-width: 768px) {
/* 1. Make the whole page a column */
.wrapper {
flex-direction: column;
}
/* 2. Hide the sidebar initially */
.sidebar {
position: relative; /* take it out of the flow */
width: 100%;
max-height: 0; /* collapsed */
overflow: hidden;
transition: max-height 0.3s ease-out;
background: var(--bg-sidebar);
padding: 0; /* remove padding */
}
.sidebar.show {
max-height: 500px; /* enough for all items */
padding: 1rem;
}
/* 3. Move the toggle button into the header */
.mobile-toggle {
display: block;
font-size: 1.5rem;
background: transparent;
border: none;
color: var(--clr-accent);
padding: 0.5rem;
margin-bottom: 0.5rem;
}
/* 4. Main content no left padding */
.main {
padding-left: 0;
padding-right: 1rem;
}
/* 5. Table scroll on small screens */
.card table {
width: 100%;
table-layout: fixed;
}
.card table thead,
.card table tbody,
.card table tr,
.card table td,
.card table th {
display: block;
}
.card table tbody {
overflow-x: auto;
white-space: nowrap;
}
.card table td,
.card table th {
display: inline-block;
vertical-align: top;
width: 30%;
}
/* 6. Adjust the host status dot positioning */
.host-status {
margin-left: 2px;
margin-right: 12px;
}
}
/* Optional: style the drawer indicator */
.sidebar.show::before {
content: "✕ Close";
display: block;
padding: 0.5rem 1rem;
background: var(--bg-sidebar);
color: var(--clr-accent);
font-weight: bold;
}

View File

@ -0,0 +1,15 @@
{
"name": "redis-table-demo",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"socket.io": "^4.7.2",
"redis": "^4.6.7",
"node-fetch": "^2.6.7",
"js-yaml": "^4.1.0"
}
}

View File

@ -0,0 +1,132 @@
// server.js
const http = require('http');
const express = require('express');
const { createClient } = require('redis');
const { Server } = require('socket.io');
const fetch = require('node-fetch'); // npm i node-fetch@2
const fs = require('fs');
const yaml = require('js-yaml'); // npm i js-yaml
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
/* --------------------------------------------------------------------- */
/* ---------- 1. Load the YAML configuration file ---------------------- */
/* --------------------------------------------------------------------- */
let config = {};
try {
const file = fs.readFileSync(path.resolve(__dirname, 'cosmostat_settings.yaml'), 'utf8');
config = yaml.load(file);
} catch (e) {
console.error('Failed to load config.yaml:', e);
process.exit(1);
}
const API_PORT = config.custom_api_port || 5000; // fallback to 5000
const API_HOST = config.api_bind_ip || '192.168.37.1'; // fallback IP
const API_BASE = `http://${API_HOST}:${API_PORT}`;
console.log('API URL:', API_BASE);
// ---------------------------------------------------------------------
// ---------- 2. Socket.io ------------------------------------------------
// ---------------------------------------------------------------------
io.on('connection', async socket => {
console.log('client connected:', socket.id);
// Call the external API every time a client connects
try {
const resp = await fetch(`${API_BASE}/start_timer`, { method: 'GET' });
const data = await resp.json();
console.log('API responded to connect:', data);
} catch (err) {
console.error('Failed to hit start_timer endpoint:', err);
}
// Listen for tableRendered event from the client
socket.on('tableRendered', async () => {
console.log('Client reported table rendered - starting timer');
try {
const resp = await fetch(`${API_BASE}/start_timer`, { method: 'GET' });
const text = await resp.text();
console.log('Timer endpoint responded:', text);
} catch (err) {
console.error('Failed to hit start_timer:', err);
}
});
});
/* --------------------------------------------------------------------- */
/* ---------- 3. Serve static files ----------------------------------- */
/* --------------------------------------------------------------------- */
app.use(express.static('public'));
/* --- 4. Redis subscriber (patched) --------------------------------- */
const redisClient = createClient({
url: 'redis://0.0.0.0:6379',
socket: { keepAlive: 60000, // 60s TCP keep-alive
reconnectStrategy: attempts => Math.min(attempts * 100, 3000) } // back-off
});
redisClient.on('error', err => console.error('Redis error', err));
(async () => {
await redisClient.connect();
const sub = redisClient.duplicate();
await sub.connect();
// --------------------------------------------------------------------
// Helper that re-subscribes to a channel (and re-sends the handler)
// --------------------------------------------------------------------
async function safeSubscribe(channel, handler) {
try {
await sub.subscribe(channel, handler);
console.log(`Subscribed to ${channel}`);
} catch (e) {
console.error(`Failed to subscribe to ${channel}`, e);
}
}
// ---------------------------------------------------------------
// Subscribe to all required channels
// ---------------------------------------------------------------
await safeSubscribe('host_metrics', (msg) => forward('host_metrics', msg));
await safeSubscribe('client_summary', (msg) => forward('client_summary', msg));
// ---------------------------------------------------------------
// Forward messages to Socket.io
// ---------------------------------------------------------------
function forward(channel, message) {
try {
const payload = JSON.parse(message);
io.emit(channel, payload);
} catch (e) {
console.error(`Failed to parse message from ${channel}`, e);
}
}
// ----------------------------------------------------------------
// Re-subscribe automatically when the Redis connection reconnects
// ----------------------------------------------------------------
sub.on('reconnecting', () => console.log('Redis reconnecting…'));
sub.on('ready', async () => {
console.log('Redis ready - re-subscribing to all channels');
await safeSubscribe('host_metrics', (msg) => forward('host_metrics', msg));
await safeSubscribe('client_summary', (msg) => forward('client_summary', msg));
});
// Optional: if the connection ends for any reason, close the process
sub.on('end', () => {
console.error('Redis connection closed - exiting');
process.exit(1);
});
})();
/* --------------------------------------------------------------------- */
/* ---------- 5. Start the HTTP server --------------------------------- */
/* --------------------------------------------------------------------- */
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`);
});

View File

@ -0,0 +1,63 @@
# nginx.conf
# This file will be mounted into /etc/nginx/conf.d/default.conf inside the container
# Enable proxy buffers (optional but recommended)
proxy_buffering on;
proxy_buffers 16 16k;
proxy_buffer_size 32k;
server {
listen 80;
server_name localhost;
# ---------------------------------------
# API Endpoints
# ---------------------------------------
location = /descriptor {
proxy_pass http://192.168.37.1:5000/descriptor;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /update_client {
proxy_pass http://192.168.37.1:5000/update_client;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /create_client {
proxy_pass http://192.168.37.1:5000/create_client;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# ---------------------------------------
# WebSocket endpoint
# ---------------------------------------
location /socket.io/ {
proxy_pass http://192.168.37.1:3000/socket.io/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# ---------------------------------------
# All other paths → Apache (PHP)
# ---------------------------------------
location / {
proxy_pass http://192.168.37.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}