cosmostat python comment enrichment

This commit is contained in:
2026-03-29 10:38:07 -07:00
parent 9646ee92fd
commit 6453a839a9
14 changed files with 95 additions and 791 deletions

View File

@ -1,218 +0,0 @@
/* ------------------------------------------------------------------ */
/* 1. SocketIO connection & helpers unchanged */
/* ------------------------------------------------------------------ */
const socket = io();
socket.on('connect_error', err => {
safeSetText('status', `Could not connect to server - ${err.message}`);
});
socket.on('reconnect', attempt => {
safeSetText('status', `Re-connected (attempt ${attempt})`);
});
function safeSetText(id, txt) {
const el = document.getElementById(id);
if (el) el.textContent = txt;
}
/* ------------------------------------------------------------------ */
/* 2. Global state */
/* ------------------------------------------------------------------ */
let selectedHost = null; // hostname that is currently displayed
const hostDataMap = {}; // hostname → client object (from CLIENT_LIST)
/* ------------------------------------------------------------------ */
/* 3. Build the host list once the page is ready */
/* ------------------------------------------------------------------ */
function initHostList() {
const listEl = document.getElementById('host-list');
listEl.innerHTML = ''; // clear any stray markup
CLIENT_LIST.forEach(host => {
hostDataMap[host.hostname] = host; // cache for quick lookup
const item = document.createElement('div');
item.textContent = host.hostname;
item.className = 'host-item';
item.dataset.hostname = host.hostname;
item.addEventListener('click', () => selectHost(host.hostname));
listEl.appendChild(item);
});
// autoselect the first host (you could also stay on "Loading…" until the user clicks)
if (CLIENT_LIST.length) selectHost(CLIENT_LIST[0].hostname);
}
/* ------------------------------------------------------------------ */
/* 4. Handle host click update UI and request live metrics */
/* ------------------------------------------------------------------ */
function selectHost(hostname) {
if (selectedHost === hostname) return; // already selected
selectedHost = hostname;
// Update active styling in the list
document.querySelectorAll('.host-item').forEach(el => {
el.classList.toggle('active', el.dataset.hostname === hostname);
});
// Render the static part of the page for this host
renderHostContent(hostDataMap[hostname]);
// Now request the live metrics for this host
// The server sends an array of all hosts well filter below
// (If you have a dedicated endpoint you could request only the chosen host here)
}
/* ------------------------------------------------------------------ */
/* 5. Render the static content (system properties + components) */
/* ------------------------------------------------------------------ */
function renderHostContent(host) {
const main = document.getElementById('main-content');
main.innerHTML = ''; // clear
// 5a. System Properties
if (host.client_properties?.[0]?.system_properties?.length) {
const propSection = document.createElement('div');
propSection.innerHTML = '<h2>System Properties</h2>';
const ul = document.createElement('ul');
ul.className = 'system-list';
host.client_properties[0].system_properties.forEach(p => {
const li = document.createElement('li');
li.textContent = p.Property;
ul.appendChild(li);
});
propSection.appendChild(ul);
main.appendChild(propSection);
}
// 5b. Components
if (host.client_properties?.[0]?.system_components?.length) {
const compSection = document.createElement('div');
compSection.innerHTML = '<h2>Components</h2>';
const compGrid = document.createElement('div');
compGrid.className = 'components';
host.client_properties[0].system_components.forEach(c => {
const compDiv = document.createElement('div');
compDiv.className = 'component';
compDiv.innerHTML = `<h3>${c.component_name}</h3>`;
const ul = document.createElement('ul');
ul.className = 'info-list';
c.info_strings.forEach(str => {
const li = document.createElement('li');
li.textContent = str;
ul.appendChild(li);
});
compDiv.appendChild(ul);
compGrid.appendChild(compDiv);
});
compSection.appendChild(compGrid);
main.appendChild(compSection);
}
// 5c. Placeholder for live metrics will be filled by Socket.IO
const metricsDiv = document.createElement('div');
metricsDiv.id = 'client_summary';
metricsDiv.textContent = 'Connecting…';
main.appendChild(metricsDiv);
}
/* ------------------------------------------------------------------ */
/* 6. Render metrics called when a client_summary event arrives */
/* ------------------------------------------------------------------ */
socket.on('client_summary', data => {
// `data` is an array of host objects (the same structure as CLIENT_LIST)
// Find the one that matches the currently selected host
const host = data.find(h => h.hostname === selectedHost);
if (!host) return; // no data for this host yet
const metrics = host.redis_data;
renderStatsTable('client_summary', metrics, 'No Stats available');
});
/* 7. Table rendering unchanged except we now target a specific
container (e.g. id = 'client_summary') */
function renderStatsTable(containerId, data, emptyMsg) {
socket.emit('tableRendered');
renderGenericTable(containerId, data, emptyMsg);
}
function renderGenericTable(containerId, data, emptyMsg) {
const container = document.getElementById(containerId);
if (!Array.isArray(data) || !data.length) {
container.textContent = emptyMsg;
return;
}
const mergedData = mergeRowsByName(data);
const orderedData = orderRows(mergedData);
const table = buildTable(orderedData);
table.id = `${containerId}_table`;
container.innerHTML = '';
container.appendChild(table);
}
function mergeRowsByName(data) {
const groups = {}; // { source: { Metric: [], Data: [] } }
data.forEach(row => {
const source = row.Source;
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,
Metric: grp.Metric,
Data: grp.Data
});
});
return merged;
}
function orderRows(rows) {
const priority = ['System', 'CPU', 'RAM'];
const priorityMap = {};
priority.forEach((src, idx) => priorityMap[src] = idx);
return [...rows].sort((a, b) => {
const aIdx = priorityMap[a.Source] ?? Infinity;
const bIdx = priorityMap[b.Source] ?? Infinity;
return aIdx - bIdx;
});
}
function buildTable(data) {
const cols = ['Source', 'Metric', 'Data'];
const table = document.createElement('table');
const thead = table.createTHead();
const headerRow = thead.insertRow();
cols.forEach(col => {
const th = document.createElement('th');
th.textContent = col;
headerRow.appendChild(th);
});
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)) {
val.forEach((v, idx) => {
const span = document.createElement('span');
span.textContent = v;
td.appendChild(span);
if (idx < val.length - 1) td.appendChild(document.createElement('br'));
});
} else {
td.textContent = val ?? '';
}
});
});
return table;
}
/* ------------------------------------------------------------------ */
/* 8. Kick things off when the DOM is ready */
/* ------------------------------------------------------------------ */
document.addEventListener('DOMContentLoaded', initHostList);

View File

@ -1,107 +0,0 @@
<?php
/* ------------------------------------------------------------------ */
/* Load the API that returns the list of all clients */
/* ------------------------------------------------------------------ */
# load API settings, this requires a simple yaml file
$raw_api_settings = file('/opt/api_settings/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;
$apiUrl = 'http://'.$api_bind_ip.':'.$customApiPort.'/client_details';
$apiCtx = stream_context_create([
'http' => [
'timeout' => 5,
'header' => "User-Agent: PHP/".PHP_VERSION."\r\n"
]
]);
$apiJson = @file_get_contents($apiUrl, false, $apiCtx);
$clients = json_decode($apiJson, true) ?: [];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cosmostat Server Dashboard</title>
<link rel="stylesheet" href="src/styles.css">
<style>
/* ------------------------------------------------------------------ */
/* Layout tweaks 2 column grid, left column 200px wide */
/* ------------------------------------------------------------------ */
.layout{display:grid;grid-template-columns:200px 1fr;gap:1rem;}
.sidebar{background:#34495e;padding:10px;border-radius:6px;}
.main{background:#34495e;padding:20px;border-radius:6px;}
.host-item{cursor:pointer;color:#bdc3c7;padding:4px 8px;border-radius:4px;}
.host-item:hover{background:#2c3e50;}
.host-item.active{background:#1abc9c;color:#fff;}
/* Preserve existing table styling --------------------------------- */
</style>
</head>
<body>
<div class="card">
<h2>Matt-Cloud Cosmostat Dashboard</h2>
<p>This dashboard shows MattCloud 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</code>
<p>This will return the entire JSON descriptor variable
</div>
<!-- --------------------------------------------------- -->
<!-- Page layout sidebar + main content -->
<!-- --------------------------------------------------- -->
<div class="layout">
<!-- Left side host list -->
<div class="sidebar">
<h3>Hosts</h3>
<div id="host-list"></div>
</div>
<!-- Right side content -->
<div class="main" id="main-content">
<h2>Loading…</h2>
</div>
</div>
<!-- --------------------------------------------------- -->
<!-- The client list is embedded so JS can build UI -->
<!-- --------------------------------------------------- -->
<script>
/* Expose the whole client list to JS this is the data that
the old PHP template used to render one host. */
const CLIENT_LIST = <?php echo json_encode($clients, JSON_UNESCAPED_SLASHES); ?>;
</script>
<!-- Socket.IO client -->
<script src="socket.io/socket.io.js"></script>
<!-- Custom Redis logic (see below) -->
<script src="src/redis-server.js"></script>
<script>
/* Toggle help panel unchanged from the original */
document.getElementById('helpToggle').addEventListener('click', function () {
const help = document.getElementById('helpText');
help.style.display = (help.style.display === 'none' || help.style.display === '') ? 'block' : 'none';
});
</script>
</body>
</html>

View File

@ -1,36 +0,0 @@
/* --------------------------------------------------
1. Expose the API URL (identical to PHPs $apiUrl)
-------------------------------------------------- */
const API_URL = 'http://<?= h($api_bind_ip) ?>:<?= h($customApiPort) ?>/php_summary';
/* --------------------------------------------------
2. Build the endpoint list
-------------------------------------------------- */
document.addEventListener('DOMContentLoaded', () => {
const listEl = document.getElementById('endpointList');
const urlParam = new URLSearchParams(window.location.search);
const current = urlParam.get('host'); // e.g. "MC-CM3588"
fetch(API_URL)
.then(r => r.json())
.then(hosts => {
hosts.forEach(hostObj => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = '?host=' + encodeURIComponent(hostObj.hostname);
a.textContent = hostObj.hostname;
if (hostObj.hostname === current) a.classList.add('active');
li.appendChild(a);
listEl.appendChild(li);
});
})
.catch(err => {
console.error('Failed to load endpoint list:', err);
const li = document.createElement('li');
li.textContent = 'Unable to load endpoints';
listEl.appendChild(li);
});
});

View File

@ -1,177 +0,0 @@
/* ------------------------------------------------------------
1. Socket-IO connection & helper functions (unchanged)
------------------------------------------------------------ */
const socket = io();
socket.on('client_summary', renderStatsTable);
socket.on('connect_error', err => {
safeSetText('client_summary', `Could not connect to server - ${err.message}`);
});
socket.on('reconnect', attempt => {
safeSetText('client_summary', `Re-connected (attempt ${attempt})`);
});
function safeSetText(id, txt) {
const el = document.getElementById(id);
if (el) el.textContent = txt;
}
/* ------------------------------------------------------------
2. Render the table for the *selected* host
------------------------------------------------------------ */
function renderStatsTable(raw) {
// Raw may be a string (from Redis) or already parsed by socket.io
let payload;
if (typeof raw === 'string') {
try {
payload = JSON.parse(raw);
} catch (e) {
safeSetText('client_summary', 'Invalid data received');
return;
}
} else {
payload = raw;
}
if (!Array.isArray(payload) || !payload.length) {
safeSetText('client_summary', 'No data available');
return;
}
/* ---------------------------------------------
2a. Determine the hostname to display
--------------------------------------------- */
const urlParams = new URLSearchParams(window.location.search);
const selectedHost = urlParams.get('host');
/* ---------------------------------------------
2b. Find the host object in the payload
--------------------------------------------- */
const hostObj =
payload.find(item => item.hostname === selectedHost) || payload[0];
/* ---------------------------------------------
2c. Extract the Redis data for that host
--------------------------------------------- */
const hostData = hostObj && Array.isArray(hostObj.redis_data)
? hostObj.redis_data
: [];
/* ---------------------------------------------
2d. Pass the host-specific data to the generic renderer
--------------------------------------------- */
renderGenericTable('host_metrics', hostData, 'No Stats available');
}
/* ------------------------------------------------------------
3. Table rendering - unchanged from original
------------------------------------------------------------ */
function renderGenericTable(containerId, data, emptyMsg) {
const container = document.getElementById(containerId);
if (!Array.isArray(data) || !data.length) {
container.textContent = emptyMsg;
return;
}
// Merge rows by source name
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);
}
/* ------------------------------------------------------------
4. Merge rows by source name
------------------------------------------------------------ */
function mergeRowsByName(data) {
const groups = {}; // { source: { Metric: [], Data: [] } }
data.forEach(row => {
const source = row.Source;
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,
Metric: grp.Metric,
Data: grp.Data,
});
});
return merged;
}
/* ------------------------------------------------------------
5. Order rows - put “System”, “CPU”, “RAM” first
------------------------------------------------------------ */
function orderRows(rows) {
const priority = ['System', 'CPU', 'RAM'];
const priorityMap = {};
priority.forEach((src, idx) => {
priorityMap[src] = idx;
});
return [...rows].sort((a, b) => {
const aIdx = priorityMap.hasOwnProperty(a.Source) ? priorityMap[a.Source] : Infinity;
const bIdx = priorityMap.hasOwnProperty(b.Source) ? priorityMap[b.Source] : Infinity;
return aIdx - bIdx;
});
}
/* ------------------------------------------------------------
6. Build an HTML table from an array of objects
------------------------------------------------------------ */
function buildTable(data) {
const cols = ['Source', 'Metric', 'Data'];
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)) {
val.forEach((v, idx) => {
td.id = 'host_metrics_column';
const span = document.createElement('span');
span.textContent = v;
td.appendChild(span);
if (idx < val.length - 1) td.appendChild(document.createElement('br'));
});
} else {
td.textContent = val !== undefined ? val : '';
}
});
});
return table;
}

View File

@ -1,18 +0,0 @@
# Use an official Node runtime
FROM node:20-alpine
# Create app directory
WORKDIR /usr/src/app
# Install dependencies
COPY package.json .
RUN npm install --only=production
# Copy app source
COPY . .
# Expose the port that the app listens on
EXPOSE 3000
# Start the server
CMD ["node", "server.js"]