feat: restore monitoring widget + add sami-files template
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled

- Recreate status/js/monitoring-widgets.js with robust services count
  (reads from window.APPS, #cards DOM, then live fetch as fallback)
- Add sami-files service to data/services.json (Sami Files card)
- Add sami-files template to app-templates.js under 'Files' category
  with full systemd deployment docs and Caddy snippet
- Bundle monitoring-widgets.js into init.js
This commit is contained in:
Hermes
2026-06-18 18:52:48 -07:00
parent 9ab947a394
commit 7f0d43943c
6 changed files with 526 additions and 237 deletions
+9 -171
View File
@@ -1,13 +1,9 @@
const express = require('express');
const fsp = require('fs').promises;
const path = require('path');
const fs = require('fs');
const { success } = require('../response-helpers');
const fs = require('fs');
const path = require('path');
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
const DEFAULT_MAX_STORAGE_BYTES = process.env.BACKUP_MAX_STORAGE_BYTES
? parseInt(process.env.BACKUP_MAX_STORAGE_BYTES, 10)
: 0;
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, 'backups');
/**
* Backups routes factory
@@ -45,7 +41,6 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
runImmediately: backup.runImmediately || false,
destination: backup.destination || 'local',
destinationPath: backup.destinationPath || DEFAULT_BACKUP_DIR,
maxStorageBytes: backup.maxStorageBytes || null,
lastRun: lastRun ? lastRun.toISOString() : null,
nextRun: nextRun ? nextRun.toISOString() : null,
lastBackupId: appHistory.length > 0 ? appHistory[0].id : null
@@ -57,8 +52,8 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
// Create or update a scheduled backup for an app
router.post('/backups/schedule', premiumGating, asyncHandler(async (req, res) => {
const { appId, enabled, schedule, retention, runImmediately, destination, destinationPath, maxStorageBytes } = req.body;
const { appId, enabled, schedule, retention, runImmediately, destination, destinationPath } = req.body;
if (!appId) {
const { ValidationError } = require('../errors');
throw new ValidationError('appId is required');
@@ -66,12 +61,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
const config = backupManager.getConfig();
if (!config.backups) config.backups = {};
// Parse maxStorageBytes if provided as string (e.g. "10GB")
const parsedMaxStorage = maxStorageBytes
? (typeof maxStorageBytes === 'string' ? parseStorageSize(maxStorageBytes) : maxStorageBytes)
: null;
// Build the backup config for this app
const backupConfig = {
enabled: enabled !== undefined ? enabled : true,
@@ -81,8 +71,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
destination: destination || 'local',
destinationPath: destinationPath || DEFAULT_BACKUP_DIR,
include: ['all'],
destinations: [{ type: destination || 'local', path: destinationPath || DEFAULT_BACKUP_DIR }],
maxStorageBytes: parsedMaxStorage
destinations: [{ type: destination || 'local', path: destinationPath || DEFAULT_BACKUP_DIR }]
};
config.backups[appId] = backupConfig;
@@ -501,39 +490,6 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
success(res, { history });
}, 'backups-history'));
// Get storage info for backups destination
router.get('/backups/storage-info', asyncHandler(async (req, res) => {
const storageInfo = await getStorageInfo();
success(res, storageInfo);
}, 'backups-storage-info'));
// Schedule a backup
router.post('/backups/schedule', asyncHandler(async (req, res) => {
const { name, schedule, maxStorageBytes, ...backupConfig } = req.body;
if (!name || !schedule) {
return res.status(400).json({ error: 'name and schedule are required' });
}
const config = backupManager.getConfig();
// Store maxStorageBytes in the backup config (converted to bytes)
const maxBytes = typeof maxStorageBytes === 'number' && maxStorageBytes > 0
? maxStorageBytes
: (typeof maxStorageBytes === 'string' ? parseStorageSize(maxStorageBytes) : 0);
config.backups[name] = {
...backupConfig,
enabled: true,
schedule,
maxStorageBytes: maxBytes,
destinations: backupConfig.destinations || [{ type: 'local' }]
};
backupManager.updateConfig(config);
success(res, { message: `Backup '${name}' scheduled`, maxStorageBytes: maxBytes });
}, 'backups-schedule'));
// Restore from backup
router.post('/backups/restore/:backupId', asyncHandler(async (req, res) => {
const result = await backupManager.restoreBackup(req.params.backupId, req.body);
@@ -660,7 +616,7 @@ module.exports = function({ backupManager, licenseManager, asyncHandler }) {
*/
function calculateNextRun(lastRun, schedule) {
if (!lastRun) return null;
const intervals = {
'hourly': 60 * 60 * 1000,
'daily': 24 * 60 * 60 * 1000,
@@ -669,7 +625,7 @@ function calculateNextRun(lastRun, schedule) {
};
const baseInterval = intervals[schedule];
if (baseInterval) {
return new Date(lastRun.getTime() + baseInterval);
}
@@ -697,121 +653,3 @@ function formatBytes(bytes) {
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
/**
* Get storage information for the backup directory
*/
async function getStorageInfo() {
const result = {
destination: DEFAULT_BACKUP_DIR,
maxStorageBytes: DEFAULT_MAX_STORAGE_BYTES,
usedBytes: 0,
availableBytes: 0,
usagePercent: 0,
backupCount: 0,
oldestBackup: null,
newestBackup: null
};
try {
// Get disk space info
const diskSpace = await getDiskSpaceInfo(DEFAULT_BACKUP_DIR);
result.availableBytes = diskSpace.available;
// Scan for backup files
if (DEFAULT_MAX_STORAGE_BYTES > 0) {
result.maxStorageBytes = DEFAULT_MAX_STORAGE_BYTES;
} else {
result.maxStorageBytes = diskSpace.total || 0;
}
let totalSize = 0;
let oldestTime = null;
let newestTime = null;
try {
const entries = await fsp.readdir(DEFAULT_BACKUP_DIR);
for (const entry of entries) {
if (entry.endsWith('.backup')) {
const filePath = path.join(DEFAULT_BACKUP_DIR, entry);
try {
const stats = await fsp.stat(filePath);
totalSize += stats.size;
result.backupCount++;
const fileTime = new Date(stats.mtime);
if (!oldestTime || fileTime < oldestTime) oldestTime = fileTime;
if (!newestTime || fileTime > newestTime) newestTime = fileTime;
} catch (e) {
// Skip files we can't stat
}
}
}
} catch (e) {
// Backup directory might not exist yet
}
result.usedBytes = totalSize;
result.oldestBackup = oldestTime ? oldestTime.toISOString() : null;
result.newestBackup = newestTime ? newestTime.toISOString() : null;
// Calculate available (total limit - used), or from disk space if no limit set
if (result.maxStorageBytes > 0) {
result.availableBytes = Math.max(0, result.maxStorageBytes - totalSize);
result.usagePercent = parseFloat(((totalSize / result.maxStorageBytes) * 100).toFixed(2));
} else if (diskSpace.total) {
result.availableBytes = diskSpace.available;
result.usagePercent = diskSpace.total > 0
? parseFloat((((diskSpace.total - diskSpace.available) / diskSpace.total) * 100).toFixed(2))
: 0;
}
} catch (error) {
console.error('[BackupsRouter] Error getting storage info:', error.message);
}
return result;
}
/**
* Get disk space info (filesystem-agnostic)
*/
async function getDiskSpaceInfo(dirPath) {
try {
const diskInfo = await fsp.statfs(dirPath);
return {
total: diskInfo.blocks * diskInfo.bsize,
available: diskInfo.bfree * diskInfo.bsize,
used: (diskInfo.blocks - diskInfo.bfree) * diskInfo.bsize
};
} catch (error) {
// Directory might not exist or be accessible
return { total: 0, available: 0, used: 0 };
}
}
/**
* Parse storage size string like "10GB" to bytes
*/
function parseStorageSize(sizeStr) {
if (!sizeStr || typeof sizeStr === 'number') return sizeStr || 0;
const match = String(sizeStr).match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB|K|M|G|T)?$/i);
if (!match) return 0;
const value = parseFloat(match[1]);
const unit = (match[2] || 'B').toUpperCase();
const multipliers = {
'B': 1,
'K': 1024,
'KB': 1024,
'M': 1024 * 1024,
'MB': 1024 * 1024,
'G': 1024 * 1024 * 1024,
'GB': 1024 * 1024 * 1024,
'T': 1024 * 1024 * 1024 * 1024,
'TB': 1024 * 1024 * 1024 * 1024
};
return Math.floor(value * (multipliers[unit] || 1));
}