Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afcccf811e | ||
|
|
0aa7244cf4 | ||
|
|
1d8919532b | ||
|
|
ea9bdf9598 | ||
|
|
c52016d727 | ||
|
|
588188edb5 |
@@ -1 +1 @@
|
|||||||
dev
|
1.8.0
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "dashcaddy-api",
|
"name": "dashcaddy-api",
|
||||||
"version": "1.6.0",
|
"version": "1.8.0",
|
||||||
"description": "DashCaddy API server - Dashboard backend for Docker, Caddy & DNS management",
|
"description": "DashCaddy API server - Dashboard backend for Docker, Caddy & DNS management",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -10,9 +10,10 @@ const { success } = require('../response-helpers');
|
|||||||
* @param {Object} deps.docker - Docker client wrapper (client, pull methods)
|
* @param {Object} deps.docker - Docker client wrapper (client, pull methods)
|
||||||
* @param {Object} deps.log - Logger instance
|
* @param {Object} deps.log - Logger instance
|
||||||
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||||
|
* @param {Object} deps.workflowEngine - WorkflowEngine instance (optional)
|
||||||
* @returns {express.Router}
|
* @returns {express.Router}
|
||||||
*/
|
*/
|
||||||
module.exports = function({ docker, log, asyncHandler }) {
|
module.exports = function({ docker, log, asyncHandler, workflowEngine }) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// Helper: verify container exists before operating on it
|
// Helper: verify container exists before operating on it
|
||||||
@@ -66,6 +67,11 @@ module.exports = function({ docker, log, asyncHandler }) {
|
|||||||
log.info('docker', `Pulling latest image: ${imageName}`);
|
log.info('docker', `Pulling latest image: ${imageName}`);
|
||||||
await docker.pull(imageName);
|
await docker.pull(imageName);
|
||||||
|
|
||||||
|
// Trigger pre-update workflow (backup before update)
|
||||||
|
if (workflowEngine) {
|
||||||
|
try { await workflowEngine.triggerEvent('pre-update', { containerId: containerId, containerName, imageName }); } catch (w) { log.warn('workflow', 'pre-update trigger failed: ' + w.message); }
|
||||||
|
}
|
||||||
|
|
||||||
// Get current container config for recreation
|
// Get current container config for recreation
|
||||||
const hostConfig = containerInfo.HostConfig;
|
const hostConfig = containerInfo.HostConfig;
|
||||||
const config = {
|
const config = {
|
||||||
@@ -138,6 +144,11 @@ module.exports = function({ docker, log, asyncHandler }) {
|
|||||||
message: `Container ${containerName} updated successfully`,
|
message: `Container ${containerName} updated successfully`,
|
||||||
newContainerId: newContainerInfo.Id
|
newContainerId: newContainerInfo.Id
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Trigger post-update workflow
|
||||||
|
if (workflowEngine) {
|
||||||
|
try { await workflowEngine.triggerEvent('post-update', { containerId: containerId, containerName, imageName, newContainerId: newContainerInfo.Id }); } catch (w) { log.warn('workflow', 'post-update trigger failed: ' + w.message); }
|
||||||
|
}
|
||||||
}, 'container-update'));
|
}, 'container-update'));
|
||||||
|
|
||||||
// Check for available updates (compares local and remote image digests)
|
// Check for available updates (compares local and remote image digests)
|
||||||
|
|||||||
@@ -372,7 +372,7 @@ module.exports = function({
|
|||||||
// Add a new service
|
// Add a new service
|
||||||
router.post('/services', asyncHandler(async (req, res) => {
|
router.post('/services', asyncHandler(async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id, name, logo } = req.body;
|
const { id, name, logo, category, containerId, port, ip, tailscaleOnly } = req.body;
|
||||||
|
|
||||||
if (!id || !name) {
|
if (!id || !name) {
|
||||||
throw new ValidationError('id and name are required');
|
throw new ValidationError('id and name are required');
|
||||||
@@ -391,7 +391,14 @@ module.exports = function({
|
|||||||
throw new ConflictError(`Service "${id}" already exists`, id);
|
throw new ConflictError(`Service "${id}" already exists`, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
services.push({ id, name, logo: logo || `/assets/${id}.png` });
|
const newService = { id, name, logo: logo || `/assets/${id}.png` };
|
||||||
|
// Persist optional metadata fields if provided
|
||||||
|
if (category) newService.category = category;
|
||||||
|
if (containerId) newService.containerId = containerId;
|
||||||
|
if (port) newService.port = port;
|
||||||
|
if (ip) newService.ip = ip;
|
||||||
|
if (typeof tailscaleOnly === 'boolean') newService.tailscaleOnly = tailscaleOnly;
|
||||||
|
services.push(newService);
|
||||||
return services;
|
return services;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -542,6 +549,8 @@ module.exports = function({
|
|||||||
};
|
};
|
||||||
if (name) services[serviceIndex].name = name;
|
if (name) services[serviceIndex].name = name;
|
||||||
if (logo) services[serviceIndex].logo = logo;
|
if (logo) services[serviceIndex].logo = logo;
|
||||||
|
// Allow category update via update endpoint too (optional body field)
|
||||||
|
if (req.body.category !== undefined) services[serviceIndex].category = req.body.category || undefined;
|
||||||
results.services = 'updated';
|
results.services = 'updated';
|
||||||
} else {
|
} else {
|
||||||
results.services = 'not found';
|
results.services = 'not found';
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# DashCaddy Host-Side Updater
|
# DashCaddy Host-Side Updater
|
||||||
# Triggered by systemd path unit when the container writes trigger.json.
|
# Triggered by systemd path unit when the container writes trigger.json.
|
||||||
# Reads the trigger, backs up current API, copies new files, rebuilds container.
|
# Reads the trigger, backs up current API + data/, copies new files, rebuilds container.
|
||||||
# Writes result.json so the new container knows the outcome.
|
# Writes result.json so the new container knows the outcome.
|
||||||
#
|
#
|
||||||
# This runs on the HOST, outside the container.
|
# This runs on the HOST, outside the container.
|
||||||
@@ -16,6 +16,10 @@ readonly CONTAINER_NAME="dashcaddy-api"
|
|||||||
readonly MAX_BACKUPS=3
|
readonly MAX_BACKUPS=3
|
||||||
readonly HEALTH_TIMEOUT=60
|
readonly HEALTH_TIMEOUT=60
|
||||||
|
|
||||||
|
# Data directory backup — stored alongside code backups so everything rolls back together
|
||||||
|
readonly DATA_SOURCE_DIR="/opt/dashcaddy/dashcaddy-api/data"
|
||||||
|
readonly DATA_BACKUP_PREFIX="data-backup"
|
||||||
|
|
||||||
log() { echo "[dashcaddy-update] $(date '+%Y-%m-%d %H:%M:%S') $*"; }
|
log() { echo "[dashcaddy-update] $(date '+%Y-%m-%d %H:%M:%S') $*"; }
|
||||||
|
|
||||||
write_result() {
|
write_result() {
|
||||||
@@ -56,6 +60,34 @@ cleanup_old_backups() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ── Data backup (rsync for efficiency + permissions) ──────────────────────────
|
||||||
|
backup_data_dir() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
if [[ -d "$DATA_SOURCE_DIR" ]]; then
|
||||||
|
log "Backing up data/ to ${backup_dir}/${DATA_BACKUP_PREFIX}/"
|
||||||
|
mkdir -p "${backup_dir}/${DATA_BACKUP_PREFIX}"
|
||||||
|
rsync -a --delete "$DATA_SOURCE_DIR/" "${backup_dir}/${DATA_BACKUP_PREFIX}/" 2>/dev/null \
|
||||||
|
|| cp -a "$DATA_SOURCE_DIR" "${backup_dir}/${DATA_BACKUP_PREFIX}"
|
||||||
|
log "Data backup complete ($(du -sh "${backup_dir}/${DATA_BACKUP_PREFIX}" 2>/dev/null | cut -f1))"
|
||||||
|
else
|
||||||
|
log "WARNING: Data source dir $DATA_SOURCE_DIR not found — skipping data backup"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Data restore ──────────────────────────────────────────────────────────────
|
||||||
|
restore_data_dir() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
local data_backup="${backup_dir}/${DATA_BACKUP_PREFIX}"
|
||||||
|
if [[ -d "$data_backup" ]]; then
|
||||||
|
log "Restoring data/ from backup..."
|
||||||
|
rsync -a --delete "$data_backup/" "$DATA_SOURCE_DIR/" 2>/dev/null \
|
||||||
|
|| cp -a "$data_backup" "$DATA_SOURCE_DIR"
|
||||||
|
log "Data restored successfully"
|
||||||
|
else
|
||||||
|
log "WARNING: No data backup found at ${data_backup} — data/ not restored"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
wait_for_health() {
|
wait_for_health() {
|
||||||
local port="${1:-3001}"
|
local port="${1:-3001}"
|
||||||
local timeout="$HEALTH_TIMEOUT"
|
local timeout="$HEALTH_TIMEOUT"
|
||||||
@@ -75,6 +107,59 @@ wait_for_health() {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ── Shared rollback: restore code + data ────────────────────────────────────
|
||||||
|
rollback_restore() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
log "Rolling back: restoring code files..."
|
||||||
|
for item in "$backup_dir"/*.js "$backup_dir"/package.json "$backup_dir"/package-lock.json "$backup_dir"/Dockerfile "$backup_dir"/openapi.yaml "$backup_dir"/VERSION; do
|
||||||
|
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
if [[ -d "$backup_dir/routes" ]]; then
|
||||||
|
rm -rf "$api_source_dir/routes"
|
||||||
|
cp -rf "$backup_dir/routes" "$api_source_dir/routes"
|
||||||
|
fi
|
||||||
|
if [[ -d "$backup_dir/src" ]]; then
|
||||||
|
rm -rf "$api_source_dir/src"
|
||||||
|
cp -rf "$backup_dir/src" "$api_source_dir/src"
|
||||||
|
fi
|
||||||
|
restore_data_dir "$backup_dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Shared container restart (preserves SERVICES_FILE env var) ───────────────
|
||||||
|
# Uses rm + run so new env vars (e.g. SERVICES_FILE) take effect.
|
||||||
|
# If docker-compose is not configured, falls back to docker start.
|
||||||
|
restart_container() {
|
||||||
|
local image="$1"
|
||||||
|
log "Restarting container (rm + run to pick up env vars)..."
|
||||||
|
# Stop and remove existing container so new env var is applied
|
||||||
|
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
|
||||||
|
|
||||||
|
# Re-create with same volumes and the SERVICES_FILE env var
|
||||||
|
docker run -d --restart unless-stopped --name "$CONTAINER_NAME" \
|
||||||
|
-p 127.0.0.1:3001:3001 \
|
||||||
|
-v /opt/dashcaddy/dashcaddy-api/data:/app/data \
|
||||||
|
-e SERVICES_FILE=/app/data/services.json \
|
||||||
|
"$image"
|
||||||
|
log "Container restarted with fresh env"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Code-only restore (used after failed build when data hasn't changed yet) ──
|
||||||
|
code_restore() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
log "Restoring code files..."
|
||||||
|
for item in "$backup_dir"/*.js "$backup_dir"/package.json "$backup_dir"/package-lock.json "$backup_dir"/Dockerfile "$backup_dir"/openapi.yaml "$backup_dir"/VERSION; do
|
||||||
|
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
if [[ -d "$backup_dir/routes" ]]; then
|
||||||
|
rm -rf "$api_source_dir/routes"
|
||||||
|
cp -rf "$backup_dir/routes" "$api_source_dir/routes"
|
||||||
|
fi
|
||||||
|
if [[ -d "$backup_dir/src" ]]; then
|
||||||
|
rm -rf "$api_source_dir/src"
|
||||||
|
cp -rf "$backup_dir/src" "$api_source_dir/src"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
local start_time
|
local start_time
|
||||||
start_time=$(date +%s)
|
start_time=$(date +%s)
|
||||||
@@ -94,45 +179,69 @@ main() {
|
|||||||
staging_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['stagingDir'])")
|
staging_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['stagingDir'])")
|
||||||
api_source_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['apiSourceDir'])")
|
api_source_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['apiSourceDir'])")
|
||||||
commit=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('commit') or '')")
|
commit=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('commit') or '')")
|
||||||
# Frontend paths — optional (older self-updaters don't write these). When
|
|
||||||
# present, this script also syncs the dashboard files (Caddy serves them
|
|
||||||
# directly from the host; the container path /app/dashboard isn't mounted).
|
|
||||||
frontend_staging_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('frontendStagingDir') or '')")
|
frontend_staging_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('frontendStagingDir') or '')")
|
||||||
frontend_target_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('frontendTargetDir') or '')")
|
frontend_target_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('frontendTargetDir') or '')")
|
||||||
|
# Handle action=rollback (no new version to deploy)
|
||||||
|
local to_version="${version}"
|
||||||
|
|
||||||
log "=== ${action^^}: v${from_version} -> v${version} ==="
|
log "=== ${action^^}: v${from_version} -> v${to_version} ==="
|
||||||
log "Staging: ${staging_dir}"
|
log "Staging: ${staging_dir}"
|
||||||
log "API source: ${api_source_dir}"
|
log "API source: ${api_source_dir}"
|
||||||
|
|
||||||
# Consume the trigger immediately so we don't re-process on failure
|
# Consume the trigger immediately so we don't re-process on failure
|
||||||
mv "$TRIGGER_FILE" "${TRIGGER_FILE}.processing"
|
mv "$TRIGGER_FILE" "${TRIGGER_FILE}.processing"
|
||||||
|
|
||||||
# 2. Validate staging directory
|
# ── Handle rollback ────────────────────────────────────────────────────────
|
||||||
if [[ ! -d "$staging_dir" ]]; then
|
if [[ "$action" == "rollback" ]]; then
|
||||||
log "ERROR: Staging directory not found: ${staging_dir}"
|
local backup_dir="${BACKUPS_DIR}/${version}"
|
||||||
write_result "false" "$version" "$(( $(date +%s) - start_time ))" "Staging directory not found"
|
if [[ ! -d "$backup_dir" ]]; then
|
||||||
|
log "ERROR: No backup found for version ${version}"
|
||||||
|
write_result "false" "$version" "$(( $(date +%s) - start_time ))" "No backup found for version ${version}"
|
||||||
rm -f "${TRIGGER_FILE}.processing"
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 3. Backup current API files
|
log "Performing rollback to v${version}..."
|
||||||
|
rollback_restore "$backup_dir"
|
||||||
|
|
||||||
|
# Rebuild old code
|
||||||
|
log "Rebuilding container..."
|
||||||
|
cd "$api_source_dir"
|
||||||
|
docker build -t dashcaddy-dashcaddy-api:latest . 2>&1 | tail -1 || true
|
||||||
|
|
||||||
|
restart_container "dashcaddy-dashcaddy-api:latest"
|
||||||
|
wait_for_health || log "WARNING: Health check failed after rollback"
|
||||||
|
|
||||||
|
write_result "true" "$version" "$(( $(date +%s) - start_time ))"
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
log "=== Rollback complete ==="
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Handle update ───────────────────────────────────────────────────────────
|
||||||
|
if [[ ! -d "$staging_dir" ]]; then
|
||||||
|
log "ERROR: Staging directory not found: ${staging_dir}"
|
||||||
|
write_result "false" "$to_version" "$(( $(date +%s) - start_time ))" "Staging directory not found"
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. Backup current API code + data/
|
||||||
local backup_dir="${BACKUPS_DIR}/${from_version}"
|
local backup_dir="${BACKUPS_DIR}/${from_version}"
|
||||||
mkdir -p "$backup_dir"
|
mkdir -p "$backup_dir"
|
||||||
log "Backing up current API files to ${backup_dir}"
|
log "Backing up current API files to ${backup_dir}"
|
||||||
|
|
||||||
# Copy all JS files, package.json, Dockerfile, and tracked subdirs
|
|
||||||
for item in "$api_source_dir"/*.js "$api_source_dir"/package.json "$api_source_dir"/package-lock.json "$api_source_dir"/Dockerfile "$api_source_dir"/openapi.yaml "$api_source_dir"/VERSION; do
|
for item in "$api_source_dir"/*.js "$api_source_dir"/package.json "$api_source_dir"/package-lock.json "$api_source_dir"/Dockerfile "$api_source_dir"/openapi.yaml "$api_source_dir"/VERSION; do
|
||||||
[[ -f "$item" ]] && cp -f "$item" "$backup_dir/" 2>/dev/null || true
|
[[ -f "$item" ]] && cp -f "$item" "$backup_dir/" 2>/dev/null || true
|
||||||
done
|
done
|
||||||
[[ -d "$api_source_dir/routes" ]] && cp -rf "$api_source_dir/routes" "$backup_dir/"
|
[[ -d "$api_source_dir/routes" ]] && cp -rf "$api_source_dir/routes" "$backup_dir/"
|
||||||
[[ -d "$api_source_dir/src" ]] && cp -rf "$api_source_dir/src" "$backup_dir/"
|
[[ -d "$api_source_dir/src" ]] && cp -rf "$api_source_dir/src" "$backup_dir/"
|
||||||
# VERSION (commit hash) was copied from api_source_dir above; preserve as-is
|
|
||||||
# so a rollback restores the original commit marker. The version *string* is
|
# Backup data/ directory (services.json, config.json, credentials, etc.)
|
||||||
# already encoded in the backup dir name (${from_version}).
|
backup_data_dir "$backup_dir"
|
||||||
|
|
||||||
cleanup_old_backups
|
cleanup_old_backups
|
||||||
|
|
||||||
# 4. Copy new files from staging to API source
|
# 3. Copy new files from staging to API source
|
||||||
log "Deploying new API files..."
|
log "Deploying new API files..."
|
||||||
for item in "$staging_dir"/*.js "$staging_dir"/package.json "$staging_dir"/package-lock.json "$staging_dir"/Dockerfile "$staging_dir"/openapi.yaml "$staging_dir"/VERSION; do
|
for item in "$staging_dir"/*.js "$staging_dir"/package.json "$staging_dir"/package-lock.json "$staging_dir"/Dockerfile "$staging_dir"/openapi.yaml "$staging_dir"/VERSION; do
|
||||||
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
||||||
@@ -145,19 +254,11 @@ main() {
|
|||||||
rm -rf "$api_source_dir/src"
|
rm -rf "$api_source_dir/src"
|
||||||
cp -rf "$staging_dir/src" "$api_source_dir/src"
|
cp -rf "$staging_dir/src" "$api_source_dir/src"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Belt-and-suspenders: always write the commit from trigger.json to VERSION,
|
|
||||||
# even if the tarball didn't include one. The container's self-updater uses
|
|
||||||
# this to detect the "same version, different commit" case.
|
|
||||||
if [[ -n "$commit" ]]; then
|
if [[ -n "$commit" ]]; then
|
||||||
echo "$commit" > "$api_source_dir/VERSION"
|
echo "$commit" > "$api_source_dir/VERSION"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 4b. Sync frontend. Caddy serves the dashboard directly from the host
|
# 3b. Sync frontend
|
||||||
# filesystem; the container-side copy in older self-updater.js builds wrote
|
|
||||||
# to /app/dashboard which isn't always mounted, so the real sync happens
|
|
||||||
# here. Trigger fields take precedence; if absent (older self-updater),
|
|
||||||
# fall back to: staging dir's sibling status/ + first existing known target.
|
|
||||||
if [[ -z "$frontend_staging_dir" ]]; then
|
if [[ -z "$frontend_staging_dir" ]]; then
|
||||||
parent_staging=$(dirname "$staging_dir")
|
parent_staging=$(dirname "$staging_dir")
|
||||||
[[ -d "$parent_staging/status" ]] && frontend_staging_dir="$parent_staging/status"
|
[[ -d "$parent_staging/status" ]] && frontend_staging_dir="$parent_staging/status"
|
||||||
@@ -175,107 +276,55 @@ main() {
|
|||||||
for sub in dist css vendor js; do
|
for sub in dist css vendor js; do
|
||||||
if [[ -d "$frontend_staging_dir/$sub" ]]; then
|
if [[ -d "$frontend_staging_dir/$sub" ]]; then
|
||||||
mkdir -p "$frontend_target_dir/$sub"
|
mkdir -p "$frontend_target_dir/$sub"
|
||||||
cp -rf "$frontend_staging_dir/$sub"/* "$frontend_target_dir/$sub/" 2>/dev/null || true
|
cp -rf "$frontend_staging_dir/$sub/"* "$frontend_target_dir/$sub/" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
# assets/ is mounted into the container; usually already in sync via bind
|
|
||||||
# mount, but if a release ships new assets we want them on disk too.
|
|
||||||
if [[ -d "$frontend_staging_dir/assets" ]]; then
|
if [[ -d "$frontend_staging_dir/assets" ]]; then
|
||||||
mkdir -p "$frontend_target_dir/assets"
|
mkdir -p "$frontend_target_dir/assets"
|
||||||
cp -rf "$frontend_staging_dir/assets"/* "$frontend_target_dir/assets/" 2>/dev/null || true
|
cp -rf "$frontend_staging_dir/assets/"* "$frontend_target_dir/assets/" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 5. Rebuild container
|
# 4. Rebuild container
|
||||||
log "Rebuilding container..."
|
log "Rebuilding container..."
|
||||||
cd "$api_source_dir"
|
cd "$api_source_dir"
|
||||||
|
|
||||||
local build_ok=false
|
local build_ok=false
|
||||||
if docker compose build --quiet 2>&1; then
|
local image_tag="dashcaddy-dashcaddy-api:latest"
|
||||||
build_ok=true
|
|
||||||
elif docker-compose build --quiet 2>&1; then
|
if docker build -t "$image_tag" . 2>&1; then
|
||||||
build_ok=true
|
build_ok=true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$build_ok" != "true" ]]; then
|
if [[ "$build_ok" != "true" ]]; then
|
||||||
log "ERROR: Docker build failed — rolling back"
|
log "ERROR: Docker build failed — rolling back code + data"
|
||||||
|
code_restore "$backup_dir"
|
||||||
# Restore backup
|
docker build -t "$image_tag" . 2>&1 | tail -3 || true
|
||||||
for item in "$backup_dir"/*.js "$backup_dir"/package.json "$backup_dir"/package-lock.json "$backup_dir"/Dockerfile "$backup_dir"/openapi.yaml "$backup_dir"/VERSION; do
|
restart_container "$image_tag"
|
||||||
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
wait_for_health || true
|
||||||
done
|
write_result "false" "$to_version" "$(( $(date +%s) - start_time ))" "Docker build failed"
|
||||||
if [[ -d "$backup_dir/routes" ]]; then
|
|
||||||
rm -rf "$api_source_dir/routes"
|
|
||||||
cp -rf "$backup_dir/routes" "$api_source_dir/routes"
|
|
||||||
fi
|
|
||||||
if [[ -d "$backup_dir/src" ]]; then
|
|
||||||
rm -rf "$api_source_dir/src"
|
|
||||||
cp -rf "$backup_dir/src" "$api_source_dir/src"
|
|
||||||
fi
|
|
||||||
|
|
||||||
write_result "false" "$version" "$(( $(date +%s) - start_time ))" "Docker build failed"
|
|
||||||
rm -f "${TRIGGER_FILE}.processing"
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 6. Restart container
|
# 5. Restart container (rm + run so new env vars take effect)
|
||||||
log "Restarting container..."
|
restart_container "$image_tag"
|
||||||
if docker compose up -d 2>&1 || docker-compose up -d 2>&1; then
|
|
||||||
log "Container restarted"
|
|
||||||
else
|
|
||||||
log "ERROR: Container restart failed — rolling back"
|
|
||||||
|
|
||||||
# Restore backup
|
# 6. Health check
|
||||||
for item in "$backup_dir"/*.js "$backup_dir"/package.json "$backup_dir"/package-lock.json "$backup_dir"/Dockerfile "$backup_dir"/openapi.yaml "$backup_dir"/VERSION; do
|
|
||||||
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
|
||||||
done
|
|
||||||
if [[ -d "$backup_dir/routes" ]]; then
|
|
||||||
rm -rf "$api_source_dir/routes"
|
|
||||||
cp -rf "$backup_dir/routes" "$api_source_dir/routes"
|
|
||||||
fi
|
|
||||||
if [[ -d "$backup_dir/src" ]]; then
|
|
||||||
rm -rf "$api_source_dir/src"
|
|
||||||
cp -rf "$backup_dir/src" "$api_source_dir/src"
|
|
||||||
fi
|
|
||||||
|
|
||||||
docker compose build --quiet 2>&1 || docker-compose build --quiet 2>&1 || true
|
|
||||||
docker compose up -d 2>&1 || docker-compose up -d 2>&1 || true
|
|
||||||
|
|
||||||
write_result "false" "$version" "$(( $(date +%s) - start_time ))" "Container restart failed"
|
|
||||||
rm -f "${TRIGGER_FILE}.processing"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 7. Health check
|
|
||||||
if wait_for_health; then
|
if wait_for_health; then
|
||||||
local duration=$(( $(date +%s) - start_time ))
|
local duration=$(( $(date +%s) - start_time ))
|
||||||
log "=== Update successful: v${version} in ${duration}s ==="
|
log "=== Update successful: v${to_version} in ${duration}s ==="
|
||||||
write_result "true" "$version" "$duration"
|
write_result "true" "$to_version" "$duration"
|
||||||
else
|
else
|
||||||
local duration=$(( $(date +%s) - start_time ))
|
local duration=$(( $(date +%s) - start_time ))
|
||||||
log "ERROR: Health check failed after update — rolling back"
|
log "ERROR: Health check failed after update — rolling back code + data"
|
||||||
|
rollback_restore "$backup_dir"
|
||||||
# Restore backup
|
docker build -t "$image_tag" . 2>&1 | tail -3 || true
|
||||||
for item in "$backup_dir"/*.js "$backup_dir"/package.json "$backup_dir"/package-lock.json "$backup_dir"/Dockerfile "$backup_dir"/openapi.yaml "$backup_dir"/VERSION; do
|
restart_container "$image_tag"
|
||||||
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
|
||||||
done
|
|
||||||
if [[ -d "$backup_dir/routes" ]]; then
|
|
||||||
rm -rf "$api_source_dir/routes"
|
|
||||||
cp -rf "$backup_dir/routes" "$api_source_dir/routes"
|
|
||||||
fi
|
|
||||||
if [[ -d "$backup_dir/src" ]]; then
|
|
||||||
rm -rf "$api_source_dir/src"
|
|
||||||
cp -rf "$backup_dir/src" "$api_source_dir/src"
|
|
||||||
fi
|
|
||||||
|
|
||||||
docker compose build --quiet 2>&1 || docker-compose build --quiet 2>&1 || true
|
|
||||||
docker compose up -d 2>&1 || docker-compose up -d 2>&1 || true
|
|
||||||
wait_for_health || log "WARNING: Rollback health check also failed"
|
wait_for_health || log "WARNING: Rollback health check also failed"
|
||||||
|
write_result "false" "$to_version" "$duration" "Health check failed after update"
|
||||||
write_result "false" "$version" "$duration" "Health check failed after update"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 8. Cleanup
|
# 7. Cleanup
|
||||||
rm -f "${TRIGGER_FILE}.processing"
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
rm -rf "${UPDATES_DIR}/staging" 2>/dev/null || true
|
rm -rf "${UPDATES_DIR}/staging" 2>/dev/null || true
|
||||||
|
|
||||||
|
|||||||
@@ -384,7 +384,8 @@ async function createApp() {
|
|||||||
apiRouter.use('/containers', containerRoutes({
|
apiRouter.use('/containers', containerRoutes({
|
||||||
docker: ctx.docker,
|
docker: ctx.docker,
|
||||||
log: ctx.log,
|
log: ctx.log,
|
||||||
asyncHandler: ctx.asyncHandler
|
asyncHandler: ctx.asyncHandler,
|
||||||
|
workflowEngine: ctx.workflowEngine
|
||||||
}));
|
}));
|
||||||
apiRouter.use(serviceRoutes({
|
apiRouter.use(serviceRoutes({
|
||||||
servicesStateManager: ctx.servicesStateManager,
|
servicesStateManager: ctx.servicesStateManager,
|
||||||
|
|||||||
Executable
+76
@@ -0,0 +1,76 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Samihost fail2ban watchdog — auto-unban whitelisted IPs and keep ignoreip list in sync.
|
||||||
|
# Deployed to /usr/local/bin/samihost-fail2ban-watchdog.sh on 194.163.161.162
|
||||||
|
# Cron: every 30 min (0,30 * * * *)
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
JAIL_LOCAL=/etc/fail2ban/jail.local
|
||||||
|
BACKUP=/etc/fail2ban/jail.local.watchdog.bak
|
||||||
|
EXPECTED_IGNOREIP="127.0.0.1/8 ::1 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 fc00::/7 fe80::/10 100.64.0.0/10 100.121.150.22 100.85.236.10 100.71.97.12 100.81.59.99 100.98.123.59 194.233.88.206 173.212.201.200 194.163.161.162"
|
||||||
|
LOG=/var/log/samihost-fail2ban-watchdog.log
|
||||||
|
TELEGRAM_LOG=/tmp/fail2ban-watchdog-last-action
|
||||||
|
|
||||||
|
ts() { date -u +"%Y-%m-%dT%H:%M:%SZ"; }
|
||||||
|
log() { echo "$(ts) $*" | tee -a "$LOG"; }
|
||||||
|
|
||||||
|
mkdir -p "$(dirname "$LOG")"
|
||||||
|
touch "$LOG"
|
||||||
|
|
||||||
|
# --- 1. Verify ignoreip line is intact and matches expected ---
|
||||||
|
CURRENT=$(grep '^ignoreip' "$JAIL_LOCAL" | sed 's/^ignoreip[[:space:]]*=[[:space:]]*//' || true)
|
||||||
|
EXPECTED_NORMALIZED=$(echo "$EXPECTED_IGNOREIP" | tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')
|
||||||
|
CURRENT_NORMALIZED=$(echo "$CURRENT" | tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')
|
||||||
|
|
||||||
|
if [ "$CURRENT_NORMALIZED" != "$EXPECTED_NORMALIZED" ]; then
|
||||||
|
log "ALERT: ignoreip line drifted. Restoring."
|
||||||
|
cp "$JAIL_LOCAL" "$BACKUP"
|
||||||
|
sed -i "s|^ignoreip = .*|ignoreip = $EXPECTED_IGNOREIP|" "$JAIL_LOCAL"
|
||||||
|
fail2ban-client reload
|
||||||
|
echo "ignoreip restored at $(ts)" > "$TELEGRAM_LOG"
|
||||||
|
log "ignoreip restored, fail2ban reloaded"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# --- 2. Unban any currently-banned IPs that match our trusted set ---
|
||||||
|
BANNED=$(fail2ban-client status sshd 2>/dev/null | awk -F: '/Banned IP list/{print $2}' | tr ' ' '\n' | grep -v '^$' || true)
|
||||||
|
UNBANNED=0
|
||||||
|
for ip in $BANNED; do
|
||||||
|
# Match against any trusted network
|
||||||
|
is_trusted=0
|
||||||
|
for net in 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10 ::1 fc00::/7 fe80::/10 100.121.150.22 100.85.236.10 100.71.97.12 100.81.59.99 100.98.123.59 194.233.88.206 173.212.201.200 194.163.161.162; do
|
||||||
|
if [[ "$net" == *"/"* ]]; then
|
||||||
|
# CIDR match (simple IPv4 only — IPv6 needs python or ipcalc, skip for now)
|
||||||
|
base="${net%/*}"
|
||||||
|
mask="${net#*/}"
|
||||||
|
if [[ "$ip" == "$base"* ]] || python3 -c "import ipaddress,sys; sys.exit(0 if ipaddress.ip_address('$ip') in ipaddress.ip_network('$net', strict=False) else 1)" 2>/dev/null; then
|
||||||
|
is_trusted=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
if [ "$ip" = "$net" ]; then
|
||||||
|
is_trusted=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ "$is_trusted" = "1" ]; then
|
||||||
|
if fail2ban-client set sshd unbanip "$ip" >/dev/null 2>&1; then
|
||||||
|
log "auto-unbanned trusted IP: $ip"
|
||||||
|
UNBANNED=$((UNBANNED+1))
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
[ "$UNBANNED" -gt 0 ] && echo "auto-unbanned $UNBANNED trusted IPs at $(ts)" > "$TELEGRAM_LOG"
|
||||||
|
|
||||||
|
# --- 3. Cap the ban count — if more than 200 are banned, mass-unban stale ones ---
|
||||||
|
TOTAL_BANNED=$(fail2ban-client status sshd 2>/dev/null | awk '/Currently banned/{print $NF}' || echo 0)
|
||||||
|
if [ "$TOTAL_BANNED" -gt 200 ]; then
|
||||||
|
log "ALERT: $TOTAL_BANNED IPs banned. Mass-unbanning all."
|
||||||
|
for ip in $BANNED; do
|
||||||
|
fail2ban-client set sshd unbanip "$ip" >/dev/null 2>&1 || true
|
||||||
|
done
|
||||||
|
echo "mass-unbanned $TOTAL_BANNED stale bans at $(ts)" > "$TELEGRAM_LOG"
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "watchdog run complete (unbanned=$UNBANNED, total_banned=$TOTAL_BANNED)"
|
||||||
@@ -72,6 +72,7 @@ const bundles = {
|
|||||||
],
|
],
|
||||||
'init.js': [
|
'init.js': [
|
||||||
JS('core', 'init.js'),
|
JS('core', 'init.js'),
|
||||||
|
JS('monitoring-widgets.js'),
|
||||||
JS('keyboard-shortcuts.js'),
|
JS('keyboard-shortcuts.js'),
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
Vendored
+114
-87
File diff suppressed because one or more lines are too long
Vendored
+307
-232
File diff suppressed because one or more lines are too long
Vendored
+129
-18
File diff suppressed because one or more lines are too long
@@ -256,6 +256,9 @@
|
|||||||
<option value="on">🟢 Online</option>
|
<option value="on">🟢 Online</option>
|
||||||
<option value="off">🔴 Offline</option>
|
<option value="off">🔴 Offline</option>
|
||||||
</select>
|
</select>
|
||||||
|
<select id="service-filter-category" style="padding: 8px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px; color: var(--fg); font-size: 0.9rem;">
|
||||||
|
<option value="all">All Categories</option>
|
||||||
|
</select>
|
||||||
<button id="batch-operations-btn" class="btn-sm" style="padding: 8px 12px;">☰ Batch Operations</button>
|
<button id="batch-operations-btn" class="btn-sm" style="padding: 8px 12px;">☰ Batch Operations</button>
|
||||||
<span id="service-filter-count" style="color: var(--muted); font-size: 0.85rem; white-space: nowrap;"></span>
|
<span id="service-filter-count" style="color: var(--muted); font-size: 0.85rem; white-space: nowrap;"></span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -41,8 +41,11 @@
|
|||||||
dismissedUpdates = new Set();
|
dismissedUpdates = new Set();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Track global update state for cross-component access
|
||||||
|
let knownUpdates = [];
|
||||||
|
|
||||||
// Fetch update data and show badges
|
// Fetch update data and show badges
|
||||||
async function refreshCardUpdates() {
|
async function refreshCardUpdates(notifyNew) {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/v1/updates/available');
|
const res = await fetch('/api/v1/updates/available');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
@@ -51,9 +54,21 @@
|
|||||||
// Clear all update badges first
|
// Clear all update badges first
|
||||||
document.querySelectorAll('.update-available-badge').forEach(el => el.classList.remove('visible'));
|
document.querySelectorAll('.update-available-badge').forEach(el => el.classList.remove('visible'));
|
||||||
|
|
||||||
if (!data.updates?.length) return;
|
const updates = data.updates || [];
|
||||||
|
knownUpdates = updates; // store globally
|
||||||
|
|
||||||
for (const upd of data.updates) {
|
// Notify if new updates appeared (periodic check with notification)
|
||||||
|
if (notifyNew && updates.length > 0) {
|
||||||
|
const prev = window._lastKnownUpdateCount || 0;
|
||||||
|
if (prev > 0 && updates.length > prev) {
|
||||||
|
showNotification(`${updates.length} container update(s) available — click Update Management to review.`, 'info');
|
||||||
|
}
|
||||||
|
window._lastKnownUpdateCount = updates.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!updates.length) return;
|
||||||
|
|
||||||
|
for (const upd of updates) {
|
||||||
// Try to match by container name to service id
|
// Try to match by container name to service id
|
||||||
const apps = window.APPS || [];
|
const apps = window.APPS || [];
|
||||||
for (const app of apps) {
|
for (const app of apps) {
|
||||||
@@ -61,17 +76,24 @@
|
|||||||
// Skip dismissed updates
|
// Skip dismissed updates
|
||||||
if (dismissedUpdates.has(app.id)) break;
|
if (dismissedUpdates.has(app.id)) break;
|
||||||
const badge = document.getElementById('update-badge-' + app.id);
|
const badge = document.getElementById('update-badge-' + app.id);
|
||||||
|
const updateBtn = document.getElementById('update-btn-' + app.id);
|
||||||
if (badge) {
|
if (badge) {
|
||||||
badge.classList.add('visible');
|
badge.classList.add('visible');
|
||||||
badge.title = `Image digest changed. Click to dismiss if already up to date.\n${upd.imageName || ''}`;
|
badge.title = `Update available — click to open Update Management.`;
|
||||||
badge.style.cursor = 'pointer';
|
badge.style.cursor = 'pointer';
|
||||||
badge.onclick = (e) => {
|
badge.onclick = (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
badge.classList.remove('visible');
|
// Open Update Management modal focused on this app
|
||||||
dismissedUpdates.add(app.id);
|
if (window.openUpdateModal) window.openUpdateModal(app.id);
|
||||||
safeSessionSet('dismissed-updates', JSON.stringify([...dismissedUpdates]));
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// Highlight update button if update is available
|
||||||
|
if (updateBtn) {
|
||||||
|
updateBtn.style.background = '#f97316';
|
||||||
|
updateBtn.style.borderColor = '#f97316';
|
||||||
|
updateBtn.style.boxShadow = '0 0 6px #f9731688';
|
||||||
|
updateBtn.title = `Update available — click to open Update Management.`;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,10 +112,10 @@
|
|||||||
refreshCardUpdates();
|
refreshCardUpdates();
|
||||||
}, 5000);
|
}, 5000);
|
||||||
|
|
||||||
// Periodic refresh every 60 seconds
|
// Periodic refresh every 60 seconds — notify on new updates detected
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
refreshCardHealth();
|
refreshCardHealth();
|
||||||
refreshCardUpdates();
|
refreshCardUpdates(true); // true = notify if new updates found
|
||||||
}, 60000);
|
}, 60000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -95,6 +95,8 @@
|
|||||||
const card = el('div', 'card');
|
const card = el('div', 'card');
|
||||||
card.setAttribute('data-app', s.id);
|
card.setAttribute('data-app', s.id);
|
||||||
card.setAttribute('data-status', 'off'); // Initial status
|
card.setAttribute('data-status', 'off'); // Initial status
|
||||||
|
if (s.containerId) card.setAttribute('data-container-id', s.containerId);
|
||||||
|
if (s.category) card.setAttribute('data-category', s.category);
|
||||||
if (s.recipeId) card.setAttribute('data-recipe-id', s.recipeId);
|
if (s.recipeId) card.setAttribute('data-recipe-id', s.recipeId);
|
||||||
|
|
||||||
const dot = el('span', 'dot bad at-bl'); dot.id = 'dot-' + s.id + '-grid'; card.appendChild(dot);
|
const dot = el('span', 'dot bad at-bl'); dot.id = 'dot-' + s.id + '-grid'; card.appendChild(dot);
|
||||||
@@ -156,6 +158,16 @@
|
|||||||
nameSpan.appendChild(tsBadge);
|
nameSpan.appendChild(tsBadge);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add Category badge if service has one (colored pill with icon)
|
||||||
|
if (s.category) {
|
||||||
|
const cats = (typeof DC !== 'undefined' && DC.CATEGORIES) || window.DC_CATEGORIES || {};
|
||||||
|
const catInfo = cats[s.category] || {};
|
||||||
|
const catBadge = el('span', 'cat-badge', `${catInfo.icon || ''} ${s.category}`.trim());
|
||||||
|
catBadge.title = `Category: ${s.category}`;
|
||||||
|
catBadge.style.cssText = `margin-left: 6px; font-size: 0.65rem; padding: 1px 6px; border-radius: 999px; background: color-mix(in srgb, ${catInfo.color || '#7f8c8d'} 25%, transparent); color: ${catInfo.color || '#7f8c8d'}; border: 1px solid color-mix(in srgb, ${catInfo.color || '#7f8c8d'} 50%, transparent); white-space: nowrap; font-weight: 500;`;
|
||||||
|
nameSpan.appendChild(catBadge);
|
||||||
|
}
|
||||||
|
|
||||||
row.appendChild(el('span', 'spacer'));
|
row.appendChild(el('span', 'spacer'));
|
||||||
|
|
||||||
const pill = el('span', 'badge off', 'OFF'); pill.id = 'badge-' + s.id; row.appendChild(pill);
|
const pill = el('span', 'badge off', 'OFF'); pill.id = 'badge-' + s.id; row.appendChild(pill);
|
||||||
@@ -282,6 +294,9 @@
|
|||||||
|
|
||||||
// Group recipe cards visually after grid is built
|
// Group recipe cards visually after grid is built
|
||||||
if (window.groupRecipeCards) requestAnimationFrame(() => window.groupRecipeCards());
|
if (window.groupRecipeCards) requestAnimationFrame(() => window.groupRecipeCards());
|
||||||
|
|
||||||
|
// Refresh the service filter so the category dropdown reflects new services
|
||||||
|
if (window.refreshServiceFilter) window.refreshServiceFilter();
|
||||||
}
|
}
|
||||||
|
|
||||||
function setBadge(id, up, responseTime = null) {
|
function setBadge(id, up, responseTime = null) {
|
||||||
|
|||||||
@@ -59,11 +59,13 @@
|
|||||||
}
|
}
|
||||||
_dashboardInitialized = true;
|
_dashboardInitialized = true;
|
||||||
await window.loadServices();
|
await window.loadServices();
|
||||||
|
await loadTemplateCategories();
|
||||||
window.buildGrid();
|
window.buildGrid();
|
||||||
animateTopCards();
|
animateTopCards();
|
||||||
window.refreshAll();
|
window.refreshAll();
|
||||||
setInterval(window.refreshAll, DC.POLL.DASHBOARD);
|
setInterval(window.refreshAll, DC.POLL.DASHBOARD);
|
||||||
if (typeof window.refreshCredsButtons === 'function') window.refreshCredsButtons();
|
if (typeof window.refreshCredsButtons === 'function') window.refreshCredsButtons();
|
||||||
|
if (typeof window.refreshMonitoringWidgets === 'function') window.refreshMonitoringWidgets();
|
||||||
// Update auth card (may have already been updated by the auto-load IIFE but ensure it's correct)
|
// Update auth card (may have already been updated by the auto-load IIFE but ensure it's correct)
|
||||||
if (typeof window._updateAuthCard === 'function') {
|
if (typeof window._updateAuthCard === 'function') {
|
||||||
try {
|
try {
|
||||||
@@ -200,6 +202,55 @@
|
|||||||
window.loadCustomServices = loadCustomServices;
|
window.loadCustomServices = loadCustomServices;
|
||||||
registerServiceWorker();
|
registerServiceWorker();
|
||||||
|
|
||||||
|
// ===== TEMPLATE CATEGORIES =====
|
||||||
|
// Cached template categories from /api/v1/templates for use across the UI
|
||||||
|
// (service create/edit, filter dropdown, category badges, etc.)
|
||||||
|
async function loadTemplateCategories() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/v1/templates', { cache: 'no-store' });
|
||||||
|
if (!r.ok) return;
|
||||||
|
const data = await r.json();
|
||||||
|
if (data && data.categories) {
|
||||||
|
window.DC_CATEGORIES = data.categories;
|
||||||
|
// Also expose via globals.js constant for convenience
|
||||||
|
if (typeof DC !== 'undefined') DC.CATEGORIES = data.categories;
|
||||||
|
// Populate any category <select> that's already in the DOM
|
||||||
|
populateCategorySelects();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[init] Failed to load template categories:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function populateCategorySelects() {
|
||||||
|
const cats = window.DC_CATEGORIES || (typeof DC !== 'undefined' && DC.CATEGORIES);
|
||||||
|
if (!cats) return;
|
||||||
|
document.querySelectorAll('select[data-role="service-category"]').forEach(select => {
|
||||||
|
const current = select.dataset.current || '';
|
||||||
|
// Clear options but keep the first (placeholder)
|
||||||
|
const placeholder = select.querySelector('option[value=""]');
|
||||||
|
select.innerHTML = '';
|
||||||
|
if (placeholder) select.appendChild(placeholder);
|
||||||
|
else {
|
||||||
|
const ph = document.createElement('option');
|
||||||
|
ph.value = '';
|
||||||
|
ph.textContent = '— Select category —';
|
||||||
|
select.appendChild(ph);
|
||||||
|
}
|
||||||
|
Object.entries(cats).forEach(([name, info]) => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = name;
|
||||||
|
opt.textContent = `${info.icon || ''} ${name}`.trim();
|
||||||
|
if (name === current) opt.selected = true;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow other modules to re-run population after they (re)inject selects
|
||||||
|
window.populateCategorySelects = populateCategorySelects;
|
||||||
|
window.loadTemplateCategories = loadTemplateCategories;
|
||||||
|
|
||||||
// TOTP-gated initialization
|
// TOTP-gated initialization
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -262,6 +262,7 @@
|
|||||||
const proxyIp = document.getElementById('external-proxy-ip').value.trim() || SITE.dnsIp || 'localhost';
|
const proxyIp = document.getElementById('external-proxy-ip').value.trim() || SITE.dnsIp || 'localhost';
|
||||||
const preserveHost = document.getElementById('external-preserve-host').checked;
|
const preserveHost = document.getElementById('external-preserve-host').checked;
|
||||||
const followRedirects = document.getElementById('external-follow-redirects').checked;
|
const followRedirects = document.getElementById('external-follow-redirects').checked;
|
||||||
|
const category = document.getElementById('external-service-category')?.value || '';
|
||||||
|
|
||||||
if (!name || !externalUrl) {
|
if (!name || !externalUrl) {
|
||||||
showNotification('Please fill in Name and External URL', 'warning');
|
showNotification('Please fill in Name and External URL', 'warning');
|
||||||
@@ -341,6 +342,8 @@
|
|||||||
isExternal: true,
|
isExternal: true,
|
||||||
isCustom: true
|
isCustom: true
|
||||||
};
|
};
|
||||||
|
// Only attach category if user actually picked one
|
||||||
|
if (category) newService.category = category;
|
||||||
|
|
||||||
window.APPS.push(newService);
|
window.APPS.push(newService);
|
||||||
results.dashboard = true;
|
results.dashboard = true;
|
||||||
@@ -457,6 +460,13 @@
|
|||||||
const healthCheck = document.getElementById('health-check-input')?.value || '';
|
const healthCheck = document.getElementById('health-check-input')?.value || '';
|
||||||
const timeout = document.getElementById('timeout-input')?.value || 30;
|
const timeout = document.getElementById('timeout-input')?.value || 30;
|
||||||
|
|
||||||
|
// Category is optional — pulled from either local or external select by the
|
||||||
|
// openAddServiceModal reset. If user doesn't choose one, it stays undefined
|
||||||
|
// and we don't send it (so the backend keeps the existing behavior).
|
||||||
|
const categoryEl = document.getElementById('service-category-input')
|
||||||
|
|| document.getElementById('external-service-category');
|
||||||
|
const category = categoryEl?.value || '';
|
||||||
|
|
||||||
const dnsToken = window.getToken(getPrimaryDnsId(), 'admin');
|
const dnsToken = window.getToken(getPrimaryDnsId(), 'admin');
|
||||||
|
|
||||||
if (!name || !port || !ip) {
|
if (!name || !port || !ip) {
|
||||||
@@ -525,6 +535,8 @@
|
|||||||
logo: logo || `/assets/${subdomain}.png`,
|
logo: logo || `/assets/${subdomain}.png`,
|
||||||
tailscaleOnly: tailscaleOnly || false
|
tailscaleOnly: tailscaleOnly || false
|
||||||
};
|
};
|
||||||
|
// Only include category if user actually picked one
|
||||||
|
if (category) serviceConfig.category = category;
|
||||||
|
|
||||||
await window.addServiceToConfig(serviceConfig);
|
await window.addServiceToConfig(serviceConfig);
|
||||||
results.dashboard = true;
|
results.dashboard = true;
|
||||||
|
|||||||
@@ -19,6 +19,16 @@
|
|||||||
document.getElementById('edit-tailscale-only').checked = service.tailscaleOnly || false;
|
document.getElementById('edit-tailscale-only').checked = service.tailscaleOnly || false;
|
||||||
document.getElementById('edit-logo-url').value = service.logo || '';
|
document.getElementById('edit-logo-url').value = service.logo || '';
|
||||||
|
|
||||||
|
// Populate the category select for this service, then set the current value.
|
||||||
|
// populateCategorySelects() uses data-current so we set it first, then call.
|
||||||
|
const categorySelect = document.getElementById('edit-service-category');
|
||||||
|
if (categorySelect) {
|
||||||
|
categorySelect.dataset.current = service.category || '';
|
||||||
|
if (typeof window.populateCategorySelects === 'function') {
|
||||||
|
window.populateCategorySelects();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
modal.classList.add('show');
|
modal.classList.add('show');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +46,7 @@
|
|||||||
const newIp = document.getElementById('edit-ip').value.trim() || 'localhost';
|
const newIp = document.getElementById('edit-ip').value.trim() || 'localhost';
|
||||||
const tailscaleOnly = document.getElementById('edit-tailscale-only').checked;
|
const tailscaleOnly = document.getElementById('edit-tailscale-only').checked;
|
||||||
const newLogo = document.getElementById('edit-logo-url').value.trim();
|
const newLogo = document.getElementById('edit-logo-url').value.trim();
|
||||||
|
const newCategory = document.getElementById('edit-service-category')?.value || '';
|
||||||
|
|
||||||
if (!newSubdomain) {
|
if (!newSubdomain) {
|
||||||
showNotification('Subdomain is required', 'warning');
|
showNotification('Subdomain is required', 'warning');
|
||||||
@@ -51,6 +62,7 @@
|
|||||||
if (newIp !== currentEditService.ip) changes.push('ip');
|
if (newIp !== currentEditService.ip) changes.push('ip');
|
||||||
if (tailscaleOnly !== (currentEditService.tailscaleOnly || false)) changes.push('tailscale');
|
if (tailscaleOnly !== (currentEditService.tailscaleOnly || false)) changes.push('tailscale');
|
||||||
if (newLogo && newLogo !== currentEditService.logo) changes.push('logo');
|
if (newLogo && newLogo !== currentEditService.logo) changes.push('logo');
|
||||||
|
if (newCategory !== (currentEditService.category || '')) changes.push('category');
|
||||||
|
|
||||||
if (changes.length === 0) {
|
if (changes.length === 0) {
|
||||||
closeServiceEditModal();
|
closeServiceEditModal();
|
||||||
@@ -72,7 +84,8 @@
|
|||||||
port: newPort || currentEditService.port,
|
port: newPort || currentEditService.port,
|
||||||
ip: newIp,
|
ip: newIp,
|
||||||
tailscaleOnly,
|
tailscaleOnly,
|
||||||
logo: newLogo || undefined
|
logo: newLogo || undefined,
|
||||||
|
category: newCategory
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -91,7 +104,8 @@
|
|||||||
port: newPort || window.APPS[appIndex].port,
|
port: newPort || window.APPS[appIndex].port,
|
||||||
ip: newIp,
|
ip: newIp,
|
||||||
tailscaleOnly,
|
tailscaleOnly,
|
||||||
logo: newLogo || window.APPS[appIndex].logo
|
logo: newLogo || window.APPS[appIndex].logo,
|
||||||
|
category: newCategory || undefined
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -187,6 +187,9 @@
|
|||||||
name: serviceConfig.name,
|
name: serviceConfig.name,
|
||||||
logo: serviceConfig.logo || `/assets/${serviceConfig.subdomain}.png`
|
logo: serviceConfig.logo || `/assets/${serviceConfig.subdomain}.png`
|
||||||
};
|
};
|
||||||
|
// Forward optional metadata fields if provided
|
||||||
|
if (serviceConfig.category) newService.category = serviceConfig.category;
|
||||||
|
if (serviceConfig.containerId) newService.containerId = serviceConfig.containerId;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await secureFetch('/api/v1/services', {
|
const response = await secureFetch('/api/v1/services', {
|
||||||
|
|||||||
@@ -82,6 +82,16 @@
|
|||||||
Enter a URL or upload an image file (PNG, JPG, SVG)
|
Enter a URL or upload an image file (PNG, JPG, SVG)
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Category -->
|
||||||
|
<div>
|
||||||
|
<label for="edit-service-category" class="form-label-accent-sm">
|
||||||
|
Category
|
||||||
|
</label>
|
||||||
|
<select id="edit-service-category" data-role="service-category" class="form-input-md">
|
||||||
|
<option value="">— No category —</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="weather-modal-buttons" style="margin-top: 24px;">
|
<div class="weather-modal-buttons" style="margin-top: 24px;">
|
||||||
@@ -239,6 +249,15 @@
|
|||||||
Reload Caddy after adding
|
Reload Caddy after adding
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
|
<!-- Category -->
|
||||||
|
<div>
|
||||||
|
<label for="service-category-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Category</label>
|
||||||
|
<select id="service-category-input" data-role="service-category" style="width: 100%;">
|
||||||
|
<option value="">— No category —</option>
|
||||||
|
</select>
|
||||||
|
<div style="font-size: 0.7rem; color: var(--muted); margin-top: 3px;">Group services on the dashboard by purpose (Media, Productivity, etc.)</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<hr style="border: none; border-top: 1px solid var(--border); margin: 4px 0;" />
|
<hr style="border: none; border-top: 1px solid var(--border); margin: 4px 0;" />
|
||||||
|
|
||||||
<div class="grid-2col">
|
<div class="grid-2col">
|
||||||
@@ -326,6 +345,14 @@
|
|||||||
Follow Redirects
|
Follow Redirects
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
|
<!-- Category (external) -->
|
||||||
|
<div>
|
||||||
|
<label for="external-service-category" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Category</label>
|
||||||
|
<select id="external-service-category" data-role="service-category" style="width: 100%;">
|
||||||
|
<option value="">— No category —</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,304 @@
|
|||||||
|
// ========== MONITORING WIDGETS ==========
|
||||||
|
// Embeds a compact system-resource + health summary panel directly on the
|
||||||
|
// main dashboard. Replaces the need for a separate monitoring-dashboard.html
|
||||||
|
// page — quick at-a-glance stats where you already are.
|
||||||
|
(function () {
|
||||||
|
|
||||||
|
// ----- Style injection (scoped to .dc-monitor so it doesn't leak) -----
|
||||||
|
const styleEl = document.createElement('style');
|
||||||
|
styleEl.textContent = `
|
||||||
|
.dc-monitor {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
padding: 12px 16px;
|
||||||
|
background: var(--card-base);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
.dc-monitor-card {
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: var(--card-bg, rgba(255,255,255,0.04));
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.dc-monitor-label {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
color: var(--muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
.dc-monitor-value {
|
||||||
|
font-size: 1.4rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--fg);
|
||||||
|
}
|
||||||
|
.dc-monitor-sub {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
color: var(--muted);
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
.dc-monitor-bar {
|
||||||
|
margin-top: 6px;
|
||||||
|
width: 100%;
|
||||||
|
height: 4px;
|
||||||
|
background: color-mix(in srgb, var(--muted) 20%, transparent);
|
||||||
|
border-radius: 2px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.dc-monitor-bar-fill {
|
||||||
|
height: 100%;
|
||||||
|
width: 0%;
|
||||||
|
background: var(--ok-fg, #27ae60);
|
||||||
|
transition: width 0.3s ease, background 0.3s ease;
|
||||||
|
}
|
||||||
|
.dc-monitor-bar-fill.warn { background: #f39c12; }
|
||||||
|
.dc-monitor-bar-fill.bad { background: #e74c3c; }
|
||||||
|
.dc-monitor-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.dc-monitor-title {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--muted);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.dc-monitor-pill {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.dc-monitor-pill.ok { background: color-mix(in srgb, #27ae60 20%, transparent); color: #27ae60; }
|
||||||
|
.dc-monitor-pill.warn { background: color-mix(in srgb, #f39c12 20%, transparent); color: #f39c12; }
|
||||||
|
.dc-monitor-pill.bad { background: color-mix(in srgb, #e74c3c 20%, transparent); color: #e74c3c; }
|
||||||
|
.dc-monitor-refresh {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
color: var(--muted);
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
document.head.appendChild(styleEl);
|
||||||
|
|
||||||
|
// ----- Container element (inserted above service-filter-bar) -----
|
||||||
|
const filterBar = document.getElementById('service-filter-bar');
|
||||||
|
if (!filterBar) return;
|
||||||
|
|
||||||
|
const panel = document.createElement('div');
|
||||||
|
panel.className = 'dc-monitor';
|
||||||
|
panel.id = 'dc-monitor-panel';
|
||||||
|
panel.innerHTML = `
|
||||||
|
<div class="dc-monitor-header" style="grid-column: 1 / -1;">
|
||||||
|
<div class="dc-monitor-title">📊 System Overview</div>
|
||||||
|
<span class="dc-monitor-refresh" id="dc-monitor-refresh-stamp">—</span>
|
||||||
|
</div>
|
||||||
|
<div class="dc-monitor-card">
|
||||||
|
<div class="dc-monitor-label">Services</div>
|
||||||
|
<div class="dc-monitor-value" id="dc-monitor-services">—</div>
|
||||||
|
<div class="dc-monitor-sub" id="dc-monitor-services-sub">loading…</div>
|
||||||
|
</div>
|
||||||
|
<div class="dc-monitor-card">
|
||||||
|
<div class="dc-monitor-label">Containers Up</div>
|
||||||
|
<div class="dc-monitor-value" id="dc-monitor-containers">—</div>
|
||||||
|
<div class="dc-monitor-sub" id="dc-monitor-containers-sub">loading…</div>
|
||||||
|
</div>
|
||||||
|
<div class="dc-monitor-card">
|
||||||
|
<div class="dc-monitor-label">Avg CPU</div>
|
||||||
|
<div class="dc-monitor-value" id="dc-monitor-cpu">—</div>
|
||||||
|
<div class="dc-monitor-bar"><div class="dc-monitor-bar-fill" id="dc-monitor-cpu-bar"></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="dc-monitor-card">
|
||||||
|
<div class="dc-monitor-label">Avg Memory</div>
|
||||||
|
<div class="dc-monitor-value" id="dc-monitor-mem">—</div>
|
||||||
|
<div class="dc-monitor-bar"><div class="dc-monitor-bar-fill" id="dc-monitor-mem-bar"></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="dc-monitor-card">
|
||||||
|
<div class="dc-monitor-label">Health</div>
|
||||||
|
<div class="dc-monitor-value" id="dc-monitor-health">—</div>
|
||||||
|
<div class="dc-monitor-sub" id="dc-monitor-health-sub">—</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
// Insert ABOVE the filter bar
|
||||||
|
filterBar.parentNode.insertBefore(panel, filterBar);
|
||||||
|
|
||||||
|
// ----- Helpers -----
|
||||||
|
function setBar(id, pct) {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
if (!el) return;
|
||||||
|
const p = Math.max(0, Math.min(100, Number(pct) || 0));
|
||||||
|
el.style.width = p + '%';
|
||||||
|
el.classList.remove('warn', 'bad');
|
||||||
|
if (p >= 85) el.classList.add('bad');
|
||||||
|
else if (p >= 65) el.classList.add('warn');
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtPct(v) {
|
||||||
|
if (v == null || isNaN(v)) return '—';
|
||||||
|
return (Math.round(v * 10) / 10) + '%';
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtBytes(b) {
|
||||||
|
if (b == null || isNaN(b)) return '—';
|
||||||
|
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
let i = 0;
|
||||||
|
while (b >= 1024 && i < units.length - 1) { b /= 1024; i++; }
|
||||||
|
return b.toFixed(1) + ' ' + units[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
function setServicesCard() {
|
||||||
|
const total = (window.APPS || []).length;
|
||||||
|
let up = 0;
|
||||||
|
document.querySelectorAll('#cards .card').forEach(c => {
|
||||||
|
if (c.dataset.status === 'on') up++;
|
||||||
|
});
|
||||||
|
const el = document.getElementById('dc-monitor-services');
|
||||||
|
const sub = document.getElementById('dc-monitor-services-sub');
|
||||||
|
if (el) el.textContent = `${up} / ${total}`;
|
||||||
|
if (sub) sub.textContent = total === 0 ? 'no services yet' : `${up} online · ${total - up} offline`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyHealthSummary(data) {
|
||||||
|
const el = document.getElementById('dc-monitor-health');
|
||||||
|
const sub = document.getElementById('dc-monitor-health-sub');
|
||||||
|
if (!el) return;
|
||||||
|
if (!data || data.summary == null) {
|
||||||
|
el.textContent = '—';
|
||||||
|
if (sub) sub.textContent = 'no data';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const s = data.summary;
|
||||||
|
const healthy = s.healthy ?? s.up ?? 0;
|
||||||
|
const unhealthy = s.unhealthy ?? s.down ?? 0;
|
||||||
|
const total = s.total ?? (healthy + unhealthy);
|
||||||
|
el.textContent = `${healthy}/${total}`;
|
||||||
|
if (sub) {
|
||||||
|
if (unhealthy === 0) {
|
||||||
|
sub.innerHTML = '<span class="dc-monitor-pill ok">● all healthy</span>';
|
||||||
|
} else if (unhealthy <= 2) {
|
||||||
|
sub.innerHTML = `<span class="dc-monitor-pill warn">● ${unhealthy} degraded</span>`;
|
||||||
|
} else {
|
||||||
|
sub.innerHTML = `<span class="dc-monitor-pill bad">● ${unhealthy} down</span>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Data fetches -----
|
||||||
|
async function fetchStats() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/v1/monitoring/stats', { cache: 'no-store' });
|
||||||
|
if (!r.ok) return null;
|
||||||
|
const data = await r.json();
|
||||||
|
return (data && data.stats) ? data.stats : null;
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchHealth() {
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/v1/health-checks/status', { cache: 'no-store' });
|
||||||
|
if (!r.ok) return null;
|
||||||
|
return await r.json();
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyStats(stats) {
|
||||||
|
const containers = document.getElementById('dc-monitor-containers');
|
||||||
|
const containersSub = document.getElementById('dc-monitor-containers-sub');
|
||||||
|
const cpuEl = document.getElementById('dc-monitor-cpu');
|
||||||
|
const memEl = document.getElementById('dc-monitor-mem');
|
||||||
|
|
||||||
|
if (!stats) {
|
||||||
|
if (containers) containers.textContent = '—';
|
||||||
|
if (cpuEl) cpuEl.textContent = '—';
|
||||||
|
if (memEl) memEl.textContent = '—';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entries = Object.values(stats);
|
||||||
|
if (entries.length === 0) {
|
||||||
|
if (containers) containers.textContent = '0';
|
||||||
|
if (containersSub) containersSub.textContent = 'no containers reporting';
|
||||||
|
if (cpuEl) cpuEl.textContent = '0%';
|
||||||
|
if (memEl) memEl.textContent = '0%';
|
||||||
|
setBar('dc-monitor-cpu-bar', 0);
|
||||||
|
setBar('dc-monitor-mem-bar', 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cpuSum = 0, memSum = 0, memBytes = 0, cpuCount = 0, memCount = 0;
|
||||||
|
entries.forEach(s => {
|
||||||
|
// CPU may be percentage (0-100) or fraction (0-1) — handle both
|
||||||
|
if (s.cpu != null) {
|
||||||
|
const cpu = Number(s.cpu);
|
||||||
|
if (!isNaN(cpu)) {
|
||||||
|
cpuSum += cpu > 1 ? cpu : cpu * 100;
|
||||||
|
cpuCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s.memory != null) {
|
||||||
|
const mem = Number(s.memory);
|
||||||
|
if (!isNaN(mem)) {
|
||||||
|
memSum += mem;
|
||||||
|
memBytes += Number(s.memoryUsage || 0);
|
||||||
|
memCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const avgCpu = cpuCount ? cpuSum / cpuCount : 0;
|
||||||
|
const avgMem = memCount ? memSum / memCount : 0;
|
||||||
|
|
||||||
|
if (containers) containers.textContent = String(entries.length);
|
||||||
|
if (containersSub) {
|
||||||
|
const memTxt = memBytes ? ` · ${fmtBytes(memBytes)} RAM` : '';
|
||||||
|
containersSub.textContent = `running${memTxt}`;
|
||||||
|
}
|
||||||
|
if (cpuEl) cpuEl.textContent = fmtPct(avgCpu);
|
||||||
|
if (memEl) memEl.textContent = fmtPct(avgMem);
|
||||||
|
setBar('dc-monitor-cpu-bar', avgCpu);
|
||||||
|
setBar('dc-monitor-mem-bar', avgMem);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Public refresh function -----
|
||||||
|
let inFlight = false;
|
||||||
|
async function refresh() {
|
||||||
|
if (inFlight) return;
|
||||||
|
inFlight = true;
|
||||||
|
try {
|
||||||
|
setServicesCard();
|
||||||
|
const [stats, health] = await Promise.all([fetchStats(), fetchHealth()]);
|
||||||
|
applyStats(stats);
|
||||||
|
applyHealthSummary(health);
|
||||||
|
const stamp = document.getElementById('dc-monitor-refresh-stamp');
|
||||||
|
if (stamp) {
|
||||||
|
const now = new Date();
|
||||||
|
stamp.textContent = `updated ${now.toLocaleTimeString()}`;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
inFlight = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expose for init.js to call once and re-call after each refreshAll cycle
|
||||||
|
window.refreshMonitoringWidgets = refresh;
|
||||||
|
|
||||||
|
// Auto-refresh on the STATS interval (separate from full DASHBOARD refresh)
|
||||||
|
setInterval(refresh, (typeof DC !== 'undefined' && DC.POLL && DC.POLL.STATS) || 5000);
|
||||||
|
|
||||||
|
// Refresh once on first script load (init.js also calls this; double-call is harmless)
|
||||||
|
setTimeout(refresh, 200);
|
||||||
|
|
||||||
|
})();
|
||||||
@@ -2,11 +2,50 @@
|
|||||||
(function() {
|
(function() {
|
||||||
const searchInput = document.getElementById('service-filter-search');
|
const searchInput = document.getElementById('service-filter-search');
|
||||||
const statusSelect = document.getElementById('service-filter-status');
|
const statusSelect = document.getElementById('service-filter-status');
|
||||||
|
const categorySelect = document.getElementById('service-filter-category');
|
||||||
const countSpan = document.getElementById('service-filter-count');
|
const countSpan = document.getElementById('service-filter-count');
|
||||||
|
|
||||||
|
// Build a single category list from both the API categories and any
|
||||||
|
// categories present on the actual rendered cards (covers custom services
|
||||||
|
// whose category isn't in TEMPLATE_CATEGORIES).
|
||||||
|
function getCategoryList() {
|
||||||
|
const seen = new Set();
|
||||||
|
const fromCards = new Set();
|
||||||
|
document.querySelectorAll('#cards .card[data-category]').forEach(c => {
|
||||||
|
const cat = c.dataset.category.trim();
|
||||||
|
if (cat) fromCards.add(cat);
|
||||||
|
});
|
||||||
|
const apiCats = (window.DC_CATEGORIES || (typeof DC !== 'undefined' && DC.CATEGORIES)) || {};
|
||||||
|
const all = Object.keys(apiCats).concat([...fromCards].filter(c => !apiCats[c]));
|
||||||
|
all.forEach(c => seen.add(c));
|
||||||
|
return { list: [...seen], apiCats };
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshCategoryDropdown() {
|
||||||
|
if (!categorySelect) return;
|
||||||
|
const { list, apiCats } = getCategoryList();
|
||||||
|
const current = categorySelect.value;
|
||||||
|
categorySelect.innerHTML = '<option value="all">All Categories</option>';
|
||||||
|
list.sort().forEach(name => {
|
||||||
|
const info = apiCats[name];
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = name;
|
||||||
|
opt.textContent = info ? `${info.icon || ''} ${name}`.trim() : name;
|
||||||
|
categorySelect.appendChild(opt);
|
||||||
|
});
|
||||||
|
// Restore selection if it still exists
|
||||||
|
if (current && [...categorySelect.options].some(o => o.value === current)) {
|
||||||
|
categorySelect.value = current;
|
||||||
|
} else {
|
||||||
|
categorySelect.value = 'all';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function updateFilter() {
|
function updateFilter() {
|
||||||
|
refreshCategoryDropdown();
|
||||||
const query = searchInput.value.toLowerCase().trim();
|
const query = searchInput.value.toLowerCase().trim();
|
||||||
const statusFilter = statusSelect.value; // 'all', 'on', or 'off'
|
const statusFilter = statusSelect.value; // 'all', 'on', or 'off'
|
||||||
|
const categoryFilter = categorySelect ? categorySelect.value : 'all';
|
||||||
|
|
||||||
const cards = document.querySelectorAll('#cards .card');
|
const cards = document.querySelectorAll('#cards .card');
|
||||||
let visibleCount = 0;
|
let visibleCount = 0;
|
||||||
@@ -15,11 +54,13 @@
|
|||||||
const name = card.querySelector('.name')?.textContent?.toLowerCase() || '';
|
const name = card.querySelector('.name')?.textContent?.toLowerCase() || '';
|
||||||
const app = card.dataset.app?.toLowerCase() || '';
|
const app = card.dataset.app?.toLowerCase() || '';
|
||||||
const status = card.dataset.status || 'off'; // 'on' or 'off'
|
const status = card.dataset.status || 'off'; // 'on' or 'off'
|
||||||
|
const category = card.dataset.category || '';
|
||||||
|
|
||||||
const matchesSearch = !query || name.includes(query) || app.includes(query);
|
const matchesSearch = !query || name.includes(query) || app.includes(query);
|
||||||
const matchesStatus = statusFilter === 'all' || status === statusFilter;
|
const matchesStatus = statusFilter === 'all' || status === statusFilter;
|
||||||
|
const matchesCategory = categoryFilter === 'all' || category === categoryFilter;
|
||||||
|
|
||||||
if (matchesSearch && matchesStatus) {
|
if (matchesSearch && matchesStatus && matchesCategory) {
|
||||||
card.style.display = '';
|
card.style.display = '';
|
||||||
visibleCount++;
|
visibleCount++;
|
||||||
} else {
|
} else {
|
||||||
@@ -44,6 +85,7 @@
|
|||||||
|
|
||||||
searchInput?.addEventListener('input', debounce(updateFilter, 200));
|
searchInput?.addEventListener('input', debounce(updateFilter, 200));
|
||||||
statusSelect?.addEventListener('change', updateFilter);
|
statusSelect?.addEventListener('change', updateFilter);
|
||||||
|
categorySelect?.addEventListener('change', updateFilter);
|
||||||
|
|
||||||
// Initial count on page load
|
// Initial count on page load
|
||||||
if (document.readyState === 'loading') {
|
if (document.readyState === 'loading') {
|
||||||
@@ -52,6 +94,7 @@
|
|||||||
setTimeout(updateFilter, 500);
|
setTimeout(updateFilter, 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Expose for external triggers
|
// Expose for external triggers (called after buildGrid to repopulate categories)
|
||||||
window.refreshServiceFilter = updateFilter;
|
window.refreshServiceFilter = updateFilter;
|
||||||
|
window.refreshCategoryDropdown = refreshCategoryDropdown;
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -17,8 +17,10 @@
|
|||||||
|
|
||||||
<!-- Tab: Available Updates -->
|
<!-- Tab: Available Updates -->
|
||||||
<div id="updates-available" class="panel-section active">
|
<div id="updates-available" class="panel-section active">
|
||||||
<div style="margin-bottom: 12px;">
|
<div style="margin-bottom: 12px; display: flex; gap: 8px; align-items: center;">
|
||||||
<button id="updates-check-btn" class="btn-accent-solid">🔍 Check for Updates</button>
|
<button id="updates-check-btn" class="btn-accent-solid">🔍 Check for Updates</button>
|
||||||
|
<button id="updates-update-all-btn" style="display: none; padding: 6px 14px; font-size: 0.82rem; background: #f97316; color: #fff; border: 1px solid #f97316; border-radius: 6px; cursor: pointer;">⬆️ Update All</button>
|
||||||
|
<span id="updates-count-badge" style="display: none; padding: 4px 10px; border-radius: 12px; font-size: 0.78rem; font-weight: 600; background: var(--accent); color: var(--bg);"></span>
|
||||||
</div>
|
</div>
|
||||||
<div id="updates-available-container" style="max-height: 450px; overflow-y: auto;">
|
<div id="updates-available-container" style="max-height: 450px; overflow-y: auto;">
|
||||||
<div class="panel-empty"><span class="empty-icon">📦</span> Click "Check for Updates" to scan containers.</div>
|
<div class="panel-empty"><span class="empty-icon">📦</span> Click "Check for Updates" to scan containers.</div>
|
||||||
@@ -94,13 +96,24 @@
|
|||||||
if (updates.length === 0) {
|
if (updates.length === 0) {
|
||||||
availableContainer.innerHTML = '<div class="panel-empty"><span class="empty-icon">✅</span>All containers are up to date.</div>';
|
availableContainer.innerHTML = '<div class="panel-empty"><span class="empty-icon">✅</span>All containers are up to date.</div>';
|
||||||
lastCheckSpan.textContent = '';
|
lastCheckSpan.textContent = '';
|
||||||
|
document.getElementById('updates-update-all-btn').style.display = 'none';
|
||||||
|
document.getElementById('updates-count-badge').style.display = 'none';
|
||||||
|
window._pendingUpdates = [];
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let html = '<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';
|
let html = '<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';
|
||||||
html += '<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';
|
html += '<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';
|
||||||
for (const u of updates) {
|
for (const u of updates) {
|
||||||
html += `<tr style="border-bottom: 1px solid var(--border);">`;
|
// Match app by containerId first, then name
|
||||||
|
const appId = (() => {
|
||||||
|
const apps = window.APPS || [];
|
||||||
|
for (const a of apps) {
|
||||||
|
if (a.containerId === u.containerId || a.name === u.containerName || a.id === u.containerName) return a.id;
|
||||||
|
}
|
||||||
|
return u.containerName;
|
||||||
|
})();
|
||||||
|
html += `<tr data-app-id="${escapeHtml(appId)}" style="border-bottom: 1px solid var(--border);">`;
|
||||||
html += `<td style="padding: 8px; font-weight: 500;">${escapeHtml(u.containerName)}</td>`;
|
html += `<td style="padding: 8px; font-weight: 500;">${escapeHtml(u.containerName)}</td>`;
|
||||||
html += `<td style="padding: 8px; color: var(--muted);">${escapeHtml(u.imageName)}</td>`;
|
html += `<td style="padding: 8px; color: var(--muted);">${escapeHtml(u.imageName)}</td>`;
|
||||||
html += `<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(u.currentDigest)}</code></td>`;
|
html += `<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(u.currentDigest)}</code></td>`;
|
||||||
@@ -114,6 +127,20 @@
|
|||||||
availableContainer.innerHTML = html;
|
availableContainer.innerHTML = html;
|
||||||
lastCheckSpan.textContent = updates.length + ' update(s) available';
|
lastCheckSpan.textContent = updates.length + ' update(s) available';
|
||||||
|
|
||||||
|
// Show count badge and Update All button
|
||||||
|
const countBadge = document.getElementById('updates-count-badge');
|
||||||
|
const updateAllBtn = document.getElementById('updates-update-all-btn');
|
||||||
|
if (countBadge) {
|
||||||
|
countBadge.textContent = updates.length + ' pending';
|
||||||
|
countBadge.style.display = '';
|
||||||
|
}
|
||||||
|
if (updateAllBtn && updates.length > 0) {
|
||||||
|
updateAllBtn.style.display = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store updates for Update All button
|
||||||
|
window._pendingUpdates = updates;
|
||||||
|
|
||||||
// Wire update buttons
|
// Wire update buttons
|
||||||
availableContainer.querySelectorAll('.update-now-btn').forEach(btn => {
|
availableContainer.querySelectorAll('.update-now-btn').forEach(btn => {
|
||||||
btn.addEventListener('click', async () => {
|
btn.addEventListener('click', async () => {
|
||||||
@@ -174,6 +201,38 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update All — sequentially, skip failures
|
||||||
|
async function updateAllContainers() {
|
||||||
|
const updates = window._pendingUpdates || [];
|
||||||
|
if (!updates.length) return;
|
||||||
|
const btn = document.getElementById('updates-update-all-btn');
|
||||||
|
if (!confirm(`Update all ${updates.length} containers? Each will restart.`)) return;
|
||||||
|
btn.textContent = '⏳ Updating...';
|
||||||
|
btn.disabled = true;
|
||||||
|
let success = 0, failed = 0;
|
||||||
|
for (const u of updates) {
|
||||||
|
try {
|
||||||
|
const r = await secureFetch(`/api/v1/updates/update/${encodeURIComponent(u.containerId)}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ autoRollback: true })
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (d.success) success++;
|
||||||
|
else failed++;
|
||||||
|
} catch (_) { failed++; }
|
||||||
|
}
|
||||||
|
btn.textContent = `✅ Done`;
|
||||||
|
showNotification(`Update all: ${success} succeeded, ${failed} failed.`, success > 0 && failed === 0 ? 'success' : 'error');
|
||||||
|
setTimeout(() => {
|
||||||
|
btn.textContent = '⬆️ Update All';
|
||||||
|
btn.disabled = false;
|
||||||
|
loadAvailable();
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('updates-update-all-btn')?.addEventListener('click', updateAllContainers);
|
||||||
|
|
||||||
async function checkForUpdates() {
|
async function checkForUpdates() {
|
||||||
checkBtn.textContent = '🔍 Checking...';
|
checkBtn.textContent = '🔍 Checking...';
|
||||||
checkBtn.disabled = true;
|
checkBtn.disabled = true;
|
||||||
@@ -499,6 +558,21 @@
|
|||||||
});
|
});
|
||||||
wireModal(modal, cancelBtn);
|
wireModal(modal, cancelBtn);
|
||||||
|
|
||||||
|
// Open Update Management modal, optionally scrolled to a specific app
|
||||||
|
window.openUpdateModal = function(appId) {
|
||||||
|
modal?.classList.add('show');
|
||||||
|
loadAvailable().then(() => {
|
||||||
|
if (!appId) return;
|
||||||
|
// Scroll to and highlight the matching row
|
||||||
|
const row = availableContainer.querySelector(`[data-app-id="${appId}"]`);
|
||||||
|
if (row) {
|
||||||
|
row.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
row.style.background = 'rgba(249,115,22,0.15)';
|
||||||
|
setTimeout(() => { row.style.background = ''; }, 3000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// Lazy-load tabs
|
// Lazy-load tabs
|
||||||
document.querySelector('[data-panel="updates-history"]')?.addEventListener('click', loadHistory);
|
document.querySelector('[data-panel="updates-history"]')?.addEventListener('click', loadHistory);
|
||||||
document.querySelector('[data-panel="updates-auto"]')?.addEventListener('click', loadAutoConfig);
|
document.querySelector('[data-panel="updates-auto"]')?.addEventListener('click', loadAutoConfig);
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
const CACHE = 'dashcaddy-shell-8ef9c82616';
|
const CACHE = 'dashcaddy-shell-43a872cc40';
|
||||||
const PRECACHE = [
|
const PRECACHE = [
|
||||||
'/',
|
'/',
|
||||||
'/index.html',
|
'/index.html',
|
||||||
|
|||||||
Reference in New Issue
Block a user