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

@ -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;
}