Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e361d9a328 | ||
|
|
aa25bcc053 | ||
|
|
bda08b592e | ||
|
|
0e408974a0 | ||
|
|
f4b35dcc30 | ||
|
|
1c0d765182 | ||
|
|
2cd62208ac | ||
|
|
7557a6364a | ||
|
|
54c4b049a8 | ||
|
|
2de72ed506 | ||
|
|
0aa1c3d077 | ||
|
|
954be9e868 | ||
|
|
afcccf811e | ||
|
|
0aa7244cf4 | ||
|
|
1d8919532b | ||
|
|
ea9bdf9598 | ||
|
|
c52016d727 | ||
|
|
588188edb5 | ||
|
|
11823a1466 |
@@ -11,6 +11,7 @@ RUN npm install --production
|
|||||||
COPY *.js ./
|
COPY *.js ./
|
||||||
COPY src/ ./src/
|
COPY src/ ./src/
|
||||||
COPY routes/ ./routes/
|
COPY routes/ ./routes/
|
||||||
|
COPY dns-providers/ ./dns-providers/
|
||||||
COPY openapi.yaml ./
|
COPY openapi.yaml ./
|
||||||
|
|
||||||
# VERSION file holds the short git SHA the image was built from. Committed as
|
# VERSION file holds the short git SHA the image was built from. Committed as
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
dev
|
1.10.0
|
||||||
|
|||||||
@@ -342,7 +342,8 @@ const APP_TEMPLATES = {
|
|||||||
volumes: [
|
volumes: [
|
||||||
"/var/run/docker.sock:/var/run/docker.sock",
|
"/var/run/docker.sock:/var/run/docker.sock",
|
||||||
"/opt/portainer/data:/data"
|
"/opt/portainer/data:/data"
|
||||||
]
|
],
|
||||||
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "portainer",
|
subdomain: "portainer",
|
||||||
defaultPort: 9000,
|
defaultPort: 9000,
|
||||||
@@ -393,7 +394,8 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "louislam/uptime-kuma:latest",
|
image: "louislam/uptime-kuma:latest",
|
||||||
ports: ["{{PORT}}:3001"],
|
ports: ["{{PORT}}:3001"],
|
||||||
volumes: ["/opt/uptime-kuma:/app/data"]
|
volumes: ["/opt/uptime-kuma:/app/data"],
|
||||||
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "uptime",
|
subdomain: "uptime",
|
||||||
defaultPort: 3002,
|
defaultPort: 3002,
|
||||||
@@ -549,7 +551,7 @@ const APP_TEMPLATES = {
|
|||||||
},
|
},
|
||||||
subdomain: "dns2",
|
subdomain: "dns2",
|
||||||
defaultPort: 953,
|
defaultPort: 953,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:53",
|
||||||
subpathSupport: 'strip',
|
subpathSupport: 'strip',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Configure zone files in /opt/bind9/config/",
|
"Configure zone files in /opt/bind9/config/",
|
||||||
@@ -640,14 +642,14 @@ const APP_TEMPLATES = {
|
|||||||
],
|
],
|
||||||
docker: {
|
docker: {
|
||||||
image: "coredns/coredns:latest",
|
image: "coredns/coredns:latest",
|
||||||
ports: ["53:53", "53:53/udp"],
|
ports: ["{{PORT}}:53", "53:53", "53:53/udp"],
|
||||||
volumes: ["/opt/coredns/config:/etc/coredns"],
|
volumes: ["/opt/coredns/config:/etc/coredns"],
|
||||||
environment: {},
|
environment: {},
|
||||||
command: ["-conf", "/etc/coredns/Corefile"]
|
command: ["-conf", "/etc/coredns/Corefile"]
|
||||||
},
|
},
|
||||||
subdomain: "dns4",
|
subdomain: "dns4",
|
||||||
defaultPort: 53,
|
defaultPort: 53,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:53",
|
||||||
subpathSupport: 'strip',
|
subpathSupport: 'strip',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Create Corefile in /opt/coredns/config/",
|
"Create Corefile in /opt/coredns/config/",
|
||||||
@@ -1007,7 +1009,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "adminer:latest",
|
image: "adminer:latest",
|
||||||
ports: ["{{PORT}}:8080"],
|
ports: ["{{PORT}}:8080"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/adminer:/var/www/html"
|
||||||
|
],
|
||||||
environment: {
|
environment: {
|
||||||
"ADMINER_DEFAULT_SERVER": "postgres"
|
"ADMINER_DEFAULT_SERVER": "postgres"
|
||||||
}
|
}
|
||||||
@@ -1099,6 +1103,7 @@ const APP_TEMPLATES = {
|
|||||||
popularity: 85,
|
popularity: 85,
|
||||||
difficulty: "Easy",
|
difficulty: "Easy",
|
||||||
isDashboardWidget: true,
|
isDashboardWidget: true,
|
||||||
|
isStaticSite: true,
|
||||||
widgetSelector: ".weather-widget-container",
|
widgetSelector: ".weather-widget-container",
|
||||||
subdomain: null,
|
subdomain: null,
|
||||||
defaultPort: null,
|
defaultPort: null,
|
||||||
@@ -1126,6 +1131,7 @@ const APP_TEMPLATES = {
|
|||||||
popularity: 80,
|
popularity: 80,
|
||||||
difficulty: "Easy",
|
difficulty: "Easy",
|
||||||
isDashboardWidget: true,
|
isDashboardWidget: true,
|
||||||
|
isStaticSite: true,
|
||||||
widgetSelector: ".clock-widget-container",
|
widgetSelector: ".clock-widget-container",
|
||||||
subdomain: null,
|
subdomain: null,
|
||||||
defaultPort: null,
|
defaultPort: null,
|
||||||
@@ -1908,7 +1914,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "traefik/whoami:latest",
|
image: "traefik/whoami:latest",
|
||||||
ports: ["{{PORT}}:80"],
|
ports: ["{{PORT}}:80"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/whoami/config:/config"
|
||||||
|
],
|
||||||
environment: {}
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "whoami",
|
subdomain: "whoami",
|
||||||
@@ -2233,7 +2241,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "excalidraw/excalidraw:latest",
|
image: "excalidraw/excalidraw:latest",
|
||||||
ports: ["{{PORT}}:80"],
|
ports: ["{{PORT}}:80"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/excalidraw/data:/var/lib/excalidraw"
|
||||||
|
],
|
||||||
environment: {}
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "draw",
|
subdomain: "draw",
|
||||||
@@ -2258,7 +2268,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "corentinth/it-tools:latest",
|
image: "corentinth/it-tools:latest",
|
||||||
ports: ["{{PORT}}:80"],
|
ports: ["{{PORT}}:80"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/it-tools/config:/config"
|
||||||
|
],
|
||||||
environment: {}
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "tools",
|
subdomain: "tools",
|
||||||
@@ -2417,7 +2429,7 @@ const APP_TEMPLATES = {
|
|||||||
},
|
},
|
||||||
subdomain: "mc",
|
subdomain: "mc",
|
||||||
defaultPort: 25565,
|
defaultPort: 25565,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:25565",
|
||||||
subpathSupport: 'none',
|
subpathSupport: 'none',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Server accepts the Minecraft EULA automatically",
|
"Server accepts the Minecraft EULA automatically",
|
||||||
@@ -2451,7 +2463,7 @@ const APP_TEMPLATES = {
|
|||||||
},
|
},
|
||||||
subdomain: "valheim",
|
subdomain: "valheim",
|
||||||
defaultPort: 2456,
|
defaultPort: 2456,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:2456",
|
||||||
subpathSupport: 'none',
|
subpathSupport: 'none',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Connect via Steam: Add Server > IP:2456",
|
"Connect via Steam: Add Server > IP:2456",
|
||||||
|
|||||||
@@ -0,0 +1,503 @@
|
|||||||
|
/**
|
||||||
|
* Auto-Restart Manager - Per-container restart policies with retry tracking
|
||||||
|
*
|
||||||
|
* When a container goes down, attempts automatic restart up to N times
|
||||||
|
* (configurable per-service). Sends notifications on each attempt and
|
||||||
|
* when max retries are exceeded. Integrates with HealthChecker events.
|
||||||
|
*
|
||||||
|
* @module auto-restart-manager
|
||||||
|
*/
|
||||||
|
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
const path = require('path');
|
||||||
|
const { readJsonFile, writeJsonFile } = require('./fs-helpers');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default policy values applied when a new policy is created.
|
||||||
|
* @readonly
|
||||||
|
*/
|
||||||
|
const DEFAULT_POLICY = {
|
||||||
|
enabled: true,
|
||||||
|
maxRetries: 3,
|
||||||
|
retryIntervalMs: 5000,
|
||||||
|
windowMinutes: 10,
|
||||||
|
currentRetries: 0,
|
||||||
|
lastRestartAt: null,
|
||||||
|
cooldownUntil: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages automatic container restart policies and execution.
|
||||||
|
*
|
||||||
|
* @extends EventEmitter
|
||||||
|
*
|
||||||
|
* @fires AutoRestartManager#auto-restart-attempt
|
||||||
|
* @fires AutoRestartManager#auto-restart-success
|
||||||
|
* @fires AutoRestartManager#auto-restart-failed
|
||||||
|
* @fires AutoRestartManager#auto-restart-max-reached
|
||||||
|
*/
|
||||||
|
class AutoRestartManager extends EventEmitter {
|
||||||
|
/**
|
||||||
|
* @param {Object} ctx - Shared application context
|
||||||
|
* @param {Object} ctx.docker - Docker client wrapper ({ client: Dockerode })
|
||||||
|
* @param {Object} ctx.healthChecker - HealthChecker singleton
|
||||||
|
* @param {Object} ctx.notification - NotificationManager instance
|
||||||
|
* @param {Object} ctx.log - Logger instance
|
||||||
|
* @param {Function} ctx.logError - Error logging function
|
||||||
|
* @param {string} ctx.SERVICES_FILE - Path to services.json (used to derive data dir)
|
||||||
|
*/
|
||||||
|
constructor(ctx) {
|
||||||
|
super();
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.log = ctx.log || console;
|
||||||
|
this.logError = ctx.logError || ((_ctx, err) => console.error(err));
|
||||||
|
this.docker = ctx.docker;
|
||||||
|
this.healthChecker = ctx.healthChecker;
|
||||||
|
this.notification = ctx.notification;
|
||||||
|
|
||||||
|
/** @type {Map<string, Object>} serviceId -> policy */
|
||||||
|
this.policies = new Map();
|
||||||
|
|
||||||
|
/** Path to the JSON file that persists policies */
|
||||||
|
this.policiesFile = path.join(path.dirname(ctx.SERVICES_FILE), 'auto-restart-policies.json');
|
||||||
|
|
||||||
|
/** Track previous health status per service for transition detection */
|
||||||
|
this._previousHealth = new Map();
|
||||||
|
|
||||||
|
/** Bound handlers so we can remove them on stop() */
|
||||||
|
this._onStatusCheck = this._handleStatusCheck.bind(this);
|
||||||
|
this._started = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Lifecycle ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load persisted policies, then wire into HealthChecker events.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async start() {
|
||||||
|
if (this._started) return;
|
||||||
|
|
||||||
|
// Load persisted policies from disk
|
||||||
|
try {
|
||||||
|
const data = await readJsonFile(this.policiesFile, {});
|
||||||
|
for (const [serviceId, policy] of Object.entries(data)) {
|
||||||
|
this.policies.set(serviceId, { ...DEFAULT_POLICY, ...policy });
|
||||||
|
}
|
||||||
|
this.log.info('auto-restart', 'Policies loaded', { count: this.policies.size });
|
||||||
|
} catch (err) {
|
||||||
|
this.log.error('auto-restart', 'Failed to load policies', { error: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Listen to health checker status transitions
|
||||||
|
if (this.healthChecker) {
|
||||||
|
this.healthChecker.on('status-check', this._onStatusCheck);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._started = true;
|
||||||
|
this.log.info('auto-restart', 'Manager started');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove event listeners and stop processing health events.
|
||||||
|
*/
|
||||||
|
stop() {
|
||||||
|
if (!this._started) return;
|
||||||
|
|
||||||
|
if (this.healthChecker) {
|
||||||
|
this.healthChecker.removeListener('status-check', this._onStatusCheck);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._started = false;
|
||||||
|
this.log.info('auto-restart', 'Manager stopped');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Policy CRUD ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create or update a restart policy for a service.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId - Unique service identifier
|
||||||
|
* @param {Object} policy - Partial policy fields to merge
|
||||||
|
* @param {boolean} [policy.enabled=true]
|
||||||
|
* @param {number} [policy.maxRetries=3]
|
||||||
|
* @param {number} [policy.retryIntervalMs=5000]
|
||||||
|
* @param {number} [policy.windowMinutes=10]
|
||||||
|
* @returns {Promise<Object>} The resulting policy
|
||||||
|
* @throws {Error} If serviceId is invalid
|
||||||
|
*/
|
||||||
|
async setPolicy(serviceId, policy) {
|
||||||
|
if (!serviceId || typeof serviceId !== 'string') {
|
||||||
|
throw new Error('serviceId is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = this.policies.get(serviceId) || { ...DEFAULT_POLICY, serviceId };
|
||||||
|
|
||||||
|
const merged = {
|
||||||
|
...existing,
|
||||||
|
...policy,
|
||||||
|
serviceId,
|
||||||
|
// Never allow caller to override runtime counters directly
|
||||||
|
currentRetries: existing.currentRetries || 0,
|
||||||
|
lastRestartAt: existing.lastRestartAt,
|
||||||
|
cooldownUntil: existing.cooldownUntil,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.policies.set(serviceId, merged);
|
||||||
|
await this._savePolicies();
|
||||||
|
|
||||||
|
this.log.info('auto-restart', 'Policy set', { serviceId, enabled: merged.enabled });
|
||||||
|
return { ...merged };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the policy for a service.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @returns {Object|null} Policy object or null if none exists
|
||||||
|
*/
|
||||||
|
getPolicy(serviceId) {
|
||||||
|
const policy = this.policies.get(serviceId);
|
||||||
|
return policy ? { ...policy } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return all policies as an array.
|
||||||
|
* @returns {Object[]}
|
||||||
|
*/
|
||||||
|
listPolicies() {
|
||||||
|
return Array.from(this.policies.values()).map(p => ({ ...p }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a service's restart policy.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @returns {Promise<boolean>} true if a policy was removed
|
||||||
|
*/
|
||||||
|
async removePolicy(serviceId) {
|
||||||
|
if (!this.policies.has(serviceId)) return false;
|
||||||
|
|
||||||
|
this.policies.delete(serviceId);
|
||||||
|
await this._savePolicies();
|
||||||
|
|
||||||
|
this.log.info('auto-restart', 'Policy removed', { serviceId });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Core Restart Logic ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when a container is detected as down.
|
||||||
|
*
|
||||||
|
* Checks policy, cooldown, and retry count, then either attempts a
|
||||||
|
* Docker restart or notifies that max retries were exceeded.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId - Service identifier
|
||||||
|
* @param {string} containerId - Docker container ID to restart
|
||||||
|
* @returns {Promise<Object>} Result of the operation
|
||||||
|
*/
|
||||||
|
async handleContainerDown(serviceId, containerId) {
|
||||||
|
const policy = this.policies.get(serviceId);
|
||||||
|
if (!policy) {
|
||||||
|
return { action: 'ignored', reason: 'no-policy' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!policy.enabled) {
|
||||||
|
return { action: 'ignored', reason: 'disabled' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check cooldown window
|
||||||
|
const now = Date.now();
|
||||||
|
if (policy.cooldownUntil && now < policy.cooldownUntil) {
|
||||||
|
this.log.info('auto-restart', 'Skipping — cooldown active', {
|
||||||
|
serviceId,
|
||||||
|
cooldownUntil: new Date(policy.cooldownUntil).toISOString(),
|
||||||
|
});
|
||||||
|
return { action: 'skipped', reason: 'cooldown' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Max retries exceeded — notify and enter cooldown
|
||||||
|
if (policy.currentRetries >= policy.maxRetries) {
|
||||||
|
const cooldownMs = policy.windowMinutes * 60 * 1000;
|
||||||
|
policy.cooldownUntil = now + cooldownMs;
|
||||||
|
policy.currentRetries = 0; // Reset so next window can try again
|
||||||
|
await this._savePolicies();
|
||||||
|
|
||||||
|
const eventData = {
|
||||||
|
serviceId,
|
||||||
|
containerId,
|
||||||
|
maxRetries: policy.maxRetries,
|
||||||
|
cooldownUntil: policy.cooldownUntil,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @event AutoRestartManager#auto-restart-max-reached
|
||||||
|
* @type {Object}
|
||||||
|
*/
|
||||||
|
this.emit('auto-restart-max-reached', eventData);
|
||||||
|
|
||||||
|
// Send notification
|
||||||
|
try {
|
||||||
|
await this._notify('auto-restart', {
|
||||||
|
containerName: serviceId,
|
||||||
|
message: `⛔ Max auto-restart retries (${policy.maxRetries}) exceeded for "${serviceId}". Cooldown until ${new Date(policy.cooldownUntil).toISOString()}.`,
|
||||||
|
...eventData,
|
||||||
|
});
|
||||||
|
} catch (notifErr) {
|
||||||
|
this.log.error('auto-restart', 'Notification failed', { error: notifErr.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
return { action: 'max-reached', ...eventData };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for the configured retry interval before attempting
|
||||||
|
if (policy.retryIntervalMs > 0 && policy.lastRestartAt) {
|
||||||
|
const elapsed = now - new Date(policy.lastRestartAt).getTime();
|
||||||
|
if (elapsed < policy.retryIntervalMs) {
|
||||||
|
const waitMs = policy.retryIntervalMs - elapsed;
|
||||||
|
this.log.info('auto-restart', 'Waiting for retry interval', { serviceId, waitMs });
|
||||||
|
await new Promise(resolve => setTimeout(resolve, waitMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attempt restart
|
||||||
|
policy.currentRetries += 1;
|
||||||
|
const attemptNum = policy.currentRetries;
|
||||||
|
const maxRetries = policy.maxRetries;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @event AutoRestartManager#auto-restart-attempt
|
||||||
|
* @type {Object}
|
||||||
|
*/
|
||||||
|
this.emit('auto-restart-attempt', {
|
||||||
|
serviceId,
|
||||||
|
containerId,
|
||||||
|
attempt: attemptNum,
|
||||||
|
maxRetries,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!this.docker?.client) {
|
||||||
|
throw new Error('Docker client not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
const container = this.docker.client.getContainer(containerId);
|
||||||
|
await container.start();
|
||||||
|
|
||||||
|
policy.lastRestartAt = new Date().toISOString();
|
||||||
|
await this._savePolicies();
|
||||||
|
|
||||||
|
const successData = {
|
||||||
|
serviceId,
|
||||||
|
containerId,
|
||||||
|
attempt: attemptNum,
|
||||||
|
maxRetries,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @event AutoRestartManager#auto-restart-success
|
||||||
|
* @type {Object}
|
||||||
|
*/
|
||||||
|
this.emit('auto-restart-success', successData);
|
||||||
|
|
||||||
|
// Notify
|
||||||
|
try {
|
||||||
|
await this._notify('auto-restart', {
|
||||||
|
containerName: serviceId,
|
||||||
|
message: `🔄 Auto-restart attempt ${attemptNum}/${maxRetries} succeeded for "${serviceId}".`,
|
||||||
|
...successData,
|
||||||
|
});
|
||||||
|
} catch (notifErr) {
|
||||||
|
this.log.error('auto-restart', 'Notification failed', { error: notifErr.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.log.info('auto-restart', 'Container restarted', {
|
||||||
|
serviceId,
|
||||||
|
attempt: attemptNum,
|
||||||
|
maxRetries,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { action: 'restarted', ...successData };
|
||||||
|
} catch (restartErr) {
|
||||||
|
policy.lastRestartAt = new Date().toISOString();
|
||||||
|
await this._savePolicies();
|
||||||
|
|
||||||
|
const failData = {
|
||||||
|
serviceId,
|
||||||
|
containerId,
|
||||||
|
attempt: attemptNum,
|
||||||
|
maxRetries,
|
||||||
|
error: restartErr.message,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @event AutoRestartManager#auto-restart-failed
|
||||||
|
* @type {Object}
|
||||||
|
*/
|
||||||
|
this.emit('auto-restart-failed', failData);
|
||||||
|
|
||||||
|
// Notify
|
||||||
|
try {
|
||||||
|
await this._notify('auto-restart', {
|
||||||
|
containerName: serviceId,
|
||||||
|
message: `❌ Auto-restart attempt ${attemptNum}/${maxRetries} failed for "${serviceId}": ${restartErr.message}`,
|
||||||
|
...failData,
|
||||||
|
});
|
||||||
|
} catch (notifErr) {
|
||||||
|
this.log.error('auto-restart', 'Notification failed', { error: notifErr.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.log.error('auto-restart', 'Restart failed', {
|
||||||
|
serviceId,
|
||||||
|
attempt: attemptNum,
|
||||||
|
error: restartErr.message,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { action: 'failed', ...failData };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when a container recovers to healthy state.
|
||||||
|
* Resets the retry counter for the associated service.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async handleContainerUp(serviceId) {
|
||||||
|
const policy = this.policies.get(serviceId);
|
||||||
|
if (!policy) return;
|
||||||
|
|
||||||
|
if (policy.currentRetries > 0) {
|
||||||
|
policy.currentRetries = 0;
|
||||||
|
policy.cooldownUntil = null;
|
||||||
|
await this._savePolicies();
|
||||||
|
|
||||||
|
this.log.info('auto-restart', 'Retries reset after recovery', { serviceId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Health Event Bridge ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal handler for HealthChecker `status-check` events.
|
||||||
|
* Detects healthy→unhealthy and unhealthy→healthy transitions for tracked services.
|
||||||
|
*
|
||||||
|
* @param {Object} status - HealthChecker status object
|
||||||
|
* @param {string} status.serviceId
|
||||||
|
* @param {string} status.status - "up" or "down"
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async _handleStatusCheck(status) {
|
||||||
|
const { serviceId, status: currentStatus } = status;
|
||||||
|
if (!serviceId) return;
|
||||||
|
|
||||||
|
// Only process services that have a restart policy
|
||||||
|
if (!this.policies.has(serviceId)) return;
|
||||||
|
|
||||||
|
const previousStatus = this._previousHealth.get(serviceId);
|
||||||
|
this._previousHealth.set(serviceId, currentStatus);
|
||||||
|
|
||||||
|
// Transition: healthy → unhealthy
|
||||||
|
if (previousStatus === 'up' && currentStatus === 'down') {
|
||||||
|
// Find the containerId from the health checker config or status details
|
||||||
|
const containerId = this._resolveContainerId(serviceId, status);
|
||||||
|
if (containerId) {
|
||||||
|
try {
|
||||||
|
await this.handleContainerDown(serviceId, containerId);
|
||||||
|
} catch (err) {
|
||||||
|
this.logError('auto-restart-health-bridge', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transition: unhealthy → healthy (recovery)
|
||||||
|
if (previousStatus === 'down' && currentStatus === 'up') {
|
||||||
|
try {
|
||||||
|
await this.handleContainerUp(serviceId);
|
||||||
|
} catch (err) {
|
||||||
|
this.logError('auto-restart-health-bridge', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempt to find the containerId for a service from various sources.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @param {Object} status - The status-check event data
|
||||||
|
* @returns {string|null}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_resolveContainerId(serviceId, status) {
|
||||||
|
// Check if it's in the status details (some health checks embed it)
|
||||||
|
if (status.details?.containerId) return status.details.containerId;
|
||||||
|
|
||||||
|
// Look in the health checker config
|
||||||
|
const hcService = this.healthChecker?.config?.services?.[serviceId];
|
||||||
|
if (hcService?.containerId) return hcService.containerId;
|
||||||
|
|
||||||
|
// Try to look it up from the services state manager
|
||||||
|
try {
|
||||||
|
const servicesStateManager = this.ctx.servicesStateManager;
|
||||||
|
if (servicesStateManager) {
|
||||||
|
const readResult = servicesStateManager.read();
|
||||||
|
if (readResult && typeof readResult.then === 'function') {
|
||||||
|
// It returns a promise — fire-and-forget lookup
|
||||||
|
readResult.then(list => {
|
||||||
|
const found = (list || []).find(s => s.id === serviceId);
|
||||||
|
return found?.containerId || null;
|
||||||
|
}).catch(() => null);
|
||||||
|
} else {
|
||||||
|
const found = (readResult || []).find(s => s.id === serviceId);
|
||||||
|
if (found?.containerId) return found.containerId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) { /* best effort */ }
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Persistence ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persist current policies to disk.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async _savePolicies() {
|
||||||
|
try {
|
||||||
|
const obj = {};
|
||||||
|
for (const [serviceId, policy] of this.policies.entries()) {
|
||||||
|
obj[serviceId] = { ...policy };
|
||||||
|
}
|
||||||
|
await writeJsonFile(this.policiesFile, obj);
|
||||||
|
} catch (err) {
|
||||||
|
this.log.error('auto-restart', 'Failed to save policies', { error: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Helpers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a notification via the notification manager.
|
||||||
|
*
|
||||||
|
* @param {string} event - Event type (e.g. 'auto-restart')
|
||||||
|
* @param {Object} data - Notification payload
|
||||||
|
* @returns {Promise<Object>}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async _notify(event, data) {
|
||||||
|
if (this.notification?.send) {
|
||||||
|
return this.notification.send(event, data);
|
||||||
|
}
|
||||||
|
return { success: false, reason: 'no-notification-manager' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { AutoRestartManager, DEFAULT_POLICY };
|
||||||
@@ -20,6 +20,14 @@ class BackupManager extends EventEmitter {
|
|||||||
this.history = this.loadHistory();
|
this.history = this.loadHistory();
|
||||||
this.scheduledJobs = new Map();
|
this.scheduledJobs = new Map();
|
||||||
this.running = false;
|
this.running = false;
|
||||||
|
this.notificationManager = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the notification manager for sending backup notifications
|
||||||
|
*/
|
||||||
|
setNotificationManager(nm) {
|
||||||
|
this.notificationManager = nm;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -177,6 +185,14 @@ class BackupManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.emit('backup-complete', historyEntry);
|
this.emit('backup-complete', historyEntry);
|
||||||
|
|
||||||
|
// Send notification if manager is configured
|
||||||
|
if (this.notificationManager) {
|
||||||
|
this.notificationManager.sendBackupComplete(historyEntry).catch(err => {
|
||||||
|
console.error('[BackupManager] Failed to send backup-complete notification:', err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`[BackupManager] Backup ${name} completed in ${duration}ms`);
|
console.log(`[BackupManager] Backup ${name} completed in ${duration}ms`);
|
||||||
|
|
||||||
return historyEntry;
|
return historyEntry;
|
||||||
@@ -194,6 +210,13 @@ class BackupManager extends EventEmitter {
|
|||||||
this.addToHistory(historyEntry);
|
this.addToHistory(historyEntry);
|
||||||
this.emit('backup-failed', historyEntry);
|
this.emit('backup-failed', historyEntry);
|
||||||
|
|
||||||
|
// Send notification if manager is configured
|
||||||
|
if (this.notificationManager) {
|
||||||
|
this.notificationManager.sendBackupFailed(historyEntry).catch(err => {
|
||||||
|
console.error('[BackupManager] Failed to send backup-failed notification:', err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,575 @@
|
|||||||
|
/**
|
||||||
|
* Bundled Workflows - Pre-configured automation templates
|
||||||
|
*
|
||||||
|
* Workflows attach to events (container-down, pre-update, resource-alert, scheduled)
|
||||||
|
* and execute a sequence of actions when triggered.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const WORKFLOWS_FILE = process.env.WORKFLOWS_FILE || path.join(__dirname, 'workflows-config.json');
|
||||||
|
const WORKFLOW_HISTORY_FILE = process.env.WORKFLOW_HISTORY_FILE || path.join(__dirname, 'workflow-history.json');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bundled workflow templates
|
||||||
|
*/
|
||||||
|
const BUNDLED_WORKFLOWS = {
|
||||||
|
'auto-restart-on-crash': {
|
||||||
|
id: 'auto-restart-on-crash',
|
||||||
|
name: 'Auto-Restart on Crash',
|
||||||
|
description: 'Automatically restart a container when it goes down',
|
||||||
|
trigger: 'container-down',
|
||||||
|
actions: [
|
||||||
|
{ type: 'docker-restart', containerId: '{{containerId}}' },
|
||||||
|
{ type: 'notify', message: 'Container {{containerId}} restarted automatically' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
'backup-before-update': {
|
||||||
|
id: 'backup-before-update',
|
||||||
|
name: 'Backup Before Update',
|
||||||
|
description: 'Create a backup before any app update',
|
||||||
|
trigger: 'pre-update',
|
||||||
|
actions: [
|
||||||
|
{ type: 'backup-create', appId: '{{appId}}', label: 'pre-update' },
|
||||||
|
{ type: 'notify', message: 'Backup created before updating {{appId}}' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
'health-check-on-interval': {
|
||||||
|
id: 'health-check-on-interval',
|
||||||
|
name: 'Periodic Health Check',
|
||||||
|
description: 'Run health checks every 15 minutes and alert if degraded',
|
||||||
|
trigger: 'scheduled',
|
||||||
|
interval: 15 * 60 * 1000, // 15 minutes
|
||||||
|
actions: [
|
||||||
|
{ type: 'health-check', target: '{{serviceId}}' },
|
||||||
|
{ type: 'notify-on-failure', message: 'Health check failed for {{serviceId}}' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
'disk-space-alert': {
|
||||||
|
id: 'disk-space-alert',
|
||||||
|
name: 'Disk Space Alert',
|
||||||
|
description: 'Alert when disk usage exceeds 80%',
|
||||||
|
trigger: 'resource-alert',
|
||||||
|
condition: 'diskPercent > 80',
|
||||||
|
actions: [
|
||||||
|
{ type: 'notify', message: '⚠️ Disk usage at {{diskPercent}}% on {{host}}' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
'weekly-container-report': {
|
||||||
|
id: 'weekly-container-report',
|
||||||
|
name: 'Weekly Container Report',
|
||||||
|
description: 'Send a weekly summary of container status and resource usage',
|
||||||
|
trigger: 'scheduled',
|
||||||
|
interval: 7 * 24 * 60 * 60 * 1000, // weekly
|
||||||
|
actions: [
|
||||||
|
{ type: 'collect-metrics', period: '7d' },
|
||||||
|
{ type: 'notify', message: '{{report}}' }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WorkflowEngine - Executes bundled workflows
|
||||||
|
*/
|
||||||
|
class WorkflowEngine extends EventEmitter {
|
||||||
|
constructor(ctx) {
|
||||||
|
super();
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.enabled = new Map();
|
||||||
|
this.history = [];
|
||||||
|
this.scheduledJobs = new Map();
|
||||||
|
|
||||||
|
this.loadConfig();
|
||||||
|
this.loadHistory();
|
||||||
|
this.startScheduledWorkflows();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load enabled/disabled state for workflows
|
||||||
|
*/
|
||||||
|
loadConfig() {
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(WORKFLOWS_FILE)) {
|
||||||
|
const data = JSON.parse(fs.readFileSync(WORKFLOWS_FILE, 'utf8'));
|
||||||
|
this.enabled = new Map(Object.entries(data.enabled || {}));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[WorkflowEngine] Error loading config:', error.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default all workflows to enabled if not explicitly set
|
||||||
|
for (const [id, workflow] of Object.entries(BUNDLED_WORKFLOWS)) {
|
||||||
|
if (!this.enabled.has(id)) {
|
||||||
|
this.enabled.set(id, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save enabled/disabled state
|
||||||
|
*/
|
||||||
|
saveConfig() {
|
||||||
|
try {
|
||||||
|
const data = {
|
||||||
|
enabled: Object.fromEntries(this.enabled)
|
||||||
|
};
|
||||||
|
fs.writeFileSync(WORKFLOWS_FILE, JSON.stringify(data, null, 2));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[WorkflowEngine] Error saving config:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load execution history
|
||||||
|
*/
|
||||||
|
loadHistory() {
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(WORKFLOW_HISTORY_FILE)) {
|
||||||
|
this.history = JSON.parse(fs.readFileSync(WORKFLOW_HISTORY_FILE, 'utf8'));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[WorkflowEngine] Error loading history:', error.message);
|
||||||
|
this.history = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save execution history
|
||||||
|
*/
|
||||||
|
saveHistory() {
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(WORKFLOW_HISTORY_FILE, JSON.stringify(this.history, null, 2));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[WorkflowEngine] Error saving history:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start scheduled workflows
|
||||||
|
*/
|
||||||
|
startScheduledWorkflows() {
|
||||||
|
for (const [id, workflow] of Object.entries(BUNDLED_WORKFLOWS)) {
|
||||||
|
if (workflow.trigger === 'scheduled' && workflow.interval) {
|
||||||
|
this.startScheduledWorkflow(id, workflow);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start a scheduled workflow
|
||||||
|
*/
|
||||||
|
startScheduledWorkflow(workflowId, workflow) {
|
||||||
|
if (!this.enabled.get(workflowId)) return;
|
||||||
|
|
||||||
|
// Clear existing job if any
|
||||||
|
this.stopScheduledWorkflow(workflowId);
|
||||||
|
|
||||||
|
const job = setInterval(() => {
|
||||||
|
this.executeWorkflow(workflowId, { trigger: 'scheduled', timestamp: new Date().toISOString() })
|
||||||
|
.catch(err => console.error(`[WorkflowEngine] Scheduled workflow ${workflowId} failed:`, err.message));
|
||||||
|
}, workflow.interval);
|
||||||
|
|
||||||
|
this.scheduledJobs.set(workflowId, job);
|
||||||
|
console.log(`[WorkflowEngine] Scheduled workflow '${workflowId}' every ${workflow.interval}ms`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop a scheduled workflow
|
||||||
|
*/
|
||||||
|
stopScheduledWorkflow(workflowId) {
|
||||||
|
if (this.scheduledJobs.has(workflowId)) {
|
||||||
|
clearInterval(this.scheduledJobs.get(workflowId));
|
||||||
|
this.scheduledJobs.delete(workflowId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a workflow by ID
|
||||||
|
*/
|
||||||
|
async executeWorkflow(workflowId, triggerData = {}) {
|
||||||
|
const workflow = BUNDLED_WORKFLOWS[workflowId];
|
||||||
|
if (!workflow) {
|
||||||
|
throw new Error(`Unknown workflow: ${workflowId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.enabled.get(workflowId)) {
|
||||||
|
console.log(`[WorkflowEngine] Workflow ${workflowId} is disabled, skipping`);
|
||||||
|
return { skipped: true, reason: 'disabled' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const executionId = `${workflowId}-${Date.now()}`;
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
console.log(`[WorkflowEngine] Executing workflow: ${workflowId}`);
|
||||||
|
this.emit('workflow-start', { workflowId, executionId, triggerData });
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
for (const action of workflow.actions) {
|
||||||
|
try {
|
||||||
|
const result = await this.executeAction(action, triggerData);
|
||||||
|
results.push({ action: action.type, success: true, result });
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`[WorkflowEngine] Action ${action.type} failed:`, error.message);
|
||||||
|
results.push({ action: action.type, success: false, error: error.message });
|
||||||
|
// Continue with other actions but log failure
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const duration = Date.now() - startTime;
|
||||||
|
const allSucceeded = results.every(r => r.success);
|
||||||
|
|
||||||
|
const historyEntry = {
|
||||||
|
executionId,
|
||||||
|
workflowId,
|
||||||
|
workflowName: workflow.name,
|
||||||
|
trigger: triggerData.trigger || 'manual',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
duration,
|
||||||
|
success: allSucceeded,
|
||||||
|
results
|
||||||
|
};
|
||||||
|
|
||||||
|
this.history.push(historyEntry);
|
||||||
|
|
||||||
|
// Keep history to last 500 entries
|
||||||
|
if (this.history.length > 500) {
|
||||||
|
this.history = this.history.slice(-500);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.saveHistory();
|
||||||
|
|
||||||
|
this.emit('workflow-complete', historyEntry);
|
||||||
|
console.log(`[WorkflowEngine] Workflow ${workflowId} completed in ${duration}ms, success: ${allSucceeded}`);
|
||||||
|
|
||||||
|
return historyEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a single action
|
||||||
|
*/
|
||||||
|
async executeAction(action, context) {
|
||||||
|
switch (action.type) {
|
||||||
|
case 'docker-restart':
|
||||||
|
return this.restartContainer(this.interpolate(action.containerId, context));
|
||||||
|
|
||||||
|
case 'backup-create':
|
||||||
|
return this.createBackup(
|
||||||
|
this.interpolate(action.appId, context),
|
||||||
|
action.label
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'notify':
|
||||||
|
return this.notify(
|
||||||
|
this.interpolate(action.message, context),
|
||||||
|
action.channel
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'notify-on-failure':
|
||||||
|
// Only send if previous action failed
|
||||||
|
return this.notify(
|
||||||
|
this.interpolate(action.message, context),
|
||||||
|
action.channel
|
||||||
|
);
|
||||||
|
|
||||||
|
case 'health-check':
|
||||||
|
return this.healthCheckService(this.interpolate(action.target, context));
|
||||||
|
|
||||||
|
case 'collect-metrics':
|
||||||
|
return this.collectMetrics(context.containerId, action.period);
|
||||||
|
|
||||||
|
default:
|
||||||
|
console.warn(`[WorkflowEngine] Unknown action type: ${action.type}`);
|
||||||
|
return { skipped: true, reason: `Unknown action type: ${action.type}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interpolate template variables in a string
|
||||||
|
*/
|
||||||
|
interpolate(str, context) {
|
||||||
|
if (!str || typeof str !== 'string') return str;
|
||||||
|
|
||||||
|
return str.replace(/\{\{(\w+)\}\}/g, (match, key) => {
|
||||||
|
return context[key] !== undefined ? context[key] : match;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Health check action
|
||||||
|
*/
|
||||||
|
async healthCheckService(serviceId) {
|
||||||
|
if (!serviceId || serviceId === '{{serviceId}}') {
|
||||||
|
// Run health check on all services
|
||||||
|
const results = [];
|
||||||
|
const servicesStateManager = this.ctx.servicesStateManager;
|
||||||
|
if (servicesStateManager) {
|
||||||
|
const services = servicesStateManager.getState() || [];
|
||||||
|
for (const service of services) {
|
||||||
|
if (service.containerId) {
|
||||||
|
try {
|
||||||
|
const healthy = await this.checkContainerHealth(service.containerId);
|
||||||
|
results.push({ service: service.id, healthy });
|
||||||
|
} catch (e) {
|
||||||
|
results.push({ service: service.id, healthy: false, error: e.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { checked: results.length, healthy: results.filter(r => r.healthy).length, results };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Single service check
|
||||||
|
const healthy = await this.checkContainerHealth(serviceId);
|
||||||
|
return { serviceId, healthy };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a container is healthy
|
||||||
|
*/
|
||||||
|
async checkContainerHealth(containerId) {
|
||||||
|
try {
|
||||||
|
const docker = this.ctx.docker?.client;
|
||||||
|
if (!docker) return false;
|
||||||
|
|
||||||
|
const container = docker.getContainer(containerId);
|
||||||
|
const info = await container.inspect();
|
||||||
|
return info.State && info.State.Running && info.State.Health !== 'unhealthy';
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Docker restart action
|
||||||
|
*/
|
||||||
|
async restartContainer(containerId) {
|
||||||
|
const docker = this.ctx.docker?.client;
|
||||||
|
if (!docker) {
|
||||||
|
throw new Error('Docker client not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!containerId || containerId === '{{containerId}}') {
|
||||||
|
throw new Error('Container ID not provided');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[WorkflowEngine] Restarting container: ${containerId}`);
|
||||||
|
const container = docker.getContainer(containerId);
|
||||||
|
await container.restart();
|
||||||
|
|
||||||
|
return { restarted: containerId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Backup create action
|
||||||
|
*/
|
||||||
|
async createBackup(appId, label = 'workflow') {
|
||||||
|
const backupManager = this.ctx.backupManager;
|
||||||
|
if (!backupManager) {
|
||||||
|
throw new Error('Backup manager not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!appId || appId === '{{appId}}') {
|
||||||
|
throw new Error('App ID not provided');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[WorkflowEngine] Creating backup for: ${appId}`);
|
||||||
|
|
||||||
|
// Use backup manager's executeBackup if available
|
||||||
|
const backupName = `${appId}-${label}`;
|
||||||
|
const backupConfig = backupManager.config?.backups?.[appId];
|
||||||
|
|
||||||
|
if (backupConfig) {
|
||||||
|
const result = await backupManager.executeBackup(backupName, backupConfig);
|
||||||
|
return { backupId: result.backupId, appId, label };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: trigger manual backup via backup manager
|
||||||
|
if (backupManager.executeBackup) {
|
||||||
|
const result = await backupManager.executeBackup(appId, {
|
||||||
|
include: ['config', 'data'],
|
||||||
|
schedule: 'manual'
|
||||||
|
});
|
||||||
|
return { backupId: result.backupId, appId, label };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Backup execution not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify action
|
||||||
|
*/
|
||||||
|
async notify(message, channel) {
|
||||||
|
const notification = this.ctx.notification;
|
||||||
|
if (!notification) {
|
||||||
|
console.warn('[WorkflowEngine] Notification manager not available');
|
||||||
|
return { notified: false, reason: 'no notification manager' };
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[WorkflowEngine] Sending notification: ${message}`);
|
||||||
|
notification.send('workflow', 'Workflow Notification', message, 'info');
|
||||||
|
|
||||||
|
return { notified: true, message };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collect metrics action
|
||||||
|
*/
|
||||||
|
async collectMetrics(containerId, period = '7d') {
|
||||||
|
const resourceMonitor = this.ctx.resourceMonitor;
|
||||||
|
if (!resourceMonitor) {
|
||||||
|
throw new Error('Resource monitor not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get aggregated stats
|
||||||
|
const stats = resourceMonitor.getAllStats();
|
||||||
|
|
||||||
|
// Build report
|
||||||
|
let report = `# Weekly Container Report\n\n`;
|
||||||
|
report += `Generated: ${new Date().toLocaleString()}\n\n`;
|
||||||
|
|
||||||
|
for (const [id, info] of Object.entries(stats)) {
|
||||||
|
const agg = info.aggregated;
|
||||||
|
report += `## ${info.name || id}\n`;
|
||||||
|
report += `- Status: ${info.current?.status || 'unknown'}\n`;
|
||||||
|
if (agg) {
|
||||||
|
report += `- CPU: avg ${agg.cpu?.avg?.toFixed(1)}%, max ${agg.cpu?.max?.toFixed(1)}%\n`;
|
||||||
|
report += `- Memory: avg ${agg.memory?.avg?.toFixed(1)}%, max ${agg.memory?.max?.toFixed(1)}%\n`;
|
||||||
|
}
|
||||||
|
report += '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
return { report, containerCount: Object.keys(stats).length };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all available workflows
|
||||||
|
*/
|
||||||
|
listWorkflows() {
|
||||||
|
return Object.entries(BUNDLED_WORKFLOWS).map(([id, workflow]) => ({
|
||||||
|
...workflow,
|
||||||
|
enabled: this.enabled.get(id) ?? true
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable or disable a workflow
|
||||||
|
*/
|
||||||
|
setWorkflowEnabled(workflowId, enabled) {
|
||||||
|
if (!BUNDLED_WORKFLOWS[workflowId]) {
|
||||||
|
throw new Error(`Unknown workflow: ${workflowId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.enabled.set(workflowId, enabled);
|
||||||
|
this.saveConfig();
|
||||||
|
|
||||||
|
// Handle scheduled workflows
|
||||||
|
const workflow = BUNDLED_WORKFLOWS[workflowId];
|
||||||
|
if (workflow.trigger === 'scheduled' && workflow.interval) {
|
||||||
|
if (enabled) {
|
||||||
|
this.startScheduledWorkflow(workflowId, workflow);
|
||||||
|
} else {
|
||||||
|
this.stopScheduledWorkflow(workflowId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[WorkflowEngine] Workflow ${workflowId} ${enabled ? 'enabled' : 'disabled'}`);
|
||||||
|
return { workflowId, enabled };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get execution history for a workflow
|
||||||
|
*/
|
||||||
|
getHistory(workflowId = null, limit = 50) {
|
||||||
|
let history = this.history;
|
||||||
|
|
||||||
|
if (workflowId) {
|
||||||
|
history = history.filter(h => h.workflowId === workflowId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return history.slice(-limit).reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger workflows for a specific event
|
||||||
|
*/
|
||||||
|
async triggerForEvent(eventType, eventData) {
|
||||||
|
const matchingWorkflows = Object.entries(BUNDLED_WORKFLOWS)
|
||||||
|
.filter(([id, workflow]) => {
|
||||||
|
if (workflow.trigger !== eventType) return false;
|
||||||
|
if (!this.enabled.get(id)) return false;
|
||||||
|
|
||||||
|
// Check condition if specified
|
||||||
|
if (workflow.condition && eventData) {
|
||||||
|
try {
|
||||||
|
// Simple condition evaluation
|
||||||
|
const conditionMet = this.evaluateCondition(workflow.condition, eventData);
|
||||||
|
return conditionMet;
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`[WorkflowEngine] Condition evaluation failed for ${id}:`, e.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
for (const [workflowId, workflow] of matchingWorkflows) {
|
||||||
|
try {
|
||||||
|
const result = await this.executeWorkflow(workflowId, {
|
||||||
|
trigger: eventType,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
...eventData
|
||||||
|
});
|
||||||
|
results.push({ workflowId, success: true, result });
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ workflowId, success: false, error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evaluate a simple condition string
|
||||||
|
*/
|
||||||
|
evaluateCondition(condition, data) {
|
||||||
|
// Simple condition like "diskPercent > 80"
|
||||||
|
// Supports: >, <, >=, <=, ==, !=
|
||||||
|
const match = condition.match(/^(\w+)\s*(>=|<=|==|!=|>|<)\s*(\S+)$/);
|
||||||
|
if (!match) return true;
|
||||||
|
|
||||||
|
const [, field, operator, value] = match;
|
||||||
|
const fieldValue = data[field];
|
||||||
|
|
||||||
|
if (fieldValue === undefined) return false;
|
||||||
|
|
||||||
|
const numValue = parseFloat(value);
|
||||||
|
const numFieldValue = parseFloat(fieldValue);
|
||||||
|
|
||||||
|
switch (operator) {
|
||||||
|
case '>': return numFieldValue > numValue;
|
||||||
|
case '<': return numFieldValue < numValue;
|
||||||
|
case '>=': return numFieldValue >= numValue;
|
||||||
|
case '<=': return numFieldValue <= numValue;
|
||||||
|
case '==': return fieldValue == value;
|
||||||
|
case '!=': return fieldValue != value;
|
||||||
|
default: return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop all scheduled workflows
|
||||||
|
*/
|
||||||
|
stop() {
|
||||||
|
for (const [workflowId] of this.scheduledJobs) {
|
||||||
|
this.stopScheduledWorkflow(workflowId);
|
||||||
|
}
|
||||||
|
console.log('[WorkflowEngine] All scheduled workflows stopped');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { WorkflowEngine, BUNDLED_WORKFLOWS };
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
/**
|
||||||
|
* Config Drift Detector - Compares services.json with live Docker state
|
||||||
|
*
|
||||||
|
* Detects discrepancies between the configured service list and what is
|
||||||
|
* actually running in Docker, including missing containers, unknown
|
||||||
|
* containers, port mismatches, state mismatches, and stale records.
|
||||||
|
*
|
||||||
|
* @module config-drift-detector
|
||||||
|
*/
|
||||||
|
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} DriftReport
|
||||||
|
* @property {string} checkedAt - ISO timestamp of the check
|
||||||
|
* @property {Object[]} missingContainers - Services with containerId but container absent in Docker
|
||||||
|
* @property {Object[]} unknownContainers - Running Docker containers with sami.managed label but not in services.json
|
||||||
|
* @property {Object[]} portMismatch - Service port != container mapped port
|
||||||
|
* @property {Object[]} stateMismatch - Service expected up but container stopped/absent
|
||||||
|
* @property {Object[]} staleRecords - Services with containerId pointing to removed containers
|
||||||
|
* @property {boolean} hasDrift - Whether any drift category is non-empty
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detects and reports configuration drift between services.json and Docker.
|
||||||
|
*
|
||||||
|
* @extends EventEmitter
|
||||||
|
*
|
||||||
|
* @fires ConfigDriftDetector#drift-detected
|
||||||
|
*/
|
||||||
|
class ConfigDriftDetector extends EventEmitter {
|
||||||
|
/**
|
||||||
|
* @param {Object} ctx - Shared application context
|
||||||
|
* @param {Object} ctx.docker - Docker client wrapper ({ client: Dockerode })
|
||||||
|
* @param {Object} ctx.servicesStateManager - StateManager for services.json
|
||||||
|
* @param {Object} ctx.notification - NotificationManager instance
|
||||||
|
* @param {Object} ctx.log - Logger instance
|
||||||
|
* @param {Function} ctx.logError - Error logging function
|
||||||
|
*/
|
||||||
|
constructor(ctx) {
|
||||||
|
super();
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.log = ctx.log || console;
|
||||||
|
this.logError = ctx.logError || ((_c, err) => console.error(err));
|
||||||
|
this.docker = ctx.docker;
|
||||||
|
this.servicesStateManager = ctx.servicesStateManager;
|
||||||
|
this.notification = ctx.notification;
|
||||||
|
|
||||||
|
/** @type {DriftReport|null} Cached report from last detection */
|
||||||
|
this.lastReport = null;
|
||||||
|
|
||||||
|
/** @type {NodeJS.Timeout|null} Polling timer reference */
|
||||||
|
this._pollTimer = null;
|
||||||
|
|
||||||
|
/** Whether polling is currently active */
|
||||||
|
this._polling = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Detection ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a full drift detection and return the report.
|
||||||
|
*
|
||||||
|
* Reads services from servicesStateManager and live containers from Docker,
|
||||||
|
* then compares them across five drift categories.
|
||||||
|
*
|
||||||
|
* @returns {Promise<DriftReport>}
|
||||||
|
*/
|
||||||
|
async detect() {
|
||||||
|
const checkedAt = new Date().toISOString();
|
||||||
|
|
||||||
|
// Gather configured services
|
||||||
|
let services = [];
|
||||||
|
try {
|
||||||
|
const data = await this.servicesStateManager.read();
|
||||||
|
services = Array.isArray(data) ? data : (data.services || []);
|
||||||
|
} catch (err) {
|
||||||
|
this.log.error('drift', 'Failed to read services', { error: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gather live Docker containers
|
||||||
|
let containers = [];
|
||||||
|
try {
|
||||||
|
containers = await this.docker.client.listContainers({ all: true });
|
||||||
|
} catch (err) {
|
||||||
|
this.log.error('drift', 'Failed to list containers', { error: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build lookup maps
|
||||||
|
const containerById = new Map(); // containerId (short or long) → container info
|
||||||
|
const containerByName = new Map(); // container name → container info
|
||||||
|
|
||||||
|
for (const c of containers) {
|
||||||
|
// Store by full ID
|
||||||
|
containerById.set(c.Id, c);
|
||||||
|
// Store by short ID (first 12 chars)
|
||||||
|
if (c.Id && c.Id.length >= 12) {
|
||||||
|
containerById.set(c.Id.substring(0, 12), c);
|
||||||
|
}
|
||||||
|
// Store by name (strip leading /)
|
||||||
|
for (const name of (c.Names || [])) {
|
||||||
|
containerByName.set(name.replace(/^\//, ''), c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build set of service containerIds for reverse lookup
|
||||||
|
const serviceContainerIds = new Set();
|
||||||
|
const serviceByContainerId = new Map();
|
||||||
|
|
||||||
|
for (const svc of services) {
|
||||||
|
if (svc.containerId) {
|
||||||
|
serviceContainerIds.add(svc.containerId);
|
||||||
|
// Index by both full and short ID
|
||||||
|
serviceByContainerId.set(svc.containerId, svc);
|
||||||
|
if (svc.containerId.length >= 12) {
|
||||||
|
serviceByContainerId.set(svc.containerId.substring(0, 12), svc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const missingContainers = [];
|
||||||
|
const portMismatch = [];
|
||||||
|
const stateMismatch = [];
|
||||||
|
const staleRecords = [];
|
||||||
|
|
||||||
|
for (const svc of services) {
|
||||||
|
if (!svc.containerId) continue;
|
||||||
|
|
||||||
|
// Look up the container
|
||||||
|
const container = containerById.get(svc.containerId)
|
||||||
|
|| containerById.get(svc.containerId.substring(0, 12));
|
||||||
|
|
||||||
|
if (!container) {
|
||||||
|
// Container ID referenced but not found in Docker at all
|
||||||
|
staleRecords.push({
|
||||||
|
serviceId: svc.id,
|
||||||
|
name: svc.name,
|
||||||
|
containerId: svc.containerId,
|
||||||
|
reason: 'Container not found in Docker',
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Missing container — service expects it but it's not running
|
||||||
|
if (container.State !== 'running') {
|
||||||
|
missingContainers.push({
|
||||||
|
serviceId: svc.id,
|
||||||
|
name: svc.name,
|
||||||
|
containerId: svc.containerId,
|
||||||
|
containerState: container.State,
|
||||||
|
containerStatus: container.Status,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Also a state mismatch if the service is expected to be up
|
||||||
|
stateMismatch.push({
|
||||||
|
serviceId: svc.id,
|
||||||
|
name: svc.name,
|
||||||
|
expectedState: 'running',
|
||||||
|
actualState: container.State,
|
||||||
|
containerId: svc.containerId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Port mismatch detection
|
||||||
|
if (svc.port && container.State === 'running') {
|
||||||
|
const actualPorts = this._extractContainerPorts(container);
|
||||||
|
if (actualPorts.length > 0 && !actualPorts.includes(svc.port)) {
|
||||||
|
portMismatch.push({
|
||||||
|
serviceId: svc.id,
|
||||||
|
name: svc.name,
|
||||||
|
configuredPort: svc.port,
|
||||||
|
actualPorts,
|
||||||
|
containerId: svc.containerId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unknown managed containers: Docker containers with sami.managed label
|
||||||
|
// that are NOT in services.json
|
||||||
|
const unknownContainers = [];
|
||||||
|
for (const c of containers) {
|
||||||
|
const isManaged = c.Labels && c.Labels['sami.managed'] === 'true';
|
||||||
|
if (!isManaged) continue;
|
||||||
|
|
||||||
|
const isInServices = serviceByContainerId.has(c.Id)
|
||||||
|
|| serviceByContainerId.has(c.Id.substring(0, 12));
|
||||||
|
|
||||||
|
if (!isInServices) {
|
||||||
|
unknownContainers.push({
|
||||||
|
containerId: c.Id,
|
||||||
|
name: (c.Names && c.Names[0] || '').replace(/^\//, ''),
|
||||||
|
image: c.Image,
|
||||||
|
state: c.State,
|
||||||
|
status: c.Status,
|
||||||
|
app: c.Labels?.['sami.app'] || null,
|
||||||
|
subdomain: c.Labels?.['sami.subdomain'] || null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
|
checkedAt,
|
||||||
|
missingContainers,
|
||||||
|
unknownContainers,
|
||||||
|
portMismatch,
|
||||||
|
stateMismatch,
|
||||||
|
staleRecords,
|
||||||
|
hasDrift: missingContainers.length > 0
|
||||||
|
|| unknownContainers.length > 0
|
||||||
|
|| portMismatch.length > 0
|
||||||
|
|| stateMismatch.length > 0
|
||||||
|
|| staleRecords.length > 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cache for quick API access
|
||||||
|
this.lastReport = report;
|
||||||
|
|
||||||
|
// Emit and notify if drift detected
|
||||||
|
if (report.hasDrift) {
|
||||||
|
/**
|
||||||
|
* @event ConfigDriftDetector#drift-detected
|
||||||
|
* @type {DriftReport}
|
||||||
|
*/
|
||||||
|
this.emit('drift-detected', report);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this._sendDriftNotification(report);
|
||||||
|
} catch (notifErr) {
|
||||||
|
this.log.error('drift', 'Failed to send drift notification', {
|
||||||
|
error: notifErr.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.log.info('drift', 'Detection complete', {
|
||||||
|
hasDrift: report.hasDrift,
|
||||||
|
missing: report.missingContainers.length,
|
||||||
|
unknown: report.unknownContainers.length,
|
||||||
|
portMismatch: report.portMismatch.length,
|
||||||
|
stateMismatch: report.stateMismatch.length,
|
||||||
|
stale: report.staleRecords.length,
|
||||||
|
});
|
||||||
|
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Auto-fix ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempt to auto-fix drift:
|
||||||
|
* - Remove stale records (services referencing removed containers)
|
||||||
|
* - Flag unknown containers for review
|
||||||
|
*
|
||||||
|
* @returns {Promise<{ staleRemoved: number, unknownFlagged: number }>}
|
||||||
|
*/
|
||||||
|
async autoFix() {
|
||||||
|
const report = await this.detect();
|
||||||
|
let staleRemoved = 0;
|
||||||
|
|
||||||
|
// Remove stale records from services.json
|
||||||
|
if (report.staleRecords.length > 0) {
|
||||||
|
const staleIds = new Set(report.staleRecords.map(r => r.serviceId));
|
||||||
|
await this.servicesStateManager.update(services => {
|
||||||
|
const before = services.length;
|
||||||
|
const cleaned = services.filter(s => !staleIds.has(s.id));
|
||||||
|
staleRemoved = before - cleaned.length;
|
||||||
|
return cleaned;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const unknownFlagged = report.unknownContainers.length;
|
||||||
|
|
||||||
|
this.log.info('drift', 'Auto-fix applied', { staleRemoved, unknownFlagged });
|
||||||
|
|
||||||
|
return { staleRemoved, unknownFlagged };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Polling ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start periodic drift detection.
|
||||||
|
*
|
||||||
|
* @param {number} [intervalMs=300000] - Polling interval in milliseconds (default 5 min)
|
||||||
|
*/
|
||||||
|
startPolling(intervalMs = 300000) {
|
||||||
|
this.stopPolling();
|
||||||
|
|
||||||
|
this._polling = true;
|
||||||
|
this._pollTimer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
await this.detect();
|
||||||
|
} catch (err) {
|
||||||
|
this.logError('drift-poll', err);
|
||||||
|
}
|
||||||
|
}, intervalMs);
|
||||||
|
|
||||||
|
this.log.info('drift', 'Polling started', { intervalMs });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop periodic drift detection.
|
||||||
|
*/
|
||||||
|
stopPolling() {
|
||||||
|
if (this._pollTimer) {
|
||||||
|
clearInterval(this._pollTimer);
|
||||||
|
this._pollTimer = null;
|
||||||
|
}
|
||||||
|
this._polling = false;
|
||||||
|
this.log.info('drift', 'Polling stopped');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether polling is currently active.
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
isPolling() {
|
||||||
|
return this._polling;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Helpers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract mapped host ports from a Docker container info object.
|
||||||
|
*
|
||||||
|
* @param {Object} container - Dockerode container info
|
||||||
|
* @returns {number[]} Array of host port numbers
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_extractContainerPorts(container) {
|
||||||
|
const ports = [];
|
||||||
|
if (!container.Ports) return ports;
|
||||||
|
|
||||||
|
for (const p of container.Ports) {
|
||||||
|
if (p.PublicPort) {
|
||||||
|
ports.push(p.PublicPort);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ports;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a notification about detected drift.
|
||||||
|
*
|
||||||
|
* @param {DriftReport} report
|
||||||
|
* @returns {Promise<Object>}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async _sendDriftNotification(report) {
|
||||||
|
if (!this.notification?.send) {
|
||||||
|
return { success: false, reason: 'no-notification-manager' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = [];
|
||||||
|
if (report.missingContainers.length > 0) {
|
||||||
|
parts.push(`Missing containers: ${report.missingContainers.map(c => c.name).join(', ')}`);
|
||||||
|
}
|
||||||
|
if (report.unknownContainers.length > 0) {
|
||||||
|
parts.push(`Unknown managed containers: ${report.unknownContainers.map(c => c.name).join(', ')}`);
|
||||||
|
}
|
||||||
|
if (report.portMismatch.length > 0) {
|
||||||
|
parts.push(`Port mismatches: ${report.portMismatch.map(c => c.name).join(', ')}`);
|
||||||
|
}
|
||||||
|
if (report.staleRecords.length > 0) {
|
||||||
|
parts.push(`Stale records: ${report.staleRecords.map(c => c.name).join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.notification.send('drift-detected', {
|
||||||
|
text: `⚠️ Configuration drift detected:\n${parts.join('\n')}`,
|
||||||
|
report,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { ConfigDriftDetector };
|
||||||
@@ -59,6 +59,15 @@ function validateConfig(config) {
|
|||||||
errors.push('dns.servers must be an object');
|
errors.push('dns.servers must be an object');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// DNS provider validation
|
||||||
|
if (config.dns.provider !== undefined) {
|
||||||
|
const validProviders = ['technitium', 'cloudflare', 'rfc2136', 'manual'];
|
||||||
|
if (typeof config.dns.provider !== 'string') {
|
||||||
|
errors.push('dns.provider must be a string');
|
||||||
|
} else if (!validProviders.includes(config.dns.provider)) {
|
||||||
|
warnings.push(`dns.provider "${config.dns.provider}" is not one of: ${validProviders.join(', ')}. It may still work if a custom adapter is installed.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ const DNS_RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SRV', 'PTR',
|
|||||||
// ── Docker ──────────────────────────────────────────────────────
|
// ── Docker ──────────────────────────────────────────────────────
|
||||||
const DOCKER = {
|
const DOCKER = {
|
||||||
CONTAINER_PREFIX: 'sami-',
|
CONTAINER_PREFIX: 'sami-',
|
||||||
TIMEOUT: 30000, // 30s — timeout for docker pull/create operations
|
TIMEOUT: 300000, // 300s — timeout for docker pull/create operations
|
||||||
LOG_CONFIG: {
|
LOG_CONFIG: {
|
||||||
Type: 'json-file',
|
Type: 'json-file',
|
||||||
Config: { 'max-size': '10m', 'max-file': '3' } // 30MB max per container
|
Config: { 'max-size': '10m', 'max-file': '3' } // 30MB max per container
|
||||||
|
|||||||
@@ -0,0 +1,605 @@
|
|||||||
|
/**
|
||||||
|
* Dependency Manager - Service dependency tracking with ordered restart chains
|
||||||
|
*
|
||||||
|
* Manages directed acyclic graph (DAG) of service dependencies. Services can
|
||||||
|
* declare which other services they depend on, and this manager provides:
|
||||||
|
* - Full dependency graph inspection
|
||||||
|
* - Topological ordering for safe restart chains
|
||||||
|
* - Circular dependency detection
|
||||||
|
* - Health-aware restart with per-service polling
|
||||||
|
*
|
||||||
|
* Dependencies are stored directly on service objects in services.json:
|
||||||
|
* { id, name, ..., dependsOn: ['service-id-1', 'service-id-2'] }
|
||||||
|
*
|
||||||
|
* @module dependency-manager
|
||||||
|
*/
|
||||||
|
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
|
||||||
|
/** Maximum seconds to wait for a single container to become healthy after restart */
|
||||||
|
const HEALTH_CHECK_TIMEOUT_MS = 30_000;
|
||||||
|
|
||||||
|
/** Interval between container health polls */
|
||||||
|
const HEALTH_CHECK_INTERVAL_MS = 1_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} ServiceNode
|
||||||
|
* @property {string} serviceId
|
||||||
|
* @property {string} name
|
||||||
|
* @property {string|null} containerId
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} DependencyEdge
|
||||||
|
* @property {string} from - The service that depends
|
||||||
|
* @property {string} to - The service being depended upon
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} DependencyGraph
|
||||||
|
* @property {ServiceNode[]} nodes
|
||||||
|
* @property {DependencyEdge[]} edges
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} DependencyStatusEntry
|
||||||
|
* @property {string} serviceId
|
||||||
|
* @property {string} name
|
||||||
|
* @property {boolean} isUp
|
||||||
|
* @property {string} [error]
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DependencyManager — tracks service dependencies and orchestrates ordered restarts.
|
||||||
|
*
|
||||||
|
* Events emitted:
|
||||||
|
* - `dependency-restart-start` ({ serviceId, chain: string[] })
|
||||||
|
* - `dependency-restart-progress` ({ serviceId, currentServiceId, index, total })
|
||||||
|
* - `dependency-restart-complete` ({ serviceId, chain: string[], results: Array })
|
||||||
|
* - `dependency-restart-failed` ({ serviceId, failedServiceId, error, chain: string[] })
|
||||||
|
*
|
||||||
|
* @extends EventEmitter
|
||||||
|
*/
|
||||||
|
class DependencyManager extends EventEmitter {
|
||||||
|
/**
|
||||||
|
* @param {Object} ctx - Application context
|
||||||
|
* @param {Object} ctx.servicesStateManager - StateManager for services.json
|
||||||
|
* @param {Object} ctx.docker - Docker context ({ client: Dockerode })
|
||||||
|
* @param {Object} ctx.notification - NotificationManager instance
|
||||||
|
* @param {Object} ctx.log - Logger instance
|
||||||
|
*/
|
||||||
|
constructor(ctx) {
|
||||||
|
super();
|
||||||
|
/** @private */
|
||||||
|
this.ctx = ctx;
|
||||||
|
/** @private */
|
||||||
|
this._servicesStateManager = ctx.servicesStateManager;
|
||||||
|
/** @private */
|
||||||
|
this._docker = ctx.docker;
|
||||||
|
/** @private */
|
||||||
|
this._notification = ctx.notification;
|
||||||
|
/** @private */
|
||||||
|
this._log = ctx.log || console;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Core helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load all services from the state manager.
|
||||||
|
* @private
|
||||||
|
* @returns {Promise<Object[]>}
|
||||||
|
*/
|
||||||
|
async _loadServices() {
|
||||||
|
const data = await this._servicesStateManager.read();
|
||||||
|
return Array.isArray(data) ? data : (data.services || []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a single service by ID.
|
||||||
|
* @private
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @returns {Promise<Object|null>}
|
||||||
|
*/
|
||||||
|
async _findService(serviceId) {
|
||||||
|
const services = await this._loadServices();
|
||||||
|
return services.find(s => s.id === serviceId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Graph queries
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the full dependency graph for visualisation.
|
||||||
|
*
|
||||||
|
* @returns {Promise<DependencyGraph>}
|
||||||
|
*/
|
||||||
|
async getDependencyGraph() {
|
||||||
|
const services = await this._loadServices();
|
||||||
|
|
||||||
|
const nodes = services.map(s => ({
|
||||||
|
serviceId: s.id,
|
||||||
|
name: s.name,
|
||||||
|
containerId: s.containerId || null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const edges = [];
|
||||||
|
for (const service of services) {
|
||||||
|
const deps = service.dependsOn || [];
|
||||||
|
for (const depId of deps) {
|
||||||
|
edges.push({ from: service.id, to: depId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { nodes, edges };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the services that depend on the given service (reverse deps).
|
||||||
|
*
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @returns {Promise<Object[]>} Services whose `dependsOn` includes `serviceId`.
|
||||||
|
*/
|
||||||
|
async getDependents(serviceId) {
|
||||||
|
const services = await this._loadServices();
|
||||||
|
return services.filter(s => (s.dependsOn || []).includes(serviceId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the direct dependencies for a service.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @returns {Promise<Object[]>} Services that `serviceId` depends on.
|
||||||
|
*/
|
||||||
|
async getDependencies(serviceId) {
|
||||||
|
const services = await this._loadServices();
|
||||||
|
const service = services.find(s => s.id === serviceId);
|
||||||
|
if (!service) return [];
|
||||||
|
const depIds = service.dependsOn || [];
|
||||||
|
return services.filter(s => depIds.includes(s.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Topological sort
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an adjacency list for the current dependency graph.
|
||||||
|
* Edge direction: service → its dependencies (i.e. what it depends on).
|
||||||
|
*
|
||||||
|
* @private
|
||||||
|
* @param {Object[]} services
|
||||||
|
* @returns {Map<string, string[]>}
|
||||||
|
*/
|
||||||
|
_buildAdjacencyList(services) {
|
||||||
|
const adj = new Map();
|
||||||
|
for (const service of services) {
|
||||||
|
adj.set(service.id, (service.dependsOn || []).slice());
|
||||||
|
}
|
||||||
|
return adj;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DFS-based topological sort with cycle detection (white/gray/black coloring).
|
||||||
|
*
|
||||||
|
* Returns services in restart order: dependencies first, dependents last.
|
||||||
|
* The target service is included at the end.
|
||||||
|
*
|
||||||
|
* @private
|
||||||
|
* @param {string} serviceId - Target service (will be last in the result).
|
||||||
|
* @param {Object[]} services - All services.
|
||||||
|
* @param {Map<string, string[]>} adj - Adjacency list (service → deps).
|
||||||
|
* @returns {string[]} Ordered service IDs for restart.
|
||||||
|
* @throws {Error} If a circular dependency is detected.
|
||||||
|
*/
|
||||||
|
_topologicalSort(serviceId, services, adj) {
|
||||||
|
// Collect only the reachable sub-graph from serviceId
|
||||||
|
const visited = new Set();
|
||||||
|
const reachable = new Set();
|
||||||
|
|
||||||
|
const collectReachable = (id) => {
|
||||||
|
if (reachable.has(id)) return;
|
||||||
|
reachable.add(id);
|
||||||
|
for (const dep of (adj.get(id) || [])) {
|
||||||
|
collectReachable(dep);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
collectReachable(serviceId);
|
||||||
|
|
||||||
|
// DFS topological sort on the reachable sub-graph
|
||||||
|
const WHITE = 0, GRAY = 1, BLACK = 2;
|
||||||
|
const color = new Map();
|
||||||
|
for (const id of reachable) color.set(id, WHITE);
|
||||||
|
|
||||||
|
const result = [];
|
||||||
|
|
||||||
|
const dfs = (id) => {
|
||||||
|
if (color.get(id) === BLACK) return;
|
||||||
|
if (color.get(id) === GRAY) {
|
||||||
|
throw new Error(`Circular dependency detected involving service "${id}"`);
|
||||||
|
}
|
||||||
|
color.set(id, GRAY);
|
||||||
|
for (const dep of (adj.get(id) || [])) {
|
||||||
|
dfs(dep);
|
||||||
|
}
|
||||||
|
color.set(id, BLACK);
|
||||||
|
result.push(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Visit the target last so it ends up at the end of the result
|
||||||
|
// Actually, we want deps *first* then the target.
|
||||||
|
// The DFS naturally puts deps before dependents, so starting from
|
||||||
|
// serviceId will place it last (which is correct for restart order).
|
||||||
|
dfs(serviceId);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the topologically ordered restart chain for a service.
|
||||||
|
*
|
||||||
|
* The returned array lists all services that must be restarted,
|
||||||
|
* starting with leaf dependencies and ending with the target service.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId - The service to build the chain for.
|
||||||
|
* @returns {Promise<string[]>} Ordered service IDs.
|
||||||
|
* @throws {Error} If `serviceId` doesn't exist or a circular dependency is found.
|
||||||
|
*/
|
||||||
|
async getOrderedRestartChain(serviceId) {
|
||||||
|
const services = await this._loadServices();
|
||||||
|
const service = services.find(s => s.id === serviceId);
|
||||||
|
if (!service) {
|
||||||
|
throw new Error(`Service "${serviceId}" not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const adj = this._buildAdjacencyList(services);
|
||||||
|
return this._topologicalSort(serviceId, services, adj);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Validation
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate a proposed set of dependencies for a service.
|
||||||
|
*
|
||||||
|
* Checks:
|
||||||
|
* - All referenced service IDs exist.
|
||||||
|
* - Adding these dependencies would not create a circular dependency.
|
||||||
|
* - A service cannot depend on itself.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId - The service to set dependencies on.
|
||||||
|
* @param {string[]} dependsOn - Proposed dependency IDs.
|
||||||
|
* @returns {Promise<{ valid: boolean, errors: string[] }>}
|
||||||
|
*/
|
||||||
|
async validateDependencies(serviceId, dependsOn) {
|
||||||
|
const errors = [];
|
||||||
|
|
||||||
|
if (!Array.isArray(dependsOn)) {
|
||||||
|
return { valid: false, errors: ['dependsOn must be an array'] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const services = await this._loadServices();
|
||||||
|
const allIds = new Set(services.map(s => s.id));
|
||||||
|
|
||||||
|
// Service must exist
|
||||||
|
if (!allIds.has(serviceId)) {
|
||||||
|
return { valid: false, errors: [`Service "${serviceId}" not found`] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-dependency
|
||||||
|
if (dependsOn.includes(serviceId)) {
|
||||||
|
errors.push(`Service "${serviceId}" cannot depend on itself`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Existence check
|
||||||
|
for (const depId of dependsOn) {
|
||||||
|
if (!allIds.has(depId)) {
|
||||||
|
errors.push(`Dependency service "${depId}" does not exist`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errors.length > 0) {
|
||||||
|
return { valid: false, errors };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Circular dependency check: temporarily set the proposed dependsOn
|
||||||
|
// and attempt a topological sort.
|
||||||
|
const tempServices = services.map(s => {
|
||||||
|
if (s.id === serviceId) {
|
||||||
|
return { ...s, dependsOn: dependsOn.slice() };
|
||||||
|
}
|
||||||
|
return { ...s };
|
||||||
|
});
|
||||||
|
|
||||||
|
const adj = this._buildAdjacencyList(tempServices);
|
||||||
|
|
||||||
|
// Check every node for cycles with the new edges
|
||||||
|
try {
|
||||||
|
const WHITE = 0, GRAY = 1, BLACK = 2;
|
||||||
|
const color = new Map();
|
||||||
|
for (const s of tempServices) color.set(s.id, WHITE);
|
||||||
|
|
||||||
|
const dfs = (id) => {
|
||||||
|
if (color.get(id) === BLACK) return;
|
||||||
|
if (color.get(id) === GRAY) {
|
||||||
|
throw new Error(`Circular dependency detected involving service "${id}"`);
|
||||||
|
}
|
||||||
|
color.set(id, GRAY);
|
||||||
|
for (const dep of (adj.get(id) || [])) {
|
||||||
|
dfs(dep);
|
||||||
|
}
|
||||||
|
color.set(id, BLACK);
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const s of tempServices) {
|
||||||
|
if (color.get(s.id) === WHITE) {
|
||||||
|
dfs(s.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
errors.push(err.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: errors.length === 0, errors };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Health status
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current container status for a service and all its transitive dependencies.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @returns {Promise<DependencyStatusEntry[]>}
|
||||||
|
* @throws {Error} If `serviceId` doesn't exist.
|
||||||
|
*/
|
||||||
|
async getDependencyStatus(serviceId) {
|
||||||
|
const services = await this._loadServices();
|
||||||
|
const service = services.find(s => s.id === serviceId);
|
||||||
|
if (!service) {
|
||||||
|
throw new Error(`Service "${serviceId}" not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect all transitive dependencies via BFS
|
||||||
|
const serviceMap = new Map(services.map(s => [s.id, s]));
|
||||||
|
const visited = new Set();
|
||||||
|
const queue = [serviceId];
|
||||||
|
const allRelated = [];
|
||||||
|
|
||||||
|
while (queue.length > 0) {
|
||||||
|
const currentId = queue.shift();
|
||||||
|
if (visited.has(currentId)) continue;
|
||||||
|
visited.add(currentId);
|
||||||
|
|
||||||
|
const svc = serviceMap.get(currentId);
|
||||||
|
if (!svc) continue;
|
||||||
|
|
||||||
|
allRelated.push(svc);
|
||||||
|
|
||||||
|
for (const depId of (svc.dependsOn || [])) {
|
||||||
|
if (!visited.has(depId)) {
|
||||||
|
queue.push(depId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Query container status for each
|
||||||
|
const results = [];
|
||||||
|
for (const svc of allRelated) {
|
||||||
|
const entry = {
|
||||||
|
serviceId: svc.id,
|
||||||
|
name: svc.name,
|
||||||
|
isUp: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!svc.containerId) {
|
||||||
|
entry.error = 'No container associated with this service';
|
||||||
|
results.push(entry);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const container = this._docker.client.getContainer(svc.containerId);
|
||||||
|
const info = await container.inspect();
|
||||||
|
entry.isUp = info.State?.Running === true;
|
||||||
|
} catch (err) {
|
||||||
|
entry.error = err.message || 'Unable to inspect container';
|
||||||
|
}
|
||||||
|
|
||||||
|
results.push(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Restart with dependencies
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wait for a container to report as running after a restart.
|
||||||
|
*
|
||||||
|
* @private
|
||||||
|
* @param {string} containerId
|
||||||
|
* @param {number} [timeoutMs=30000]
|
||||||
|
* @returns {Promise<boolean>} `true` if healthy, `false` if timed out.
|
||||||
|
*/
|
||||||
|
async _waitForContainerHealthy(containerId, timeoutMs = HEALTH_CHECK_TIMEOUT_MS) {
|
||||||
|
const start = Date.now();
|
||||||
|
while (Date.now() - start < timeoutMs) {
|
||||||
|
try {
|
||||||
|
const container = this._docker.client.getContainer(containerId);
|
||||||
|
const info = await container.inspect();
|
||||||
|
if (info.State?.Running === true) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Container might not be inspectable during restart — keep polling
|
||||||
|
}
|
||||||
|
await new Promise(r => setTimeout(r, HEALTH_CHECK_INTERVAL_MS));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restart a service and all its dependencies in topological order.
|
||||||
|
*
|
||||||
|
* Emits progress events and sends a notification on completion/failure.
|
||||||
|
* This method is designed to be called from the route handler and
|
||||||
|
* **does not throw** — errors are reported via events and notifications.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId - Target service to restart (with deps).
|
||||||
|
* @returns {Promise<{ success: boolean, chain: string[], results: Array }>}
|
||||||
|
*/
|
||||||
|
async restartWithDependencies(serviceId) {
|
||||||
|
const service = await this._findService(serviceId);
|
||||||
|
if (!service) {
|
||||||
|
const err = new Error(`Service "${serviceId}" not found`);
|
||||||
|
this.emit('dependency-restart-failed', {
|
||||||
|
serviceId,
|
||||||
|
failedServiceId: serviceId,
|
||||||
|
error: err.message,
|
||||||
|
chain: [],
|
||||||
|
});
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
let chain;
|
||||||
|
try {
|
||||||
|
chain = await this.getOrderedRestartChain(serviceId);
|
||||||
|
} catch (err) {
|
||||||
|
this.emit('dependency-restart-failed', {
|
||||||
|
serviceId,
|
||||||
|
failedServiceId: serviceId,
|
||||||
|
error: err.message,
|
||||||
|
chain: [],
|
||||||
|
});
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const services = await this._loadServices();
|
||||||
|
const serviceMap = new Map(services.map(s => [s.id, s]));
|
||||||
|
|
||||||
|
this._log.info('dependency', 'Starting dependency restart chain', {
|
||||||
|
serviceId,
|
||||||
|
chain,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.emit('dependency-restart-start', { serviceId, chain });
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
const total = chain.length;
|
||||||
|
|
||||||
|
for (let i = 0; i < total; i++) {
|
||||||
|
const currentId = chain[i];
|
||||||
|
const svc = serviceMap.get(currentId);
|
||||||
|
|
||||||
|
this.emit('dependency-restart-progress', {
|
||||||
|
serviceId,
|
||||||
|
currentServiceId: currentId,
|
||||||
|
index: i,
|
||||||
|
total,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!svc || !svc.containerId) {
|
||||||
|
const msg = !svc
|
||||||
|
? `Service "${currentId}" not found in state`
|
||||||
|
: `Service "${currentId}" has no container — skipping restart`;
|
||||||
|
this._log.warn('dependency', msg);
|
||||||
|
results.push({ serviceId: currentId, restarted: false, skipped: true, reason: msg });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const container = this._docker.client.getContainer(svc.containerId);
|
||||||
|
this._log.info('dependency', `Restarting container for service "${currentId}"`, {
|
||||||
|
containerId: svc.containerId,
|
||||||
|
});
|
||||||
|
await container.restart();
|
||||||
|
|
||||||
|
// Wait for it to come back up
|
||||||
|
const healthy = await this._waitForContainerHealthy(svc.containerId);
|
||||||
|
if (!healthy) {
|
||||||
|
const msg = `Container for service "${currentId}" did not become healthy within ${HEALTH_CHECK_TIMEOUT_MS / 1000}s`;
|
||||||
|
this._log.warn('dependency', msg);
|
||||||
|
results.push({ serviceId: currentId, restarted: true, healthy: false, error: msg });
|
||||||
|
|
||||||
|
// Abort chain — dependency didn't come back
|
||||||
|
this.emit('dependency-restart-failed', {
|
||||||
|
serviceId,
|
||||||
|
failedServiceId: currentId,
|
||||||
|
error: msg,
|
||||||
|
chain,
|
||||||
|
});
|
||||||
|
await this._notifyRestartResult(serviceId, false, chain, results, currentId);
|
||||||
|
return { success: false, chain, results };
|
||||||
|
}
|
||||||
|
|
||||||
|
this._log.info('dependency', `Service "${currentId}" is healthy after restart`);
|
||||||
|
results.push({ serviceId: currentId, restarted: true, healthy: true });
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err.message || 'Unknown error during restart';
|
||||||
|
this._log.error('dependency', `Failed to restart service "${currentId}"`, {
|
||||||
|
error: msg,
|
||||||
|
});
|
||||||
|
results.push({ serviceId: currentId, restarted: false, error: msg });
|
||||||
|
|
||||||
|
this.emit('dependency-restart-failed', {
|
||||||
|
serviceId,
|
||||||
|
failedServiceId: currentId,
|
||||||
|
error: msg,
|
||||||
|
chain,
|
||||||
|
});
|
||||||
|
await this._notifyRestartResult(serviceId, false, chain, results, currentId);
|
||||||
|
return { success: false, chain, results };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.emit('dependency-restart-complete', { serviceId, chain, results });
|
||||||
|
await this._notifyRestartResult(serviceId, true, chain, results);
|
||||||
|
return { success: true, chain, results };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a notification about the restart result.
|
||||||
|
*
|
||||||
|
* @private
|
||||||
|
* @param {string} serviceId
|
||||||
|
* @param {boolean} success
|
||||||
|
* @param {string[]} chain
|
||||||
|
* @param {Array} results
|
||||||
|
* @param {string} [failedServiceId]
|
||||||
|
*/
|
||||||
|
async _notifyRestartResult(serviceId, success, chain, results, failedServiceId) {
|
||||||
|
if (!this._notification) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (success) {
|
||||||
|
await this._notification.send('dependency-restart-complete', {
|
||||||
|
text: `✅ Dependency restart chain completed for "${serviceId}". Restarted: ${chain.join(' → ')}`,
|
||||||
|
serviceId,
|
||||||
|
chain,
|
||||||
|
results,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await this._notification.send('dependency-restart-failed', {
|
||||||
|
text: `❌ Dependency restart chain failed for "${serviceId}" at "${failedServiceId}". Chain: ${chain.join(' → ')}`,
|
||||||
|
serviceId,
|
||||||
|
failedServiceId,
|
||||||
|
chain,
|
||||||
|
results,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this._log.error('dependency', 'Failed to send restart notification', {
|
||||||
|
error: err.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = DependencyManager;
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
/**
|
||||||
|
* DNS Propagation Checker
|
||||||
|
* Verifies DNS record propagation by querying multiple resolvers.
|
||||||
|
* Runs as background jobs with configurable timeout and interval.
|
||||||
|
*
|
||||||
|
* @module dns-propagation
|
||||||
|
*/
|
||||||
|
|
||||||
|
const dns = require('dns').promises;
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
|
||||||
|
/** Default verification options */
|
||||||
|
const DEFAULT_OPTIONS = {
|
||||||
|
timeout: 300000, // 5 minutes
|
||||||
|
interval: 10000, // 10 seconds
|
||||||
|
resolvers: ['1.1.1.1', '8.8.8.8', '9.9.9.9']
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Maximum age for stored verification results (1 hour) */
|
||||||
|
const MAX_RESULT_AGE_MS = 3600000;
|
||||||
|
|
||||||
|
class DNSPropagationChecker extends EventEmitter {
|
||||||
|
/**
|
||||||
|
* Create a DNSPropagationChecker instance.
|
||||||
|
* @param {Object} ctx - Shared application context
|
||||||
|
* @param {Object} ctx.notification - NotificationManager instance
|
||||||
|
* @param {Object} ctx.log - Logger instance
|
||||||
|
*/
|
||||||
|
constructor(ctx) {
|
||||||
|
super();
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.log = ctx.log || console;
|
||||||
|
|
||||||
|
/** @type {Map<string, Object>} domain → verification status */
|
||||||
|
this.verifications = new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that a DNS record has propagated by querying multiple resolvers.
|
||||||
|
* Retries every `interval` ms until `timeout` is reached.
|
||||||
|
*
|
||||||
|
* @param {string} domain - The domain to check (e.g., 'test.sami')
|
||||||
|
* @param {string} expectedIp - The expected IP address
|
||||||
|
* @param {Object} [options={}] - Verification options
|
||||||
|
* @param {number} [options.timeout=300000] - Maximum time to wait (ms)
|
||||||
|
* @param {number} [options.interval=10000] - Time between retries (ms)
|
||||||
|
* @param {string[]} [options.resolvers] - DNS resolvers to query
|
||||||
|
* @returns {Promise<Object>} Verification result
|
||||||
|
*/
|
||||||
|
async verifyRecord(domain, expectedIp, options = {}) {
|
||||||
|
const startTime = Date.now();
|
||||||
|
const {
|
||||||
|
timeout = DEFAULT_OPTIONS.timeout,
|
||||||
|
interval = DEFAULT_OPTIONS.interval,
|
||||||
|
resolvers = DEFAULT_OPTIONS.resolvers
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
const allResults = [];
|
||||||
|
let propagated = false;
|
||||||
|
|
||||||
|
while (Date.now() - startTime < timeout) {
|
||||||
|
const roundResults = [];
|
||||||
|
|
||||||
|
for (const resolver of resolvers) {
|
||||||
|
const checkStart = Date.now();
|
||||||
|
try {
|
||||||
|
// Use dns.resolve4 with a custom resolver
|
||||||
|
const resolverInstance = new dns.Resolver();
|
||||||
|
resolverInstance.setServers([resolver]);
|
||||||
|
resolverInstance.setTimeout(5000);
|
||||||
|
|
||||||
|
const addresses = await resolverInstance.resolve4(domain);
|
||||||
|
const matched = addresses.includes(expectedIp);
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
resolver,
|
||||||
|
ips: addresses,
|
||||||
|
matched,
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
responseTime: Date.now() - checkStart
|
||||||
|
};
|
||||||
|
|
||||||
|
roundResults.push(result);
|
||||||
|
|
||||||
|
if (matched) {
|
||||||
|
propagated = true;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
roundResults.push({
|
||||||
|
resolver,
|
||||||
|
ips: [],
|
||||||
|
matched: false,
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
error: err.code || err.message,
|
||||||
|
responseTime: Date.now() - checkStart
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
allResults.push(...roundResults);
|
||||||
|
|
||||||
|
// Emit progress event
|
||||||
|
this.emit('propagation-check', {
|
||||||
|
domain,
|
||||||
|
expectedIp,
|
||||||
|
roundResults,
|
||||||
|
elapsed: Date.now() - startTime,
|
||||||
|
propagated
|
||||||
|
});
|
||||||
|
|
||||||
|
if (propagated) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait before next attempt
|
||||||
|
await new Promise(resolve => setTimeout(resolve, interval));
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalTime = Date.now() - startTime;
|
||||||
|
|
||||||
|
return {
|
||||||
|
domain,
|
||||||
|
expectedIp,
|
||||||
|
propagated,
|
||||||
|
results: allResults,
|
||||||
|
totalTime,
|
||||||
|
checkedAt: new Date().toISOString()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start a background DNS propagation verification.
|
||||||
|
* Does not block — returns immediately with the job reference.
|
||||||
|
*
|
||||||
|
* @param {string} domain - The domain to verify
|
||||||
|
* @param {string} expectedIp - The expected IP address
|
||||||
|
* @param {Object} [options={}] - Verification options
|
||||||
|
* @returns {Object} Job status object
|
||||||
|
*/
|
||||||
|
startVerification(domain, expectedIp, options = {}) {
|
||||||
|
// If there's already a running verification for this domain, return it
|
||||||
|
const existing = this.verifications.get(domain);
|
||||||
|
if (existing && existing.status === 'running') {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
const job = {
|
||||||
|
domain,
|
||||||
|
expectedIp,
|
||||||
|
status: 'running',
|
||||||
|
startedAt: new Date().toISOString(),
|
||||||
|
progress: [],
|
||||||
|
result: null
|
||||||
|
};
|
||||||
|
|
||||||
|
this.verifications.set(domain, job);
|
||||||
|
|
||||||
|
// Run verification in background (non-blocking)
|
||||||
|
this.verifyRecord(domain, expectedIp, options)
|
||||||
|
.then(result => {
|
||||||
|
job.status = 'completed';
|
||||||
|
job.result = result;
|
||||||
|
job.completedAt = new Date().toISOString();
|
||||||
|
|
||||||
|
if (result.propagated) {
|
||||||
|
this.emit('propagation-complete', result);
|
||||||
|
|
||||||
|
if (this.ctx.notification) {
|
||||||
|
this.ctx.notification.send('dns-propagation', {
|
||||||
|
text: `✅ DNS record for ${domain} propagated successfully to ${expectedIp}`,
|
||||||
|
domain,
|
||||||
|
expectedIp,
|
||||||
|
totalTime: result.totalTime
|
||||||
|
}, 'success').catch(err => {
|
||||||
|
this.log.error('dns-propagation', 'Failed to send propagation notification', {
|
||||||
|
error: err.message
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.emit('propagation-timeout', result);
|
||||||
|
|
||||||
|
if (this.ctx.notification) {
|
||||||
|
this.ctx.notification.send('dns-propagation', {
|
||||||
|
text: `⏱️ DNS propagation timeout for ${domain} — expected ${expectedIp} not found after ${Math.round(result.totalTime / 1000)}s`,
|
||||||
|
domain,
|
||||||
|
expectedIp,
|
||||||
|
totalTime: result.totalTime
|
||||||
|
}, 'warning').catch(err => {
|
||||||
|
this.log.error('dns-propagation', 'Failed to send timeout notification', {
|
||||||
|
error: err.message
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
job.status = 'error';
|
||||||
|
job.error = err.message;
|
||||||
|
job.completedAt = new Date().toISOString();
|
||||||
|
|
||||||
|
this.log.error('dns-propagation', `Verification failed for ${domain}`, {
|
||||||
|
error: err.message
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return job;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current verification status for a domain.
|
||||||
|
*
|
||||||
|
* @param {string} domain - The domain to look up
|
||||||
|
* @returns {Object|null} Verification status or null if not found
|
||||||
|
*/
|
||||||
|
getVerificationStatus(domain) {
|
||||||
|
const job = this.verifications.get(domain);
|
||||||
|
if (!job) return null;
|
||||||
|
return {
|
||||||
|
domain: job.domain,
|
||||||
|
expectedIp: job.expectedIp,
|
||||||
|
status: job.status,
|
||||||
|
startedAt: job.startedAt,
|
||||||
|
completedAt: job.completedAt || null,
|
||||||
|
result: job.result || null,
|
||||||
|
error: job.error || null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all recent verifications.
|
||||||
|
*
|
||||||
|
* @returns {Object[]} Array of verification statuses
|
||||||
|
*/
|
||||||
|
getAllVerifications() {
|
||||||
|
const results = [];
|
||||||
|
for (const [domain, job] of this.verifications.entries()) {
|
||||||
|
results.push({
|
||||||
|
domain,
|
||||||
|
expectedIp: job.expectedIp,
|
||||||
|
status: job.status,
|
||||||
|
startedAt: job.startedAt,
|
||||||
|
completedAt: job.completedAt || null,
|
||||||
|
propagated: job.result?.propagated || null,
|
||||||
|
totalTime: job.result?.totalTime || null,
|
||||||
|
error: job.error || null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove verifications older than 1 hour.
|
||||||
|
*/
|
||||||
|
cleanup() {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [domain, job] of this.verifications.entries()) {
|
||||||
|
const completedAt = job.completedAt ? new Date(job.completedAt).getTime() : null;
|
||||||
|
const startedAt = new Date(job.startedAt).getTime();
|
||||||
|
|
||||||
|
// Clean up completed/error jobs older than 1 hour
|
||||||
|
// Also clean up stale running jobs that started over 2 hours ago
|
||||||
|
const age = completedAt ? (now - completedAt) : (now - startedAt);
|
||||||
|
const maxAge = job.status === 'running' ? MAX_RESULT_AGE_MS * 2 : MAX_RESULT_AGE_MS;
|
||||||
|
|
||||||
|
if (age > maxAge) {
|
||||||
|
this.verifications.delete(domain);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = DNSPropagationChecker;
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/**
|
||||||
|
* Base DNS Provider Adapter
|
||||||
|
* All DNS provider adapters must extend this class and implement the required methods.
|
||||||
|
*
|
||||||
|
* Each adapter handles the specifics of talking to a particular DNS provider's API.
|
||||||
|
* The routes layer calls these methods generically — no provider-specific logic in routes.
|
||||||
|
*/
|
||||||
|
class BaseDNSProvider {
|
||||||
|
constructor(config, ctx) {
|
||||||
|
this.config = config; // Provider-specific config (api token, server url, etc.)
|
||||||
|
this.ctx = ctx; // Shared app context (log, credentialManager, fetchT, etc.)
|
||||||
|
this.providerId = 'base';
|
||||||
|
this.displayName = 'Base DNS Provider';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Check if this provider supports a given capability */
|
||||||
|
supportsCapability(cap) {
|
||||||
|
// Capabilities: 'create-record', 'delete-record', 'resolve', 'list-records',
|
||||||
|
// 'logs', 'restart', 'update-check', 'credentials', 'zones'
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Authenticate and return a token/session */
|
||||||
|
async authenticate() { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** Create a DNS record */
|
||||||
|
async createRecord({ domain, zone, type, value, ttl, overwrite }) { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** Delete a DNS record */
|
||||||
|
async deleteRecord({ domain, type, value }) { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** Resolve/query existing records for a domain */
|
||||||
|
async resolveRecords({ domain, zone, type }) { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** List all records in a zone */
|
||||||
|
async listRecords({ zone }) { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** Get DNS query logs */
|
||||||
|
async getLogs({ limit, server }) { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** Restart the DNS server */
|
||||||
|
async restartServer({ server }) { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** Check for DNS server updates */
|
||||||
|
async checkUpdate({ server }) { throw new Error('Not implemented'); }
|
||||||
|
|
||||||
|
/** Get provider status info */
|
||||||
|
async getStatus() {
|
||||||
|
return {
|
||||||
|
providerId: this.providerId,
|
||||||
|
displayName: this.displayName,
|
||||||
|
capabilities: this.getCapabilities(),
|
||||||
|
authenticated: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get list of supported capabilities */
|
||||||
|
getCapabilities() {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validate provider-specific config */
|
||||||
|
validateConfig() { return { valid: true, errors: [] }; }
|
||||||
|
|
||||||
|
/** Clean up resources on shutdown */
|
||||||
|
async shutdown() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = BaseDNSProvider;
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
/**
|
||||||
|
* Cloudflare DNS Provider Adapter
|
||||||
|
* Manages DNS records via the Cloudflare API v4.
|
||||||
|
*/
|
||||||
|
const BaseDNSProvider = require('./base');
|
||||||
|
|
||||||
|
const CF_API_BASE = 'https://api.cloudflare.com/client/v4';
|
||||||
|
|
||||||
|
class CloudflareDNSProvider extends BaseDNSProvider {
|
||||||
|
constructor(config, ctx) {
|
||||||
|
super(config, ctx);
|
||||||
|
this.providerId = 'cloudflare';
|
||||||
|
this.displayName = 'Cloudflare DNS';
|
||||||
|
|
||||||
|
// Resolve API token: explicit config takes priority, then credential manager
|
||||||
|
this.apiToken = config.apiToken
|
||||||
|
|| (ctx.credentialManager && ctx.credentialManager.get('dns.cloudflare.apiToken'))
|
||||||
|
|| null;
|
||||||
|
this.zoneId = config.zoneId || null;
|
||||||
|
this.domain = config.domain || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Build common request headers for Cloudflare API calls */
|
||||||
|
_headers() {
|
||||||
|
return {
|
||||||
|
'Authorization': `Bearer ${this.apiToken}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Make an authenticated request to the Cloudflare API */
|
||||||
|
async _cfRequest(method, path, body) {
|
||||||
|
const url = `${CF_API_BASE}${path}`;
|
||||||
|
const opts = {
|
||||||
|
method,
|
||||||
|
headers: this._headers(),
|
||||||
|
};
|
||||||
|
if (body !== undefined) {
|
||||||
|
opts.body = JSON.stringify(body);
|
||||||
|
}
|
||||||
|
return this.ctx.fetchT(url, opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Map a Cloudflare DNS record to the normalised format expected by routes */
|
||||||
|
_mapRecord(rec) {
|
||||||
|
return {
|
||||||
|
id: rec.id,
|
||||||
|
type: rec.type,
|
||||||
|
name: rec.name,
|
||||||
|
value: rec.content,
|
||||||
|
ttl: rec.ttl,
|
||||||
|
proxied: rec.proxied || false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Capabilities ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
supportsCapability(cap) {
|
||||||
|
return this.getCapabilities().includes(cap);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCapabilities() {
|
||||||
|
return ['create-record', 'delete-record', 'resolve', 'list-records', 'credentials', 'zones'];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Authentication ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate the API token by calling the Cloudflare verify endpoint.
|
||||||
|
* Stores basic zone info on success.
|
||||||
|
*/
|
||||||
|
async authenticate() {
|
||||||
|
this.ctx.log('[cloudflare] Authenticating – verifying API token…');
|
||||||
|
|
||||||
|
if (!this.apiToken) {
|
||||||
|
return { status: 'error', message: 'No Cloudflare API token provided' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await this._cfRequest('GET', '/user/tokens/verify');
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!data.success) {
|
||||||
|
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'Token verification failed';
|
||||||
|
this.ctx.log(`[cloudflare] Authentication failed: ${msg}`);
|
||||||
|
return { status: 'error', message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.log(`[cloudflare] Token verified for status "${data.status}"`);
|
||||||
|
|
||||||
|
// Optionally fetch zone info if zoneId is configured
|
||||||
|
if (this.zoneId) {
|
||||||
|
try {
|
||||||
|
const zoneRes = await this._cfRequest('GET', `/zones/${this.zoneId}`);
|
||||||
|
const zoneData = await zoneRes.json();
|
||||||
|
if (zoneData.success && zoneData.result) {
|
||||||
|
this.zoneInfo = zoneData.result;
|
||||||
|
this.ctx.log(`[cloudflare] Zone loaded: ${zoneData.result.name} (${zoneData.result.id})`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.ctx.log(`[cloudflare] Could not fetch zone info: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status: 'ok', response: { status: data.status } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Create Record ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a DNS record.
|
||||||
|
* If overwrite is true, first delete any existing record with the same name+type.
|
||||||
|
*/
|
||||||
|
async createRecord({ domain, zone, type, value, ttl, overwrite }) {
|
||||||
|
const targetDomain = domain || this.domain;
|
||||||
|
const targetZone = zone || this.zoneId;
|
||||||
|
|
||||||
|
if (!targetZone) {
|
||||||
|
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (overwrite) {
|
||||||
|
this.ctx.log(`[cloudflare] Overwrite requested – deleting existing ${type} record for ${targetDomain}`);
|
||||||
|
try {
|
||||||
|
await this.deleteRecord({ domain: targetDomain, type, value });
|
||||||
|
} catch (err) {
|
||||||
|
this.ctx.log(`[cloudflare] No existing record to overwrite (or delete failed): ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
type,
|
||||||
|
name: targetDomain,
|
||||||
|
content: value,
|
||||||
|
ttl: ttl || 1, // 1 = automatic TTL in Cloudflare
|
||||||
|
proxied: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ctx.log(`[cloudflare] Creating ${type} record: ${targetDomain} → ${value}`);
|
||||||
|
const res = await this._cfRequest('POST', `/zones/${targetZone}/dns_records`, body);
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!data.success) {
|
||||||
|
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'Record creation failed';
|
||||||
|
this.ctx.log(`[cloudflare] Create failed: ${msg}`);
|
||||||
|
return { status: 'error', message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status: 'ok', response: { record: this._mapRecord(data.result) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Delete Record ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete DNS records matching domain+type.
|
||||||
|
* Lists matching records first, then deletes each one.
|
||||||
|
*/
|
||||||
|
async deleteRecord({ domain, type, value }) {
|
||||||
|
const targetDomain = domain || this.domain;
|
||||||
|
const targetZone = this.zoneId;
|
||||||
|
|
||||||
|
if (!targetZone) {
|
||||||
|
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// List records matching name + type
|
||||||
|
let queryPath = `/zones/${targetZone}/dns_records?name=${encodeURIComponent(targetDomain)}`;
|
||||||
|
if (type) {
|
||||||
|
queryPath += `&type=${encodeURIComponent(type)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const listRes = await this._cfRequest('GET', queryPath);
|
||||||
|
const listData = await listRes.json();
|
||||||
|
|
||||||
|
if (!listData.success) {
|
||||||
|
const msg = (listData.errors && listData.errors[0] && listData.errors[0].message) || 'Failed to list records for deletion';
|
||||||
|
this.ctx.log(`[cloudflare] Delete – list failed: ${msg}`);
|
||||||
|
return { status: 'error', message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
const matching = listData.result || [];
|
||||||
|
if (matching.length === 0) {
|
||||||
|
this.ctx.log(`[cloudflare] No records found for ${targetDomain} (${type || 'any type'})`);
|
||||||
|
return { status: 'ok', response: { deleted: 0 } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a specific value is given, only delete records matching that value
|
||||||
|
const toDelete = value
|
||||||
|
? matching.filter((r) => r.content === value)
|
||||||
|
: matching;
|
||||||
|
|
||||||
|
let deleted = 0;
|
||||||
|
for (const record of toDelete) {
|
||||||
|
const delRes = await this._cfRequest('DELETE', `/zones/${targetZone}/dns_records/${record.id}`);
|
||||||
|
const delData = await delRes.json();
|
||||||
|
if (delData.success) {
|
||||||
|
deleted++;
|
||||||
|
this.ctx.log(`[cloudflare] Deleted record ${record.id} (${record.type} ${record.name})`);
|
||||||
|
} else {
|
||||||
|
const msg = (delData.errors && delData.errors[0] && delData.errors[0].message) || 'Delete failed';
|
||||||
|
this.ctx.log(`[cloudflare] Failed to delete record ${record.id}: ${msg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status: 'ok', response: { deleted } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Resolve Records ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve/query existing records for a domain.
|
||||||
|
* Returns records matching domain (and optionally type).
|
||||||
|
*/
|
||||||
|
async resolveRecords({ domain, zone, type }) {
|
||||||
|
const targetDomain = domain || this.domain;
|
||||||
|
const targetZone = zone || this.zoneId;
|
||||||
|
|
||||||
|
if (!targetZone) {
|
||||||
|
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
|
||||||
|
}
|
||||||
|
|
||||||
|
let queryPath = `/zones/${targetZone}/dns_records?name=${encodeURIComponent(targetDomain)}`;
|
||||||
|
if (type) {
|
||||||
|
queryPath += `&type=${encodeURIComponent(type)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.log(`[cloudflare] Resolving records for ${targetDomain}${type ? ` (${type})` : ''}`);
|
||||||
|
const res = await this._cfRequest('GET', queryPath);
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!data.success) {
|
||||||
|
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'Resolve failed';
|
||||||
|
this.ctx.log(`[cloudflare] Resolve failed: ${msg}`);
|
||||||
|
return { status: 'error', message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
const records = (data.result || []).map(this._mapRecord);
|
||||||
|
return { status: 'ok', response: { records } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── List Records ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all DNS records in a zone.
|
||||||
|
*/
|
||||||
|
async listRecords({ zone }) {
|
||||||
|
const targetZone = zone || this.zoneId;
|
||||||
|
|
||||||
|
if (!targetZone) {
|
||||||
|
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.log(`[cloudflare] Listing all records in zone ${targetZone}`);
|
||||||
|
const res = await this._cfRequest('GET', `/zones/${targetZone}/dns_records`);
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!data.success) {
|
||||||
|
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'List failed';
|
||||||
|
this.ctx.log(`[cloudflare] List failed: ${msg}`);
|
||||||
|
return { status: 'error', message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
const records = (data.result || []).map(this._mapRecord);
|
||||||
|
return { status: 'ok', response: { records } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = CloudflareDNSProvider;
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
/**
|
||||||
|
* Manual DNS Provider Adapter
|
||||||
|
* No-op adapter for users who manage DNS externally (manual, cPanel, other control panels).
|
||||||
|
* Provides propagation checking only — all record operations return helpful instructions.
|
||||||
|
*/
|
||||||
|
const BaseDNSProvider = require('./base');
|
||||||
|
|
||||||
|
class ManualDNSProvider extends BaseDNSProvider {
|
||||||
|
constructor(config, ctx) {
|
||||||
|
super(config, ctx);
|
||||||
|
this.providerId = 'manual';
|
||||||
|
this.displayName = 'Manual / External DNS';
|
||||||
|
this.description = 'Manage DNS records yourself via your provider\'s control panel';
|
||||||
|
}
|
||||||
|
|
||||||
|
supportsCapability(cap) {
|
||||||
|
return ['credentials'].includes(cap);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCapabilities() {
|
||||||
|
return ['credentials'];
|
||||||
|
}
|
||||||
|
|
||||||
|
async authenticate() {
|
||||||
|
return { success: true, message: 'Manual DNS — no authentication needed' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async createRecord({ domain, zone, type, value, ttl }) {
|
||||||
|
return {
|
||||||
|
status: 'manual',
|
||||||
|
message: `Create this record manually in your DNS control panel:`,
|
||||||
|
instructions: {
|
||||||
|
name: domain,
|
||||||
|
type: type || 'A',
|
||||||
|
value,
|
||||||
|
ttl: ttl || 300
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteRecord({ domain, type, value }) {
|
||||||
|
return {
|
||||||
|
status: 'manual',
|
||||||
|
message: `Delete this record manually from your DNS control panel:`,
|
||||||
|
instructions: {
|
||||||
|
name: domain,
|
||||||
|
type: type || 'A',
|
||||||
|
value: value || '(any)'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async resolveRecords({ domain, zone, type }) {
|
||||||
|
// Use Node.js built-in DNS to resolve regardless of provider
|
||||||
|
const dns = require('dns').promises;
|
||||||
|
try {
|
||||||
|
const resolver = new dns.Resolver();
|
||||||
|
resolver.setServers(['1.1.1.1', '8.8.8.8']);
|
||||||
|
const records = await resolver.resolve(domain, type || 'A');
|
||||||
|
return {
|
||||||
|
status: 'ok',
|
||||||
|
response: {
|
||||||
|
records: records.map(r => ({
|
||||||
|
type: type || 'A',
|
||||||
|
domain,
|
||||||
|
rData: { ipAddress: r },
|
||||||
|
ttl: 0,
|
||||||
|
manual: true
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
return { status: 'ok', response: { records: [] } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getStatus() {
|
||||||
|
return {
|
||||||
|
providerId: this.providerId,
|
||||||
|
displayName: this.displayName,
|
||||||
|
description: this.description,
|
||||||
|
capabilities: this.getCapabilities(),
|
||||||
|
authenticated: true,
|
||||||
|
note: 'DNS records are managed externally. Use propagation checks to verify changes.'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig() {
|
||||||
|
return { valid: true, errors: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ManualDNSProvider;
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
/**
|
||||||
|
* DNS Provider Registry
|
||||||
|
* Manages available DNS provider adapters.
|
||||||
|
* Providers register themselves, and the active provider is selected by config.
|
||||||
|
*/
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
class DNSProviderRegistry {
|
||||||
|
constructor() {
|
||||||
|
this.providers = new Map(); // providerId -> adapter class
|
||||||
|
this.instances = new Map(); // providerId -> adapter instance
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Register a provider adapter class */
|
||||||
|
register(adapterClass) {
|
||||||
|
const instance = new adapterClass({}, {});
|
||||||
|
const id = instance.providerId;
|
||||||
|
if (this.providers.has(id)) {
|
||||||
|
console.warn(`DNS provider "${id}" already registered, overwriting`);
|
||||||
|
}
|
||||||
|
this.providers.set(id, adapterClass);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get list of all registered provider IDs */
|
||||||
|
getProviderIds() {
|
||||||
|
return Array.from(this.providers.keys());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get metadata for all providers (without instantiating with real config) */
|
||||||
|
getProviderMeta() {
|
||||||
|
return this.getProviderIds().map(id => {
|
||||||
|
const Adapter = this.providers.get(id);
|
||||||
|
const inst = new Adapter({}, {});
|
||||||
|
return {
|
||||||
|
id: inst.providerId,
|
||||||
|
displayName: inst.displayName,
|
||||||
|
capabilities: inst.getCapabilities()
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get or create an adapter instance for the given provider + config
|
||||||
|
* @param {string} providerId - The provider to instantiate
|
||||||
|
* @param {Object} config - Provider-specific configuration
|
||||||
|
* @param {Object} ctx - Shared application context
|
||||||
|
* @returns {BaseDNSProvider} The provider adapter instance
|
||||||
|
*/
|
||||||
|
getProvider(providerId, config, ctx) {
|
||||||
|
// Re-create if config changed
|
||||||
|
const cacheKey = providerId;
|
||||||
|
const Adapter = this.providers.get(providerId);
|
||||||
|
if (!Adapter) {
|
||||||
|
throw new Error(`Unknown DNS provider: ${providerId}. Available: ${this.getProviderIds().join(', ')}`);
|
||||||
|
}
|
||||||
|
const instance = new Adapter(config, ctx);
|
||||||
|
this.instances.set(cacheKey, instance);
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Auto-discover and register all providers in this directory */
|
||||||
|
autoDiscover() {
|
||||||
|
const fs = require('fs');
|
||||||
|
const dir = __dirname;
|
||||||
|
const files = fs.readdirSync(dir).filter(f =>
|
||||||
|
f !== 'base.js' && f !== 'registry.js' && f.endsWith('.js') && !f.startsWith('.')
|
||||||
|
);
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
const Loaded = require(path.join(dir, file));
|
||||||
|
// Support: module.exports = Class, module.exports = { Class }, or plain objects
|
||||||
|
let cls = null;
|
||||||
|
if (typeof Loaded === 'function') {
|
||||||
|
cls = Loaded;
|
||||||
|
} else if (typeof Loaded === 'object' && Loaded !== null) {
|
||||||
|
// Try to find a class in the exported object
|
||||||
|
cls = Object.values(Loaded).find(v => typeof v === 'function');
|
||||||
|
}
|
||||||
|
if (cls) {
|
||||||
|
// Verify it has providerId (on prototype or set in constructor)
|
||||||
|
try {
|
||||||
|
const test = new cls({}, {});
|
||||||
|
if (test.providerId && typeof test.getCapabilities === 'function') {
|
||||||
|
this.register(cls);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Not a valid provider adapter, skip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to load DNS provider from ${file}:`, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Singleton
|
||||||
|
const registry = new DNSProviderRegistry();
|
||||||
|
registry.autoDiscover();
|
||||||
|
|
||||||
|
module.exports = registry;
|
||||||
@@ -0,0 +1,383 @@
|
|||||||
|
/**
|
||||||
|
* RFC 2136 Dynamic DNS Provider Adapter
|
||||||
|
*
|
||||||
|
* Manages DNS records via RFC 2136 dynamic updates using the nsupdate CLI tool.
|
||||||
|
* Compatible with BIND, PowerDNS, Windows DNS, and any RFC 2136-compliant server.
|
||||||
|
*
|
||||||
|
* Capabilities: create-record, delete-record, resolve, credentials
|
||||||
|
* Not supported: logs, restart, update-check, list-records, zones
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { execFile } = require('child_process');
|
||||||
|
const { promisify } = require('util');
|
||||||
|
const dns = require('dns');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
const BaseDNSProvider = require('./base');
|
||||||
|
|
||||||
|
const CAPABILITIES = ['create-record', 'delete-record', 'resolve', 'credentials'];
|
||||||
|
|
||||||
|
const DEFAULT_PORT = 53;
|
||||||
|
const DEFAULT_TSIG_ALGORITHM = 'hmac-sha256';
|
||||||
|
const NSUPDATE_TIMEOUT_MS = 15000;
|
||||||
|
|
||||||
|
class RFC2136Provider extends BaseDNSProvider {
|
||||||
|
static providerId = 'rfc2136';
|
||||||
|
static displayName = 'RFC 2136 (Dynamic DNS)';
|
||||||
|
|
||||||
|
constructor(config, ctx) {
|
||||||
|
super(config, ctx);
|
||||||
|
|
||||||
|
this.providerId = 'rfc2136';
|
||||||
|
this.displayName = 'RFC 2136 (Dynamic DNS)';
|
||||||
|
|
||||||
|
// Core config
|
||||||
|
this.server = config.server || null;
|
||||||
|
this.port = config.port || DEFAULT_PORT;
|
||||||
|
this.zone = config.zone || null;
|
||||||
|
|
||||||
|
// TSIG authentication
|
||||||
|
this.tsigAlgorithm = config.tsigAlgorithm || DEFAULT_TSIG_ALGORITHM;
|
||||||
|
this.tsigKeyName = config.tsigKeyName || null;
|
||||||
|
this.tsigSecret = config.tsigSecret || null;
|
||||||
|
|
||||||
|
// Resolve credentials from credential manager if available
|
||||||
|
if (ctx && ctx.credentialManager) {
|
||||||
|
if (!this.tsigKeyName && ctx.credentialManager.get) {
|
||||||
|
this.tsigKeyName = ctx.credentialManager.get('rfc2136_tsigKeyName') || null;
|
||||||
|
}
|
||||||
|
if (!this.tsigSecret && ctx.credentialManager.get) {
|
||||||
|
this.tsigSecret = ctx.credentialManager.get('rfc2136_tsigSecret') || null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logger shorthand
|
||||||
|
this._log = ctx && ctx.log ? ctx.ctx : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Logging helper ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_log(level, message, meta) {
|
||||||
|
if (this.ctx && this.ctx.log && typeof this.ctx.log[level] === 'function') {
|
||||||
|
this.ctx.log[level](`[rfc2136] ${message}`, meta || {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Capabilities ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
supportsCapability(cap) {
|
||||||
|
return CAPABILITIES.includes(cap);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCapabilities() {
|
||||||
|
return [...CAPABILITIES];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Config validation ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
validateConfig() {
|
||||||
|
const errors = [];
|
||||||
|
if (!this.server) errors.push('Missing required config: server');
|
||||||
|
if (!this.zone) errors.push('Missing required config: zone');
|
||||||
|
return { valid: errors.length === 0, errors };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure a domain name ends with a trailing dot (FQDN for nsupdate).
|
||||||
|
*/
|
||||||
|
_ensureFqdn(domain) {
|
||||||
|
if (!domain) return domain;
|
||||||
|
return domain.endsWith('.') ? domain : `${domain}.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the common nsupdate header lines (server, zone, key).
|
||||||
|
*/
|
||||||
|
_buildHeader() {
|
||||||
|
const lines = [];
|
||||||
|
lines.push(`server ${this.server} ${this.port}`);
|
||||||
|
lines.push(`zone ${this.zone}`);
|
||||||
|
|
||||||
|
if (this.tsigKeyName && this.tsigSecret) {
|
||||||
|
lines.push(`key ${this.tsigAlgorithm}:${this.tsigKeyName} ${this.tsigSecret}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute an nsupdate script and return { stdout, stderr }.
|
||||||
|
* Writes commands to a temporary file and runs `nsupdate <file>`.
|
||||||
|
*/
|
||||||
|
async _runNsupdate(commands) {
|
||||||
|
const script = commands.join('\n') + '\n';
|
||||||
|
const tmpFile = path.join(os.tmpdir(), `nsupdate-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.cmd`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.promises.writeFile(tmpFile, script, { mode: 0o600 });
|
||||||
|
this._log('debug', `Executing nsupdate script`, { script: script.trim() });
|
||||||
|
|
||||||
|
const { stdout, stderr } = await execFileAsync('nsupdate', [tmpFile], {
|
||||||
|
timeout: NSUPDATE_TIMEOUT_MS,
|
||||||
|
maxBuffer: 1024 * 1024,
|
||||||
|
});
|
||||||
|
|
||||||
|
this._log('debug', 'nsupdate completed', { stdout: (stdout || '').trim(), stderr: (stderr || '').trim() });
|
||||||
|
|
||||||
|
if (stderr && stderr.toLowerCase().includes('refused')) {
|
||||||
|
throw new Error(`nsupdate refused: ${stderr.trim()}`);
|
||||||
|
}
|
||||||
|
if (stderr && stderr.toLowerCase().includes('failed')) {
|
||||||
|
throw new Error(`nsupdate failed: ${stderr.trim()}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { stdout: (stdout || '').trim(), stderr: (stderr || '').trim() };
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === 'ENOENT') {
|
||||||
|
throw new Error('nsupdate command not found. Install bind9utils (Debian/Ubuntu) or bind-utils (RHEL/CentOS).');
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
try { await fs.promises.unlink(tmpFile); } catch (_) { /* ignore */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Authenticate ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify nsupdate is available and optionally test connectivity.
|
||||||
|
* Runs a minimal nsupdate with just "show" (no-op) to confirm the tool works.
|
||||||
|
*/
|
||||||
|
async authenticate() {
|
||||||
|
const validation = this.validateConfig();
|
||||||
|
if (!validation.valid) {
|
||||||
|
throw new Error(`RFC 2136 config invalid: ${validation.errors.join('; ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check nsupdate binary is available with a dry-run command set
|
||||||
|
const commands = [
|
||||||
|
...this._buildHeader(),
|
||||||
|
'show',
|
||||||
|
];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { stdout } = await this._runNsupdate(commands);
|
||||||
|
this._log('info', 'Authenticated to RFC 2136 server', { server: this.server, port: this.port });
|
||||||
|
return { success: true, server: this.server, port: this.port };
|
||||||
|
} catch (err) {
|
||||||
|
this._log('error', 'Authentication test failed', { error: err.message });
|
||||||
|
// If nsupdate is missing, rethrow immediately
|
||||||
|
if (err.message.includes('not found')) throw err;
|
||||||
|
// Otherwise, the server might be unreachable but the tool works — return partial
|
||||||
|
return { success: false, error: err.message, server: this.server };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Create Record ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create (add) a DNS record via RFC 2136 UPDATE.
|
||||||
|
*
|
||||||
|
* @param {Object} params
|
||||||
|
* @param {string} params.domain - Record name (e.g. "www.example.com")
|
||||||
|
* @param {string} params.zone - Zone name (overrides constructor zone)
|
||||||
|
* @param {string} params.type - Record type (A, AAAA, CNAME, TXT, etc.)
|
||||||
|
* @param {string} params.value - Record value
|
||||||
|
* @param {number} [params.ttl=300] - TTL in seconds
|
||||||
|
*/
|
||||||
|
async createRecord({ domain, zone, type, value, ttl }) {
|
||||||
|
const effectiveZone = zone || this.zone;
|
||||||
|
const effectiveTtl = ttl || 300;
|
||||||
|
const fqdn = this._ensureFqdn(domain);
|
||||||
|
|
||||||
|
const commands = [
|
||||||
|
`server ${this.server} ${this.port}`,
|
||||||
|
`zone ${effectiveZone}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (this.tsigKeyName && this.tsigSecret) {
|
||||||
|
commands.push(`key ${this.tsigAlgorithm}:${this.tsigKeyName} ${this.tsigSecret}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
commands.push(`update add ${fqdn} ${effectiveTtl} ${type} ${value}`);
|
||||||
|
commands.push('show');
|
||||||
|
commands.push('send');
|
||||||
|
|
||||||
|
this._log('info', 'Creating DNS record', { domain: fqdn, type, value, ttl: effectiveTtl });
|
||||||
|
|
||||||
|
const result = await this._runNsupdate(commands);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
action: 'create-record',
|
||||||
|
domain: fqdn,
|
||||||
|
type,
|
||||||
|
value,
|
||||||
|
ttl: effectiveTtl,
|
||||||
|
zone: effectiveZone,
|
||||||
|
raw: result.stdout,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Delete Record ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a DNS record via RFC 2136 UPDATE.
|
||||||
|
*
|
||||||
|
* @param {Object} params
|
||||||
|
* @param {string} params.domain - Record name
|
||||||
|
* @param {string} params.type - Record type
|
||||||
|
* @param {string} [params.value] - Optional specific value to match
|
||||||
|
*/
|
||||||
|
async deleteRecord({ domain, type, value }) {
|
||||||
|
const effectiveZone = this.zone;
|
||||||
|
const fqdn = this._ensureFqdn(domain);
|
||||||
|
|
||||||
|
const commands = [
|
||||||
|
`server ${this.server} ${this.port}`,
|
||||||
|
`zone ${effectiveZone}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (this.tsigKeyName && this.tsigSecret) {
|
||||||
|
commands.push(`key ${this.tsigAlgorithm}:${this.tsigKeyName} ${this.tsigSecret}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// "update delete" with value removes that specific RR;
|
||||||
|
// without value it removes all RRs of that type for the name.
|
||||||
|
const deleteClause = value
|
||||||
|
? `update delete ${fqdn} ${type} ${value}`
|
||||||
|
: `update delete ${fqdn} ${type}`;
|
||||||
|
|
||||||
|
commands.push(deleteClause);
|
||||||
|
commands.push('show');
|
||||||
|
commands.push('send');
|
||||||
|
|
||||||
|
this._log('info', 'Deleting DNS record', { domain: fqdn, type, value: value || '(all)' });
|
||||||
|
|
||||||
|
const result = await this._runNsupdate(commands);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
action: 'delete-record',
|
||||||
|
domain: fqdn,
|
||||||
|
type,
|
||||||
|
value: value || null,
|
||||||
|
zone: effectiveZone,
|
||||||
|
raw: result.stdout,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Resolve Records ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve DNS records for a domain.
|
||||||
|
* First attempts dig against the configured server, then falls back to Node dns module.
|
||||||
|
*
|
||||||
|
* @param {Object} params
|
||||||
|
* @param {string} params.domain - Domain to resolve
|
||||||
|
* @param {string} [params.zone] - Zone (unused for resolution, kept for interface consistency)
|
||||||
|
* @param {string} [params.type='A'] - Record type to query
|
||||||
|
*/
|
||||||
|
async resolveRecords({ domain, zone, type }) {
|
||||||
|
const queryType = type || 'A';
|
||||||
|
const fqdn = domain.endsWith('.') ? domain : domain;
|
||||||
|
|
||||||
|
// Strategy 1: Use dig against the configured RFC 2136 server
|
||||||
|
try {
|
||||||
|
const { stdout } = await execFileAsync('dig', [
|
||||||
|
`@${this.server}`,
|
||||||
|
'-p', String(this.port),
|
||||||
|
fqdn,
|
||||||
|
queryType,
|
||||||
|
'+short',
|
||||||
|
'+time=5',
|
||||||
|
'+tries=1',
|
||||||
|
], { timeout: 10000 });
|
||||||
|
|
||||||
|
const records = stdout
|
||||||
|
.split('\n')
|
||||||
|
.map(line => line.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (records.length > 0) {
|
||||||
|
this._log('debug', `Resolved ${fqdn} ${queryType} via dig`, { records });
|
||||||
|
return {
|
||||||
|
domain: fqdn,
|
||||||
|
type: queryType,
|
||||||
|
records: records.map(r => ({ value: r, type: queryType })),
|
||||||
|
source: 'dig',
|
||||||
|
server: this.server,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this._log('warn', 'dig resolution failed, falling back to Node dns', { error: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 2: Fallback to Node.js built-in resolver
|
||||||
|
try {
|
||||||
|
const resolver = new dns.Resolver();
|
||||||
|
resolver.setServers([this.server]);
|
||||||
|
|
||||||
|
const resolveMethod = this._getResolveMethod(queryType);
|
||||||
|
const resolveAsync = promisify(resolver[resolveMethod]).bind(resolver);
|
||||||
|
|
||||||
|
const results = await resolveAsync(fqdn);
|
||||||
|
const records = Array.isArray(results) ? results : [results];
|
||||||
|
|
||||||
|
this._log('debug', `Resolved ${fqdn} ${queryType} via Node dns`, { records });
|
||||||
|
|
||||||
|
return {
|
||||||
|
domain: fqdn,
|
||||||
|
type: queryType,
|
||||||
|
records: records.map(r => ({ value: String(r), type: queryType })),
|
||||||
|
source: 'node-dns',
|
||||||
|
server: this.server,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
this._log('warn', 'Node dns resolution also failed', { error: err.message });
|
||||||
|
return {
|
||||||
|
domain: fqdn,
|
||||||
|
type: queryType,
|
||||||
|
records: [],
|
||||||
|
source: 'none',
|
||||||
|
server: this.server,
|
||||||
|
error: err.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map record type to the Node dns resolver method name.
|
||||||
|
*/
|
||||||
|
_getResolveMethod(type) {
|
||||||
|
const map = {
|
||||||
|
A: 'resolve4',
|
||||||
|
AAAA: 'resolve6',
|
||||||
|
CNAME: 'resolveCname',
|
||||||
|
MX: 'resolveMx',
|
||||||
|
TXT: 'resolveTxt',
|
||||||
|
NS: 'resolveNs',
|
||||||
|
SOA: 'resolveSoa',
|
||||||
|
SRV: 'resolveSrv',
|
||||||
|
PTR: 'reverse',
|
||||||
|
};
|
||||||
|
return map[(type || '').toUpperCase()] || 'resolve4';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Shutdown ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async shutdown() {
|
||||||
|
this._log('info', 'RFC 2136 provider shutting down');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expose providerId on the prototype so the registry's auto-discover can detect it
|
||||||
|
RFC2136Provider.prototype.providerId = 'rfc2136';
|
||||||
|
|
||||||
|
module.exports = RFC2136Provider;
|
||||||
@@ -0,0 +1,507 @@
|
|||||||
|
/**
|
||||||
|
* Technitium DNS Server Provider Adapter
|
||||||
|
*
|
||||||
|
* Wraps Technitium-specific DNS logic into the standard adapter interface.
|
||||||
|
* Uses the Technitium HTTP API (default port 5380) for all operations.
|
||||||
|
*/
|
||||||
|
const BaseDNSProvider = require('./base');
|
||||||
|
|
||||||
|
const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24-hour token lifetime
|
||||||
|
|
||||||
|
class TechnitiumDNSProvider extends BaseDNSProvider {
|
||||||
|
constructor(config, ctx) {
|
||||||
|
super(config, ctx);
|
||||||
|
this.providerId = 'technitium';
|
||||||
|
this.displayName = 'Technitium DNS Server';
|
||||||
|
|
||||||
|
this.serverIp = config.serverIp;
|
||||||
|
this.serverPort = config.serverPort || 5380;
|
||||||
|
this.dnsId = config.dnsId || null;
|
||||||
|
|
||||||
|
// Token state
|
||||||
|
this.token = null;
|
||||||
|
this.tokenExpiry = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Capabilities
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
static CAPABILITIES = [
|
||||||
|
'create-record',
|
||||||
|
'delete-record',
|
||||||
|
'resolve',
|
||||||
|
'list-records',
|
||||||
|
'logs',
|
||||||
|
'restart',
|
||||||
|
'update-check',
|
||||||
|
'credentials',
|
||||||
|
'zones'
|
||||||
|
];
|
||||||
|
|
||||||
|
supportsCapability(cap) {
|
||||||
|
return TechnitiumDNSProvider.CAPABILITIES.includes(cap);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCapabilities() {
|
||||||
|
return [...TechnitiumDNSProvider.CAPABILITIES];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Build the base URL for this server */
|
||||||
|
_baseUrl() {
|
||||||
|
return `http://${this.serverIp}:${this.serverPort}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build a full API URL with query-string params */
|
||||||
|
_buildUrl(apiPath, params = {}) {
|
||||||
|
const qs = new URLSearchParams(params).toString();
|
||||||
|
return `${this._baseUrl()}${apiPath}${qs ? '?' + qs : ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ensure we have a valid token; throws on failure */
|
||||||
|
async _requireToken() {
|
||||||
|
// Re-use existing token if still valid
|
||||||
|
if (this.token && this.tokenExpiry && new Date() < new Date(this.tokenExpiry)) {
|
||||||
|
return this.token;
|
||||||
|
}
|
||||||
|
const result = await this.authenticate();
|
||||||
|
if (!result.success) {
|
||||||
|
const err = new Error('No valid DNS token available. ' + (result.error || ''));
|
||||||
|
err.statusCode = 401;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return this.token;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Authentication
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate against the Technitium server.
|
||||||
|
* Checks per-server credentials first (dns.{dnsId}.readonly.username),
|
||||||
|
* then falls back to global credentials (dns.username).
|
||||||
|
*
|
||||||
|
* Stores token + expiry on success.
|
||||||
|
*/
|
||||||
|
async authenticate() {
|
||||||
|
const { credentialManager, log } = this.ctx;
|
||||||
|
|
||||||
|
// Try per-server credentials first
|
||||||
|
if (this.dnsId) {
|
||||||
|
for (const role of ['readonly', 'admin']) {
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve(`dns.${this.dnsId}.${role}.username`);
|
||||||
|
const password = await credentialManager.retrieve(`dns.${this.dnsId}.${role}.password`);
|
||||||
|
if (username && password) {
|
||||||
|
const result = await this._doLogin(username, password);
|
||||||
|
if (result.success) return result;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log.error('technitium', `Per-server ${role} credential error`, {
|
||||||
|
dnsId: this.dnsId,
|
||||||
|
error: err.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to global credentials
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve('dns.username');
|
||||||
|
const password = await credentialManager.retrieve('dns.password');
|
||||||
|
if (username && password) {
|
||||||
|
return await this._doLogin(username, password);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log.error('technitium', 'Global credential error', { error: err.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'No DNS credentials configured. Please set up credentials via /api/dns/credentials'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform the actual login POST to Technitium.
|
||||||
|
* Stores token on success.
|
||||||
|
*/
|
||||||
|
async _doLogin(username, password) {
|
||||||
|
const { fetchT, log } = this.ctx;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
user: username,
|
||||||
|
pass: password,
|
||||||
|
includeInfo: 'false'
|
||||||
|
});
|
||||||
|
|
||||||
|
const url = `${this._baseUrl()}/api/user/login?${params.toString()}`;
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.status === 'ok' && result.token) {
|
||||||
|
this.token = result.token;
|
||||||
|
this.tokenExpiry = new Date(Date.now() + SESSION_TTL_MS).toISOString();
|
||||||
|
log.info('technitium', 'DNS token obtained', {
|
||||||
|
server: this.serverIp,
|
||||||
|
expires: this.tokenExpiry
|
||||||
|
});
|
||||||
|
return { success: true, token: this.token };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, error: result.errorMessage || 'Login failed' };
|
||||||
|
} catch (error) {
|
||||||
|
log.error('technitium', 'Login error', { error: error.message });
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Record Management
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create (or overwrite) a DNS record.
|
||||||
|
* GET /api/zones/records/add?token=...&domain=...&zone=...&type=...&ipAddress=...&ttl=...&overwrite=...
|
||||||
|
*/
|
||||||
|
async createRecord({ domain, zone, type, value, ttl, overwrite }) {
|
||||||
|
const token = await this._requireToken();
|
||||||
|
const { fetchT, log } = this.ctx;
|
||||||
|
|
||||||
|
const params = {
|
||||||
|
token,
|
||||||
|
domain,
|
||||||
|
zone,
|
||||||
|
type: type || 'A',
|
||||||
|
ipAddress: value,
|
||||||
|
ttl: String(ttl || 300),
|
||||||
|
overwrite: String(overwrite !== false)
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info('technitium', 'Creating DNS record', { domain, type, value });
|
||||||
|
const url = this._buildUrl('/api/zones/records/add', params);
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' }
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.status === 'ok') {
|
||||||
|
log.info('technitium', 'DNS record created', { domain, type, value });
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// If token expired, re-authenticate and retry once
|
||||||
|
if (result.errorMessage && result.errorMessage.toLowerCase().includes('token')) {
|
||||||
|
log.info('technitium', 'Token expired, re-authenticating');
|
||||||
|
this.token = null;
|
||||||
|
this.tokenExpiry = null;
|
||||||
|
const retryToken = await this._requireToken();
|
||||||
|
params.token = retryToken;
|
||||||
|
const retryUrl = this._buildUrl('/api/zones/records/add', params);
|
||||||
|
const retryResp = await fetchT(retryUrl, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' }
|
||||||
|
});
|
||||||
|
const retryResult = await retryResp.json();
|
||||||
|
if (retryResult.status === 'ok') {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
throw new Error(retryResult.errorMessage || 'Failed after token refresh');
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(result.errorMessage || 'Unknown error');
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Failed to create DNS record for ${domain}: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a DNS record.
|
||||||
|
* GET /api/zones/records/delete?token=...&domain=...&type=... (+ ipAddress if value provided)
|
||||||
|
*/
|
||||||
|
async deleteRecord({ domain, type, value }) {
|
||||||
|
const token = await this._requireToken();
|
||||||
|
const { fetchT, log } = this.ctx;
|
||||||
|
|
||||||
|
const params = {
|
||||||
|
token,
|
||||||
|
domain,
|
||||||
|
type: type || 'A'
|
||||||
|
};
|
||||||
|
if (value) {
|
||||||
|
params.ipAddress = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info('technitium', 'Deleting DNS record', { domain, type, value });
|
||||||
|
const url = this._buildUrl('/api/zones/records/delete', params);
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' }
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.status === 'ok') {
|
||||||
|
log.info('technitium', 'DNS record deleted', { domain, type, value });
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(result.errorMessage || 'Unknown error');
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Failed to delete DNS record for ${domain}: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve/query records for a domain in a zone.
|
||||||
|
* GET /api/zones/records/get?token=...&domain=...&zone=...&listZone=true
|
||||||
|
* Filters returned records by type if provided.
|
||||||
|
*/
|
||||||
|
async resolveRecords({ domain, zone, type }) {
|
||||||
|
const token = await this._requireToken();
|
||||||
|
const { fetchT, log } = this.ctx;
|
||||||
|
|
||||||
|
const params = {
|
||||||
|
token,
|
||||||
|
domain,
|
||||||
|
zone,
|
||||||
|
listZone: 'true'
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info('technitium', 'Resolving records', { domain, zone, type });
|
||||||
|
const url = this._buildUrl('/api/zones/records/get', params);
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' }
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.status !== 'ok') {
|
||||||
|
throw new Error(result.errorMessage || 'Failed to resolve records');
|
||||||
|
}
|
||||||
|
|
||||||
|
let records = (result.response && result.response.records) || [];
|
||||||
|
|
||||||
|
// Filter by type if specified
|
||||||
|
if (type) {
|
||||||
|
records = records.filter(r => r.type === type);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, records };
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Failed to resolve records for ${domain}: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all records in a zone.
|
||||||
|
* Delegates to resolveRecords with a wildcard domain.
|
||||||
|
*/
|
||||||
|
async listRecords({ zone }) {
|
||||||
|
return this.resolveRecords({ domain: zone, zone, type: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Logs
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch and parse DNS query logs.
|
||||||
|
* 1. GET /api/logs/list to discover the latest log file
|
||||||
|
* 2. GET /api/logs/download?token=...&fileName=... to download it
|
||||||
|
* 3. Parse text format: [timestamp] [client:port] [protocol] QNAME: domain; QTYPE: type; QCLASS: class; RCODE: rcode; ANSWER: [answer]
|
||||||
|
*/
|
||||||
|
async getLogs({ limit, server } = {}) {
|
||||||
|
const token = await this._requireToken();
|
||||||
|
const { fetchT, log } = this.ctx;
|
||||||
|
|
||||||
|
const targetIp = server || this.serverIp;
|
||||||
|
const targetPort = this.serverPort;
|
||||||
|
const baseUrl = `http://${targetIp}:${targetPort}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Step 1: Get log file list
|
||||||
|
const listUrl = this._buildUrl('/api/logs/list', { token });
|
||||||
|
const listResp = await fetchT(listUrl.replace(this._baseUrl(), baseUrl), {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' }
|
||||||
|
});
|
||||||
|
const listResult = await listResp.json();
|
||||||
|
|
||||||
|
if (listResult.status !== 'ok' || !listResult.response || !listResult.response.length) {
|
||||||
|
throw new Error(listResult.errorMessage || 'No log files found');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pick the latest log file (last entry)
|
||||||
|
const logFile = listResult.response[listResult.response.length - 1];
|
||||||
|
const fileName = logFile.name || logFile.fileName || logFile;
|
||||||
|
|
||||||
|
// Step 2: Download the log file
|
||||||
|
const downloadUrl = `${baseUrl}/api/logs/download?${new URLSearchParams({ token, fileName }).toString()}`;
|
||||||
|
const downloadResp = await fetchT(downloadUrl, {
|
||||||
|
method: 'GET'
|
||||||
|
});
|
||||||
|
const logText = await downloadResp.text();
|
||||||
|
|
||||||
|
// Step 3: Parse lines
|
||||||
|
const parsed = this._parseLogText(logText, limit);
|
||||||
|
return { success: true, logs: parsed };
|
||||||
|
} catch (error) {
|
||||||
|
log.error('technitium', 'Failed to fetch DNS logs', { error: error.message });
|
||||||
|
throw new Error(`Failed to get DNS logs: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse Technitium DNS log text format.
|
||||||
|
* Line format: [timestamp] [client:port] [protocol] QNAME: domain; QTYPE: type; QCLASS: class; RCODE: rcode; ANSWER: [answer]
|
||||||
|
*/
|
||||||
|
_parseLogText(text, limit) {
|
||||||
|
const lines = text.split('\n').filter(l => l.trim());
|
||||||
|
const parsed = [];
|
||||||
|
|
||||||
|
// Process newest first if we need to limit
|
||||||
|
const iterable = limit ? lines.slice(-limit).reverse() : lines;
|
||||||
|
|
||||||
|
for (const line of iterable) {
|
||||||
|
try {
|
||||||
|
const entry = {};
|
||||||
|
|
||||||
|
// Extract timestamp: [2024-01-15 10:30:45]
|
||||||
|
const tsMatch = line.match(/\[([^\]]+)\]/);
|
||||||
|
if (tsMatch) entry.timestamp = tsMatch[1];
|
||||||
|
|
||||||
|
// Extract client:port: [192.168.1.100:12345]
|
||||||
|
const clientMatch = line.match(/\[([^\]]+:\d+)\]/g);
|
||||||
|
if (clientMatch && clientMatch.length >= 2) {
|
||||||
|
entry.client = clientMatch[1].replace(/\[|\]/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract protocol: [UDP] or [TCP]
|
||||||
|
const protoMatch = line.match(/\]\s*\[(UDP|TCP|DoH|DoT|DoH2)\]/i);
|
||||||
|
if (protoMatch) entry.protocol = protoMatch[1];
|
||||||
|
|
||||||
|
// Extract key-value pairs: QNAME: value; QTYPE: value; etc.
|
||||||
|
const kvPattern = /(\w+):\s*([^;]+)/g;
|
||||||
|
let match;
|
||||||
|
while ((match = kvPattern.exec(line)) !== null) {
|
||||||
|
const key = match[1];
|
||||||
|
const val = match[2].trim();
|
||||||
|
if (['QNAME', 'QTYPE', 'QCLASS', 'RCODE'].includes(key)) {
|
||||||
|
entry[key.toLowerCase()] = val;
|
||||||
|
} else if (key === 'ANSWER') {
|
||||||
|
entry.answer = val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.raw = line;
|
||||||
|
parsed.push(entry);
|
||||||
|
} catch {
|
||||||
|
// Skip unparseable lines
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Server Management
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restart the DNS server.
|
||||||
|
* POST /api/admin/restart?token=...
|
||||||
|
* Requires admin credentials.
|
||||||
|
*/
|
||||||
|
async restartServer({ server } = {}) {
|
||||||
|
const token = await this._requireToken();
|
||||||
|
const { fetchT, log } = this.ctx;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info('technitium', 'Restarting DNS server', { server: this.serverIp });
|
||||||
|
const url = this._buildUrl('/api/admin/restart', { token });
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Accept': 'application/json' }
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.status === 'ok') {
|
||||||
|
log.info('technitium', 'DNS server restart initiated');
|
||||||
|
return { success: true, message: 'Server restart initiated' };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(result.errorMessage || 'Restart failed');
|
||||||
|
} catch (error) {
|
||||||
|
log.error('technitium', 'DNS restart error', { error: error.message });
|
||||||
|
throw new Error(`Failed to restart DNS server: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check for DNS server updates.
|
||||||
|
* GET /api/user/checkForUpdate?token=...
|
||||||
|
*/
|
||||||
|
async checkUpdate({ server } = {}) {
|
||||||
|
const token = await this._requireToken();
|
||||||
|
const { fetchT, log } = this.ctx;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info('technitium', 'Checking for DNS server update', { server: this.serverIp });
|
||||||
|
const url = this._buildUrl('/api/user/checkForUpdate', { token });
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' }
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.status === 'ok') {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
updateAvailable: !!(result.response && result.response.updateAvailable),
|
||||||
|
latestVersion: (result.response && result.response.latestVersion) || null,
|
||||||
|
currentVersion: (result.response && result.response.currentVersion) || null,
|
||||||
|
response: result.response
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(result.errorMessage || 'Update check failed');
|
||||||
|
} catch (error) {
|
||||||
|
log.error('technitium', 'Update check error', { error: error.message });
|
||||||
|
throw new Error(`Failed to check for updates: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Config Validation
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
validateConfig() {
|
||||||
|
const errors = [];
|
||||||
|
if (!this.serverIp) {
|
||||||
|
errors.push('serverIp is required');
|
||||||
|
}
|
||||||
|
if (this.serverPort && (typeof this.serverPort !== 'number' || this.serverPort < 1 || this.serverPort > 65535)) {
|
||||||
|
errors.push('serverPort must be a valid port number (1-65535)');
|
||||||
|
}
|
||||||
|
return { valid: errors.length === 0, errors };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = TechnitiumDNSProvider;
|
||||||
@@ -317,6 +317,9 @@ class LicenseManager {
|
|||||||
*/
|
*/
|
||||||
isExpired() {
|
isExpired() {
|
||||||
if (!this.activation) return true;
|
if (!this.activation) return true;
|
||||||
|
// Lifetime licenses never expire
|
||||||
|
if (this.activation.lifetime || this.activation.durationDays === 0) return false;
|
||||||
|
if (!this.activation.expiresAt) return false; // No expiry set = lifetime
|
||||||
return Date.now() > new Date(this.activation.expiresAt).getTime();
|
return Date.now() > new Date(this.activation.expiresAt).getTime();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,501 @@
|
|||||||
|
/**
|
||||||
|
* Notification Manager - Multi-provider notification delivery
|
||||||
|
* Supports Discord, Telegram, ntfy, and Email notifications
|
||||||
|
*/
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const nodemailer = require('nodemailer');
|
||||||
|
|
||||||
|
const DEFAULT_CONFIG = {
|
||||||
|
enabled: true,
|
||||||
|
providers: {
|
||||||
|
discord: { enabled: false, webhookUrl: '' },
|
||||||
|
telegram: { enabled: false, botToken: '', chatId: '' },
|
||||||
|
ntfy: { enabled: false, topic: '', serverUrl: 'https://ntfy.sh' },
|
||||||
|
email: { enabled: false, host: '', port: 587, to: '', from: '', username: '', password: '' }
|
||||||
|
},
|
||||||
|
events: {
|
||||||
|
'container-down': true,
|
||||||
|
'container-up': false,
|
||||||
|
'alert': true,
|
||||||
|
'backup-complete': true,
|
||||||
|
'backup-failed': true,
|
||||||
|
'update-available': true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class NotificationManager extends EventEmitter {
|
||||||
|
constructor(ctx) {
|
||||||
|
super();
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.NOTIFICATIONS_FILE = ctx.NOTIFICATIONS_FILE;
|
||||||
|
this.log = ctx.log || console;
|
||||||
|
this.config = { ...DEFAULT_CONFIG };
|
||||||
|
this.lastSent = null;
|
||||||
|
this.history = [];
|
||||||
|
this.maxHistory = 100;
|
||||||
|
this.healthDaemonInterval = null;
|
||||||
|
this.healthState = new Map();
|
||||||
|
|
||||||
|
this._loadConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load config from file
|
||||||
|
*/
|
||||||
|
_loadConfig() {
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(this.NOTIFICATIONS_FILE)) {
|
||||||
|
const data = JSON.parse(fs.readFileSync(this.NOTIFICATIONS_FILE, 'utf8'));
|
||||||
|
this.config = this._mergeConfig(DEFAULT_CONFIG, data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.log.error('notification', 'Failed to load config', { error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge loaded config with defaults
|
||||||
|
*/
|
||||||
|
_mergeConfig(defaults, loaded) {
|
||||||
|
const result = { ...defaults };
|
||||||
|
for (const key of Object.keys(defaults)) {
|
||||||
|
if (loaded && typeof defaults[key] === 'object' && !Array.isArray(defaults[key])) {
|
||||||
|
result[key] = { ...defaults[key], ...loaded[key] };
|
||||||
|
} else if (loaded && loaded[key] !== undefined) {
|
||||||
|
result[key] = loaded[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current config (for API)
|
||||||
|
*/
|
||||||
|
getConfig() {
|
||||||
|
return this.config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save config to file
|
||||||
|
*/
|
||||||
|
async saveConfig() {
|
||||||
|
try {
|
||||||
|
const dir = path.dirname(this.NOTIFICATIONS_FILE);
|
||||||
|
if (!fs.existsSync(dir)) {
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
}
|
||||||
|
fs.writeFileSync(this.NOTIFICATIONS_FILE, JSON.stringify(this.config, null, 2));
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
this.log.error('notification', 'Failed to save config', { error: error.message });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get notification history
|
||||||
|
*/
|
||||||
|
getHistory() {
|
||||||
|
return this.history.slice();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear notification history
|
||||||
|
*/
|
||||||
|
clearHistory() {
|
||||||
|
this.history = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add entry to history
|
||||||
|
*/
|
||||||
|
_addToHistory(entry) {
|
||||||
|
this.history.unshift({
|
||||||
|
...entry,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
|
if (this.history.length > this.maxHistory) {
|
||||||
|
this.history = this.history.slice(0, this.maxHistory);
|
||||||
|
}
|
||||||
|
this.lastSent = new Date().toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send notification via all enabled providers
|
||||||
|
*/
|
||||||
|
async send(event, data, type = 'info') {
|
||||||
|
if (!this.config.enabled) {
|
||||||
|
return { success: false, error: 'Notifications disabled' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if event is enabled
|
||||||
|
if (event && this.config.events && !this.config.events[event]) {
|
||||||
|
return { success: false, error: `Event ${event} not enabled` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
const providers = this.config.providers;
|
||||||
|
|
||||||
|
// Discord
|
||||||
|
if (providers.discord?.enabled && providers.discord?.webhookUrl) {
|
||||||
|
try {
|
||||||
|
const result = await this.sendDiscord(this._formatText(data, event), this._formatEmbed(data, event, type));
|
||||||
|
results.push({ provider: 'discord', ...result });
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ provider: 'discord', success: false, error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Telegram
|
||||||
|
if (providers.telegram?.enabled && providers.telegram?.botToken && providers.telegram?.chatId) {
|
||||||
|
try {
|
||||||
|
const result = await this.sendTelegram(this._formatText(data, event));
|
||||||
|
results.push({ provider: 'telegram', ...result });
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ provider: 'telegram', success: false, error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ntfy
|
||||||
|
if (providers.ntfy?.enabled && providers.ntfy?.topic) {
|
||||||
|
try {
|
||||||
|
const result = await this.sendNtfy(this._formatText(data, event), this._formatTitle(event));
|
||||||
|
results.push({ provider: 'ntfy', ...result });
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ provider: 'ntfy', success: false, error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Email
|
||||||
|
if (providers.email?.enabled && providers.email?.host && providers.email?.to) {
|
||||||
|
try {
|
||||||
|
const result = await this.sendEmail(
|
||||||
|
this._formatTitle(event),
|
||||||
|
this._formatText(data, event)
|
||||||
|
);
|
||||||
|
results.push({ provider: 'email', ...result });
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ provider: 'email', success: false, error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const allSucceeded = results.every(r => r.success);
|
||||||
|
this._addToHistory({
|
||||||
|
title: this._formatTitle(event),
|
||||||
|
type,
|
||||||
|
event,
|
||||||
|
results
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: allSucceeded, results };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send Discord webhook notification
|
||||||
|
*/
|
||||||
|
async sendDiscord(text, embed) {
|
||||||
|
const { webhookUrl } = this.config.providers.discord;
|
||||||
|
if (!webhookUrl) {
|
||||||
|
throw new Error('Discord webhook not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
content: text,
|
||||||
|
embeds: embed ? [embed] : []
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.ctx.fetchT(webhookUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Discord API error: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send Telegram message
|
||||||
|
*/
|
||||||
|
async sendTelegram(text) {
|
||||||
|
const { botToken, chatId } = this.config.providers.telegram;
|
||||||
|
if (!botToken || !chatId) {
|
||||||
|
throw new Error('Telegram not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = `https://api.telegram.org/bot${botToken}/sendMessage`;
|
||||||
|
const payload = {
|
||||||
|
chat_id: chatId,
|
||||||
|
text,
|
||||||
|
parse_mode: 'Markdown'
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.ctx.fetchT(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
if (!data.ok) {
|
||||||
|
throw new Error(`Telegram error: ${data.description}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send ntfy notification
|
||||||
|
*/
|
||||||
|
async sendNtfy(text, title) {
|
||||||
|
const { serverUrl, topic } = this.config.providers.ntfy;
|
||||||
|
if (!topic) {
|
||||||
|
throw new Error('ntfy topic not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = `${serverUrl.replace(/\/$/, '')}/${topic}`;
|
||||||
|
|
||||||
|
const response = await this.ctx.fetchT(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'text/plain',
|
||||||
|
'Title': title || 'DashCaddy',
|
||||||
|
'Priority': '3'
|
||||||
|
},
|
||||||
|
body: text
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`ntfy error: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send email notification
|
||||||
|
*/
|
||||||
|
async sendEmail(subject, body) {
|
||||||
|
const { host, port, to, from, username, password, secure } = this.config.providers.email;
|
||||||
|
if (!host || !to) {
|
||||||
|
throw new Error('Email not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create transporter
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host,
|
||||||
|
port: parseInt(port) || 587,
|
||||||
|
secure: !!secure,
|
||||||
|
auth: username ? {
|
||||||
|
user: username,
|
||||||
|
pass: password
|
||||||
|
} : undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send mail
|
||||||
|
await transporter.sendMail({
|
||||||
|
from: from || username,
|
||||||
|
to,
|
||||||
|
subject,
|
||||||
|
text: body,
|
||||||
|
html: `<pre style="font-family: monospace;">${body}</pre>`
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send resource alert
|
||||||
|
*/
|
||||||
|
async sendAlert(alert) {
|
||||||
|
const text = this._formatAlertText(alert);
|
||||||
|
const embed = {
|
||||||
|
title: `⚠️ Resource Alert: ${alert.containerName}`,
|
||||||
|
color: this._getAlertColor(alert.alerts),
|
||||||
|
fields: alert.alerts.map(a => ({
|
||||||
|
name: a.type.toUpperCase(),
|
||||||
|
value: a.message,
|
||||||
|
inline: true
|
||||||
|
})),
|
||||||
|
footer: {
|
||||||
|
text: 'DashCaddy Resource Monitor'
|
||||||
|
},
|
||||||
|
timestamp: alert.timestamp
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.send('alert', { ...alert, text, embed }, 'warning');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send backup complete notification
|
||||||
|
*/
|
||||||
|
async sendBackupComplete(backup) {
|
||||||
|
const event = backup.status === 'success' ? 'backup-complete' : 'backup-failed';
|
||||||
|
const type = backup.status === 'success' ? 'success' : 'error';
|
||||||
|
|
||||||
|
const text = backup.status === 'success'
|
||||||
|
? `✅ Backup "${backup.name}" completed successfully`
|
||||||
|
: `❌ Backup "${backup.name}" failed: ${backup.error}`;
|
||||||
|
|
||||||
|
return this.send(event, { ...backup, text }, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send service event notification (container up/down, deploy success/fail)
|
||||||
|
*/
|
||||||
|
async sendServiceEvent(event, service) {
|
||||||
|
const eventMap = {
|
||||||
|
'container-up': { type: 'success', text: `✅ Container "${service.containerName || service.name}" is now UP` },
|
||||||
|
'container-down': { type: 'error', text: `🔴 Container "${service.containerName || service.name}" is DOWN` },
|
||||||
|
'deploy-success': { type: 'success', text: `✅ "${service.name}" deployed successfully` },
|
||||||
|
'deploy-failed': { type: 'error', text: `❌ "${service.name}" deployment failed` },
|
||||||
|
'auto-restart': { type: 'warning', text: `🔄 Container "${service.containerName || service.name}" auto-restarted` }
|
||||||
|
};
|
||||||
|
|
||||||
|
const info = eventMap[event] || { type: 'info', text: `Service event: ${event}` };
|
||||||
|
return this.send(event, { ...service, text: info.text }, info.type);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Helper Methods =====
|
||||||
|
|
||||||
|
_formatTitle(event) {
|
||||||
|
const titles = {
|
||||||
|
'container-down': 'Container Down',
|
||||||
|
'container-up': 'Container Recovered',
|
||||||
|
'alert': 'Resource Alert',
|
||||||
|
'backup-complete': 'Backup Complete',
|
||||||
|
'backup-failed': 'Backup Failed',
|
||||||
|
'update-available': 'Update Available',
|
||||||
|
'test': 'Test Notification',
|
||||||
|
'auto-restart': 'Auto-Restart',
|
||||||
|
'deploy-success': 'Deployment Success',
|
||||||
|
'deploy-failed': 'Deployment Failed'
|
||||||
|
};
|
||||||
|
return titles[event] || 'DashCaddy Notification';
|
||||||
|
}
|
||||||
|
|
||||||
|
_formatText(data, event) {
|
||||||
|
if (typeof data === 'string') return data;
|
||||||
|
return data.text || data.message || this._formatTitle(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
_formatEmbed(data, event, type) {
|
||||||
|
if (typeof data === 'string') return null;
|
||||||
|
if (data.embed) return data.embed;
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: this._formatTitle(event),
|
||||||
|
description: data.text || data.message || '',
|
||||||
|
color: this._getTypeColor(type),
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
_formatAlertText(alert) {
|
||||||
|
const lines = [
|
||||||
|
`**${alert.containerName}**`,
|
||||||
|
'',
|
||||||
|
...alert.alerts.map(a => `• ${a.message}`)
|
||||||
|
];
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
_getAlertColor(alerts) {
|
||||||
|
if (alerts.some(a => a.severity === 'critical')) return 15158332; // Red
|
||||||
|
if (alerts.some(a => a.severity === 'warning')) return 16776960; // Yellow
|
||||||
|
return 3447003; // Blue
|
||||||
|
}
|
||||||
|
|
||||||
|
_getTypeColor(type) {
|
||||||
|
const colors = {
|
||||||
|
success: 3066993, // Green
|
||||||
|
error: 15158332, // Red
|
||||||
|
warning: 16776960, // Yellow
|
||||||
|
info: 3447003 // Blue
|
||||||
|
};
|
||||||
|
return colors[type] || colors.info;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Health Check Daemon =====
|
||||||
|
|
||||||
|
startHealthDaemon() {
|
||||||
|
if (this.healthDaemonInterval) return;
|
||||||
|
|
||||||
|
const interval = (this.config.healthCheck?.intervalMinutes || 5) * 60 * 1000;
|
||||||
|
this.healthDaemonInterval = setInterval(() => {
|
||||||
|
this.checkHealth().catch(err => {
|
||||||
|
this.log.error('notification', 'Health check failed', { error: err.message });
|
||||||
|
});
|
||||||
|
}, interval);
|
||||||
|
|
||||||
|
this.log.info('notification', 'Health daemon started', { intervalMinutes: this.config.healthCheck?.intervalMinutes });
|
||||||
|
}
|
||||||
|
|
||||||
|
stopHealthDaemon() {
|
||||||
|
if (this.healthDaemonInterval) {
|
||||||
|
clearInterval(this.healthDaemonInterval);
|
||||||
|
this.healthDaemonInterval = null;
|
||||||
|
this.log.info('notification', 'Health daemon stopped');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async checkHealth() {
|
||||||
|
if (!this.config.healthCheck?.enabled || !this.ctx.docker) {
|
||||||
|
return { checked: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const containers = await this.ctx.docker.listContainers({ all: true });
|
||||||
|
const previousState = new Map(this.healthState);
|
||||||
|
|
||||||
|
for (const container of containers) {
|
||||||
|
const name = container.Names[0]?.replace(/^\//, '') || container.Id.substring(0, 12);
|
||||||
|
const wasDown = previousState.get(container.Id) === false;
|
||||||
|
const isDown = container.State !== 'running';
|
||||||
|
|
||||||
|
this.healthState.set(container.Id, isDown);
|
||||||
|
|
||||||
|
if (wasDown && !isDown) {
|
||||||
|
// Container recovered
|
||||||
|
await this.sendServiceEvent('container-up', {
|
||||||
|
containerId: container.Id,
|
||||||
|
containerName: name,
|
||||||
|
state: container.State
|
||||||
|
});
|
||||||
|
} else if (!wasDown && isDown) {
|
||||||
|
// Container went down
|
||||||
|
await this.sendServiceEvent('container-down', {
|
||||||
|
containerId: container.Id,
|
||||||
|
containerName: name,
|
||||||
|
state: container.State
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update last check time
|
||||||
|
this.config.healthCheck = this.config.healthCheck || {};
|
||||||
|
this.config.healthCheck.lastCheck = new Date().toISOString();
|
||||||
|
await this.saveConfig();
|
||||||
|
|
||||||
|
return {
|
||||||
|
checked: true,
|
||||||
|
containersMonitored: containers.length,
|
||||||
|
lastCheck: this.config.healthCheck.lastCheck
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
this.log.error('notification', 'Health check error', { error: error.message });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getHealthState() {
|
||||||
|
return new Map(this.healthState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = NotificationManager;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "dashcaddy-api",
|
"name": "dashcaddy-api",
|
||||||
"version": "1.6.0",
|
"version": "1.11.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": {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ const STATS_FILE = process.env.STATS_FILE || path.join(__dirname, 'container-sta
|
|||||||
const STATS_HOURLY_FILE = process.env.STATS_HOURLY_FILE || path.join(__dirname, 'container-stats-hourly.json');
|
const STATS_HOURLY_FILE = process.env.STATS_HOURLY_FILE || path.join(__dirname, 'container-stats-hourly.json');
|
||||||
const STATS_DAILY_FILE = process.env.STATS_DAILY_FILE || path.join(__dirname, 'container-stats-daily.json');
|
const STATS_DAILY_FILE = process.env.STATS_DAILY_FILE || path.join(__dirname, 'container-stats-daily.json');
|
||||||
const ALERT_CONFIG_FILE = process.env.ALERT_CONFIG_FILE || path.join(__dirname, 'alert-config.json');
|
const ALERT_CONFIG_FILE = process.env.ALERT_CONFIG_FILE || path.join(__dirname, 'alert-config.json');
|
||||||
|
const ALERT_HISTORY_FILE = process.env.ALERT_HISTORY_FILE || path.join(__dirname, 'alert-history.json');
|
||||||
const STATS_RETENTION_HOURS = parseInt(process.env.STATS_RETENTION_HOURS || '168', 10); // 7 days raw
|
const STATS_RETENTION_HOURS = parseInt(process.env.STATS_RETENTION_HOURS || '168', 10); // 7 days raw
|
||||||
const STATS_HOURLY_RETENTION_DAYS = parseInt(process.env.STATS_HOURLY_RETENTION_DAYS || '30', 10); // 30 days hourly
|
const STATS_HOURLY_RETENTION_DAYS = parseInt(process.env.STATS_HOURLY_RETENTION_DAYS || '30', 10); // 30 days hourly
|
||||||
const STATS_DAILY_RETENTION_DAYS = parseInt(process.env.STATS_DAILY_RETENTION_DAYS || '365', 10); // 365 days daily
|
const STATS_DAILY_RETENTION_DAYS = parseInt(process.env.STATS_DAILY_RETENTION_DAYS || '365', 10); // 365 days daily
|
||||||
@@ -35,11 +36,21 @@ class ResourceMonitor extends EventEmitter {
|
|||||||
this.dailyHistory = new Map(); // containerId -> { name, samples: [...] } (daily avg, 365d)
|
this.dailyHistory = new Map(); // containerId -> { name, samples: [...] } (daily avg, 365d)
|
||||||
this.alerts = new Map(); // containerId -> alert config
|
this.alerts = new Map(); // containerId -> alert config
|
||||||
this.lastAlerts = new Map(); // containerId -> last alert timestamp
|
this.lastAlerts = new Map(); // containerId -> last alert timestamp
|
||||||
|
this.alertHistory = []; // alert history entries
|
||||||
|
this.notificationManager = null;
|
||||||
|
|
||||||
this.loadStats();
|
this.loadStats();
|
||||||
this.loadHourlyStats();
|
this.loadHourlyStats();
|
||||||
this.loadDailyStats();
|
this.loadDailyStats();
|
||||||
this.loadAlertConfig();
|
this.loadAlertConfig();
|
||||||
|
this.loadAlertHistory();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the notification manager for sending alerts
|
||||||
|
*/
|
||||||
|
setNotificationManager(nm) {
|
||||||
|
this.notificationManager = nm;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -286,19 +297,57 @@ class ResourceMonitor extends EventEmitter {
|
|||||||
if (alerts.length > 0) {
|
if (alerts.length > 0) {
|
||||||
this.lastAlerts.set(containerId, now);
|
this.lastAlerts.set(containerId, now);
|
||||||
|
|
||||||
this.emit('alert', {
|
// Add alert history entries
|
||||||
|
for (const alert of alerts) {
|
||||||
|
this.addAlertHistoryEntry({
|
||||||
|
id: `${containerId}-${Date.now()}-${alert.type}`,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
containerId,
|
||||||
|
containerName,
|
||||||
|
type: alert.type,
|
||||||
|
metric: alert.type,
|
||||||
|
value: alert.value,
|
||||||
|
threshold: alert.threshold,
|
||||||
|
severity: alert.severity,
|
||||||
|
notified: !!this.notificationManager,
|
||||||
|
autoRestartTriggered: !!alertConfig.autoRestart
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const alertPayload = {
|
||||||
containerId,
|
containerId,
|
||||||
containerName,
|
containerName,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
alerts,
|
alerts,
|
||||||
stats,
|
stats,
|
||||||
config: alertConfig
|
config: alertConfig
|
||||||
|
};
|
||||||
|
|
||||||
|
this.emit('alert', alertPayload);
|
||||||
|
|
||||||
|
// Send notification if manager is configured
|
||||||
|
if (this.notificationManager) {
|
||||||
|
this.notificationManager.sendAlert(alertPayload).catch(err => {
|
||||||
|
console.error('[ResourceMonitor] Failed to send alert notification:', err.message);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Auto-restart if configured
|
// Auto-restart if configured
|
||||||
if (alertConfig.autoRestart) {
|
if (alertConfig.autoRestart) {
|
||||||
this.restartContainer(containerId, containerName, alerts);
|
this.restartContainer(containerId, containerName, alerts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Trigger bundled workflows for resource-alert
|
||||||
|
this.triggerWorkflows('resource-alert', {
|
||||||
|
containerId,
|
||||||
|
containerName,
|
||||||
|
alerts,
|
||||||
|
stats,
|
||||||
|
diskPercent: (stats.disk?.readBytes + stats.disk?.writeBytes) > 0
|
||||||
|
? Math.round((stats.disk.readBytes / (stats.disk.readBytes + stats.disk.writeBytes)) * 100)
|
||||||
|
: 0,
|
||||||
|
host: require('os').hostname()
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,11 +367,55 @@ class ResourceMonitor extends EventEmitter {
|
|||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
reason: alerts
|
reason: alerts
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Send notification if manager is configured
|
||||||
|
if (this.notificationManager) {
|
||||||
|
this.notificationManager.send('auto-restart', {
|
||||||
|
containerId,
|
||||||
|
containerName,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
reason: alerts
|
||||||
|
}).catch(err => {
|
||||||
|
console.error('[ResourceMonitor] Failed to send auto-restart notification:', err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[ResourceMonitor] Failed to restart ${containerName}:`, error.message);
|
console.error(`[ResourceMonitor] Failed to restart ${containerName}:`, error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger bundled workflows for an event
|
||||||
|
*/
|
||||||
|
triggerWorkflows(eventType, eventData) {
|
||||||
|
if (!this.workflowEngine) {
|
||||||
|
console.log('[ResourceMonitor] Workflow engine not set, skipping workflow trigger');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.workflowEngine.triggerForEvent(eventType, eventData)
|
||||||
|
.then(results => {
|
||||||
|
if (results && results.length > 0) {
|
||||||
|
console.log(`[ResourceMonitor] Triggered ${results.length} workflow(s) for ${eventType}`);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.error('[ResourceMonitor] Workflow trigger error:', err.message);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[ResourceMonitor] Error triggering workflows:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the workflow engine for triggering workflows
|
||||||
|
*/
|
||||||
|
setWorkflowEngine(workflowEngine) {
|
||||||
|
this.workflowEngine = workflowEngine;
|
||||||
|
console.log('[ResourceMonitor] Workflow engine configured');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current stats for a container
|
* Get current stats for a container
|
||||||
*/
|
*/
|
||||||
@@ -430,6 +523,62 @@ class ResourceMonitor extends EventEmitter {
|
|||||||
this.saveAlertConfig();
|
this.saveAlertConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all alert configurations
|
||||||
|
*/
|
||||||
|
getAllAlertConfigs() {
|
||||||
|
const configs = {};
|
||||||
|
for (const [containerId, config] of this.alerts.entries()) {
|
||||||
|
configs[containerId] = config;
|
||||||
|
}
|
||||||
|
return configs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add entry to alert history
|
||||||
|
*/
|
||||||
|
addAlertHistoryEntry(entry) {
|
||||||
|
this.alertHistory.unshift(entry);
|
||||||
|
// Keep only last 1000 entries
|
||||||
|
if (this.alertHistory.length > 1000) {
|
||||||
|
this.alertHistory = this.alertHistory.slice(0, 1000);
|
||||||
|
}
|
||||||
|
this.saveAlertHistory();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get alert history
|
||||||
|
*/
|
||||||
|
getAlertHistory(limit = 50) {
|
||||||
|
return this.alertHistory.slice(0, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load alert history from disk
|
||||||
|
*/
|
||||||
|
loadAlertHistory() {
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(ALERT_HISTORY_FILE)) {
|
||||||
|
const data = JSON.parse(fs.readFileSync(ALERT_HISTORY_FILE, 'utf8'));
|
||||||
|
this.alertHistory = Array.isArray(data) ? data : [];
|
||||||
|
console.log(`[ResourceMonitor] Loaded ${this.alertHistory.length} alert history entries`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[ResourceMonitor] Error loading alert history:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save alert history to disk
|
||||||
|
*/
|
||||||
|
saveAlertHistory() {
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(ALERT_HISTORY_FILE, JSON.stringify(this.alertHistory, null, 2));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[ResourceMonitor] Error saving alert history:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cleanup old stats beyond retention period
|
* Cleanup old stats beyond retention period
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -306,7 +306,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
} else {
|
} else {
|
||||||
containerId = await deployContainer(appId, config, template);
|
containerId = await deployContainer(appId, config, template);
|
||||||
log.info('deploy', 'Container deployed', { containerId });
|
log.info('deploy', 'Container deployed', { containerId });
|
||||||
await helpers.waitForHealthCheck(containerId, template.healthCheck, config.port || template.defaultPort);
|
await helpers.waitForHealthCheck(containerId, template.healthCheck, config.port || template.defaultPort, 30);
|
||||||
log.info('deploy', 'Container is healthy', { containerId });
|
log.info('deploy', 'Container is healthy', { containerId });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,7 +316,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
let dnsWarning = null;
|
let dnsWarning = null;
|
||||||
if (config.createDns && !isSubdirectoryMode) {
|
if (config.createDns && !isSubdirectoryMode) {
|
||||||
try {
|
try {
|
||||||
await ctx.dns.createRecord(config.subdomain, config.ip);
|
await ctx.dns.universalCreateRecord(config.subdomain, config.ip);
|
||||||
log.info('deploy', 'DNS record created', { domain: ctx.buildDomain(config.subdomain), ip: config.ip });
|
log.info('deploy', 'DNS record created', { domain: ctx.buildDomain(config.subdomain), ip: config.ip });
|
||||||
} catch (dnsError) {
|
} catch (dnsError) {
|
||||||
await logError('app-deploy-dns', dnsError, { appId, subdomain: config.subdomain, ip: config.ip });
|
await logError('app-deploy-dns', dnsError, { appId, subdomain: config.subdomain, ip: config.ip });
|
||||||
@@ -420,10 +420,11 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
|
|
||||||
res.json(response);
|
res.json(response);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await logError('app-deploy', error, { appId, config });
|
try { await logError('app-deploy', error, { appId, config }); } catch (_) { /* logError failure should not mask original error */ }
|
||||||
log.error('deploy', 'Deployment failed', { appId, error: error.message });
|
const msg = error?.message || String(error || 'Unknown error');
|
||||||
|
log.error('deploy', 'Deployment failed', { appId, error: msg });
|
||||||
const template = ctx.APP_TEMPLATES[appId];
|
const template = ctx.APP_TEMPLATES[appId];
|
||||||
ctx.notification.send('deploymentFailed', 'Deployment Failed', `Failed to deploy **${template?.name || appId}**.\nError: ${error.message}`, 'error');
|
try { ctx.notification.send('deploymentFailed', 'Deployment Failed', `Failed to deploy **${template?.name || appId}**.\nError: ${msg}`, 'error'); } catch (_) {}
|
||||||
errorResponse(res, 500, ctx.safeErrorMessage(error));
|
errorResponse(res, 500, ctx.safeErrorMessage(error));
|
||||||
}
|
}
|
||||||
}, 'apps-deploy'));
|
}, 'apps-deploy'));
|
||||||
|
|||||||
@@ -379,9 +379,12 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
return content.slice(0, endIdx) + injection + content.slice(endIdx);
|
return content.slice(0, endIdx) + injection + content.slice(endIdx);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success && result.error !== 'No changes to apply') {
|
||||||
throw new Error(`[DC-303] Failed to add subpath config for ${subdomain}: ${result.error}`);
|
throw new Error(`[DC-303] Failed to add subpath config for ${subdomain}: ${result.error}`);
|
||||||
}
|
}
|
||||||
|
if (result.error === 'No changes to apply') {
|
||||||
|
log.info('caddy', 'Subpath config already exists, reusing', { subdomain });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove a subpath config block from between its markers in the Caddyfile. */
|
/** Remove a subpath config block from between its markers in the Caddyfile. */
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ module.exports = function(ctx) {
|
|||||||
asyncHandler: ctx.asyncHandler,
|
asyncHandler: ctx.asyncHandler,
|
||||||
errorResponse: ctx.errorResponse,
|
errorResponse: ctx.errorResponse,
|
||||||
log: ctx.log,
|
log: ctx.log,
|
||||||
// Additional context properties needed by routes
|
|
||||||
APP_TEMPLATES: ctx.APP_TEMPLATES,
|
APP_TEMPLATES: ctx.APP_TEMPLATES,
|
||||||
TEMPLATE_CATEGORIES: ctx.TEMPLATE_CATEGORIES,
|
TEMPLATE_CATEGORIES: ctx.TEMPLATE_CATEGORIES,
|
||||||
DIFFICULTY_LEVELS: ctx.DIFFICULTY_LEVELS,
|
DIFFICULTY_LEVELS: ctx.DIFFICULTY_LEVELS,
|
||||||
@@ -40,26 +39,27 @@ module.exports = function(ctx) {
|
|||||||
ctx: ctx
|
ctx: ctx
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initialize helpers with dependencies (ctx is the Koa context)
|
|
||||||
const helpers = initHelpers({ ...deps, ctx });
|
const helpers = initHelpers({ ...deps, ctx });
|
||||||
|
|
||||||
// Mount sub-routes — pass full ctx so sub-routes can reference ctx.* properties
|
|
||||||
const subCtx = Object.assign({}, ctx, { helpers });
|
const subCtx = Object.assign({}, ctx, { helpers });
|
||||||
|
|
||||||
try { router.use('/deploy', initDeploy(subCtx)); }
|
// Mount sub-routers at their prefix paths.
|
||||||
catch(e) { (ctx.log || console).error('[apps] deploy routes init failed:', e.message); }
|
// Sub-modules define routes at '/' (root of their sub-router).
|
||||||
|
// Final paths: /api/v1/apps/deploy, /api/v1/apps/remove, /api/v1/apps/templates, etc.
|
||||||
|
|
||||||
try { router.use('/remove', initRemoval(subCtx)); }
|
try { router.use('/apps', initDeploy(subCtx)); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] removal routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] deploy routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
|
try { router.use('/apps', initRemoval(subCtx)); }
|
||||||
|
catch(e) { (ctx.log || console).error('[apps] removal routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
try { router.use('/apps', initTemplates(subCtx)); }
|
try { router.use('/apps', initTemplates(subCtx)); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] templates routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] templates routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
try { router.use('/restore', initRestore(subCtx)); }
|
try { router.use('/apps', initRestore(Object.assign({}, subCtx, { backupManager: ctx.backupManager }))); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] restore routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] restore routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
try { router.use('/compose', initCompose(subCtx)); }
|
try { router.use('/apps', initCompose(subCtx)); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] compose routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] compose routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -71,18 +71,13 @@ module.exports = function({
|
|||||||
if (shouldDeleteContainer && subdomain && ctx.dns.getToken()) {
|
if (shouldDeleteContainer && subdomain && ctx.dns.getToken()) {
|
||||||
try {
|
try {
|
||||||
const domain = ctx.buildDomain(subdomain);
|
const domain = ctx.buildDomain(subdomain);
|
||||||
const getResult = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/get', {
|
const resolveResult = await ctx.dns.universalResolveRecord(domain, 'A');
|
||||||
token: ctx.dns.getToken(), domain, zone: ctx.siteConfig.tld.replace(/^\./, ''), listZone: 'true'
|
|
||||||
});
|
|
||||||
let recordIp = ip || 'localhost';
|
let recordIp = ip || 'localhost';
|
||||||
if (getResult.status === 'ok' && getResult.response?.records) {
|
if (resolveResult) {
|
||||||
const aRecord = getResult.response.records.find(r => r.type === 'A');
|
recordIp = resolveResult;
|
||||||
if (aRecord && aRecord.rData?.ipAddress) recordIp = aRecord.rData.ipAddress;
|
|
||||||
}
|
}
|
||||||
const dnsResult = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/delete', {
|
await ctx.dns.universalDeleteRecord(domain, recordIp);
|
||||||
token: ctx.dns.getToken(), domain, type: 'A', ipAddress: recordIp
|
results.dns = 'deleted';
|
||||||
});
|
|
||||||
results.dns = dnsResult.status === 'ok' ? 'deleted' : (dnsResult.errorMessage || 'failed');
|
|
||||||
log.info('dns', 'DNS record removal', { result: results.dns });
|
log.info('dns', 'DNS record removal', { result: results.dns });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
results.dns = error.message;
|
results.dns = error.message;
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
const { DOCKER } = require('../../constants');
|
const { DOCKER } = require('../../constants');
|
||||||
|
|
||||||
|
const DEFAULT_BACKUP_DIR = process.env.BACKUP_DIR || path.join(__dirname, '..', 'backups');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Apps restore routes factory
|
* Apps restore routes factory
|
||||||
* @param {Object} deps - Explicit dependencies
|
* @param {Object} deps - Explicit dependencies
|
||||||
@@ -122,6 +126,180 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
|||||||
res.json({ success: true, services: status });
|
res.json({ success: true, services: status });
|
||||||
}, 'apps-restore-status'));
|
}, 'apps-restore-status'));
|
||||||
|
|
||||||
|
// ==================== POINT-IN-TIME RESTORE (BACKUP FILE BASED) ====================
|
||||||
|
|
||||||
|
// Get available backup files for a specific app
|
||||||
|
router.get('/:appId/backup-points', asyncHandler(async (req, res) => {
|
||||||
|
const { appId } = req.params;
|
||||||
|
const backupDir = DEFAULT_BACKUP_DIR;
|
||||||
|
const files = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(backupDir)) {
|
||||||
|
const entries = fs.readdirSync(backupDir, { withFileTypes: true });
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry.isFile() && entry.name.endsWith('.backup')) {
|
||||||
|
try {
|
||||||
|
const nameWithoutExt = entry.name.replace('.backup', '');
|
||||||
|
const parts = nameWithoutExt.split('-');
|
||||||
|
const fileAppId = parts[0];
|
||||||
|
|
||||||
|
// Only include files for the requested app
|
||||||
|
if (fileAppId !== appId) continue;
|
||||||
|
|
||||||
|
const filepath = path.join(backupDir, entry.name);
|
||||||
|
const stats = fs.statSync(filepath);
|
||||||
|
const timestamp = parts.length > 1 ? parseInt(parts[parts.length - 1]) : stats.mtimeMs;
|
||||||
|
|
||||||
|
files.push({
|
||||||
|
name: entry.name,
|
||||||
|
appId: fileAppId,
|
||||||
|
size: stats.size,
|
||||||
|
sizeFormatted: formatBytes(stats.size),
|
||||||
|
timestamp: new Date(timestamp).toISOString(),
|
||||||
|
modified: stats.mtime.toISOString(),
|
||||||
|
path: filepath
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// Skip malformed filenames
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Directory might not exist yet
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by timestamp descending (newest first)
|
||||||
|
files.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
appId,
|
||||||
|
isBackupFile: true,
|
||||||
|
files,
|
||||||
|
total: files.length
|
||||||
|
});
|
||||||
|
}, 'apps-backup-points'));
|
||||||
|
|
||||||
|
// Revert a specific app to a backup file (point-in-time restore)
|
||||||
|
router.post('/:appId/revert/:filename', asyncHandler(async (req, res) => {
|
||||||
|
const { appId, filename } = req.params;
|
||||||
|
const { encryptionKey, restartContainers } = req.body || {};
|
||||||
|
|
||||||
|
// Security: prevent path traversal
|
||||||
|
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||||
|
return res.status(400).json({ success: false, error: 'Invalid filename' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const filepath = path.join(DEFAULT_BACKUP_DIR, filename);
|
||||||
|
if (!fs.existsSync(filepath)) {
|
||||||
|
return res.status(404).json({ success: false, error: `Backup file not found: ${filename}` });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Read the backup file
|
||||||
|
let fileData = fs.readFileSync(filepath);
|
||||||
|
|
||||||
|
// Decrypt if needed
|
||||||
|
if (encryptionKey) {
|
||||||
|
try {
|
||||||
|
fileData = await backupManager.decryptBackup(fileData, encryptionKey);
|
||||||
|
} catch (err) {
|
||||||
|
return res.status(400).json({ success: false, error: 'Failed to decrypt backup: ' + err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress
|
||||||
|
const backupData = await backupManager.decompressBackup(fileData);
|
||||||
|
|
||||||
|
// Extract to temp directory
|
||||||
|
const os = require('os');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const tempDir = path.join(os.tmpdir(), `dashcaddy-revert-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`);
|
||||||
|
fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tarPath = path.join(tempDir, 'backup.tar.gz');
|
||||||
|
fs.writeFileSync(tarPath, backupData);
|
||||||
|
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
try {
|
||||||
|
execSync(`cd "${tempDir}" && tar -xzf backup.tar.gz`, { stdio: 'pipe' });
|
||||||
|
} catch (tarErr) {
|
||||||
|
throw new Error('Failed to extract backup archive: ' + tarErr.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read manifest if present
|
||||||
|
let manifest = null;
|
||||||
|
const manifestPath = path.join(tempDir, 'manifest.json');
|
||||||
|
if (fs.existsSync(manifestPath)) {
|
||||||
|
try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read app-specific data
|
||||||
|
const appServicesPath = path.join(tempDir, 'services.json');
|
||||||
|
const appConfigPath = path.join(tempDir, 'config.json');
|
||||||
|
const appCredsPath = path.join(tempDir, 'credentials.json');
|
||||||
|
|
||||||
|
let restoreData = { services: null, config: null, credentials: null };
|
||||||
|
|
||||||
|
if (fs.existsSync(appServicesPath)) {
|
||||||
|
try { restoreData.services = JSON.parse(fs.readFileSync(appServicesPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
if (fs.existsSync(appConfigPath)) {
|
||||||
|
try { restoreData.config = JSON.parse(fs.readFileSync(appConfigPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
if (fs.existsSync(appCredsPath)) {
|
||||||
|
try { restoreData.credentials = JSON.parse(fs.readFileSync(appCredsPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If restartContainers is true, actually perform the restore
|
||||||
|
if (restartContainers) {
|
||||||
|
if (restoreData.services) backupManager.restoreServices(restoreData.services);
|
||||||
|
if (restoreData.config) backupManager.restoreConfig(restoreData.config);
|
||||||
|
if (restoreData.credentials) backupManager.restoreCredentials(restoreData.credentials);
|
||||||
|
|
||||||
|
// Cleanup temp dir
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
isBackupFile: true,
|
||||||
|
restored: {
|
||||||
|
services: !!restoreData.services,
|
||||||
|
config: !!restoreData.config,
|
||||||
|
credentials: !!restoreData.credentials
|
||||||
|
},
|
||||||
|
message: `${appId} reverted to backup successfully`
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Preview mode
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
isBackupFile: true,
|
||||||
|
preview: true,
|
||||||
|
filename,
|
||||||
|
appId,
|
||||||
|
manifest,
|
||||||
|
restoreData: {
|
||||||
|
hasServices: !!restoreData.services,
|
||||||
|
hasConfig: !!restoreData.config,
|
||||||
|
hasCredentials: !!restoreData.credentials
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch (_) {}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ success: false, error: err.message });
|
||||||
|
}
|
||||||
|
}, 'apps-revert'));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Core restore logic for a single service.
|
* Core restore logic for a single service.
|
||||||
*/
|
*/
|
||||||
@@ -280,7 +458,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
|||||||
// DNS record
|
// DNS record
|
||||||
if (manifest.config.createDns && manifest.caddy.routingMode !== 'subdirectory') {
|
if (manifest.config.createDns && manifest.caddy.routingMode !== 'subdirectory') {
|
||||||
try {
|
try {
|
||||||
await ctx.dns.createRecord(manifest.config.subdomain, manifest.config.ip);
|
await ctx.dns.universalCreateRecord(manifest.config.subdomain, manifest.config.ip);
|
||||||
log.info('restore', 'DNS record recreated', { subdomain: manifest.config.subdomain });
|
log.info('restore', 'DNS record recreated', { subdomain: manifest.config.subdomain });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.warn('restore', `DNS recreation failed: ${e.message}`);
|
log.warn('restore', `DNS recreation failed: ${e.message}`);
|
||||||
@@ -309,3 +487,12 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
|||||||
|
|
||||||
return router;
|
return router;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Helper: format bytes to human readable
|
||||||
|
function formatBytes(bytes) {
|
||||||
|
if (bytes === 0) return '0 B';
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||||
|
}
|
||||||
|
|||||||
@@ -107,10 +107,8 @@ module.exports = function({
|
|||||||
if (oldSubdomain && ctx.dns.getToken()) {
|
if (oldSubdomain && ctx.dns.getToken()) {
|
||||||
try {
|
try {
|
||||||
const oldDomain = oldSubdomain.includes('.') ? oldSubdomain : ctx.buildDomain(oldSubdomain);
|
const oldDomain = oldSubdomain.includes('.') ? oldSubdomain : ctx.buildDomain(oldSubdomain);
|
||||||
const result = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/delete', {
|
await ctx.dns.universalDeleteRecord(oldDomain, ip || 'localhost');
|
||||||
token: ctx.dns.getToken(), domain: oldDomain, type: 'A', ipAddress: ip || 'localhost'
|
results.oldDns = 'deleted';
|
||||||
});
|
|
||||||
results.oldDns = result.status === 'ok' ? 'deleted' : result.errorMessage;
|
|
||||||
log.info('dns', 'Old DNS record deleted', { domain: oldDomain });
|
log.info('dns', 'Old DNS record deleted', { domain: oldDomain });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
results.oldDns = `failed: ${error.message}`;
|
results.oldDns = `failed: ${error.message}`;
|
||||||
@@ -120,7 +118,7 @@ module.exports = function({
|
|||||||
|
|
||||||
if (newSubdomain && ctx.dns.getToken()) {
|
if (newSubdomain && ctx.dns.getToken()) {
|
||||||
try {
|
try {
|
||||||
await ctx.dns.createRecord(newSubdomain, ip || 'localhost');
|
await ctx.dns.universalCreateRecord(newSubdomain, ip || 'localhost');
|
||||||
results.newDns = 'created';
|
results.newDns = 'created';
|
||||||
log.info('dns', 'New DNS record created', { domain: ctx.buildDomain(newSubdomain) });
|
log.info('dns', 'New DNS record created', { domain: ctx.buildDomain(newSubdomain) });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
/**
|
||||||
|
* Auto-Restart Policy Routes
|
||||||
|
*
|
||||||
|
* CRUD endpoints for per-container auto-restart policies.
|
||||||
|
* Also provides a dry-run test endpoint.
|
||||||
|
*
|
||||||
|
* @module routes/auto-restart
|
||||||
|
*/
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const { success } = require('../response-helpers');
|
||||||
|
const { ValidationError, NotFoundError } = require('../errors');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auto-restart route factory
|
||||||
|
*
|
||||||
|
* @param {Object} deps - Explicit dependencies
|
||||||
|
* @param {Object} deps.autoRestartManager - AutoRestartManager instance
|
||||||
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||||
|
* @param {Function} deps.logError - Error logging function
|
||||||
|
* @returns {express.Router}
|
||||||
|
*/
|
||||||
|
module.exports = function ({ autoRestartManager, asyncHandler, logError }) {
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /auto-restart/policies
|
||||||
|
* List all configured auto-restart policies.
|
||||||
|
*/
|
||||||
|
router.get('/policies', asyncHandler(async (_req, res) => {
|
||||||
|
const policies = autoRestartManager.listPolicies();
|
||||||
|
success(res, { policies });
|
||||||
|
}, 'auto-restart-list'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /auto-restart/policies/:serviceId
|
||||||
|
* Get the restart policy for a single service.
|
||||||
|
*/
|
||||||
|
router.get('/policies/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
|
||||||
|
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||||
|
throw new ValidationError('Invalid service ID format');
|
||||||
|
}
|
||||||
|
|
||||||
|
const policy = autoRestartManager.getPolicy(serviceId);
|
||||||
|
if (!policy) {
|
||||||
|
throw new NotFoundError(`Auto-restart policy for "${serviceId}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, { policy });
|
||||||
|
}, 'auto-restart-get'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /auto-restart/policies/:serviceId
|
||||||
|
* Create or update a restart policy.
|
||||||
|
*
|
||||||
|
* Body: { enabled, maxRetries, retryIntervalMs, windowMinutes }
|
||||||
|
*/
|
||||||
|
router.post('/policies/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
|
||||||
|
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||||
|
throw new ValidationError('Invalid service ID format');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { enabled, maxRetries, retryIntervalMs, windowMinutes } = req.body;
|
||||||
|
|
||||||
|
// Validate inputs
|
||||||
|
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
||||||
|
throw new ValidationError('enabled must be a boolean');
|
||||||
|
}
|
||||||
|
if (maxRetries !== undefined) {
|
||||||
|
if (!Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 100) {
|
||||||
|
throw new ValidationError('maxRetries must be an integer between 0 and 100');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (retryIntervalMs !== undefined) {
|
||||||
|
if (!Number.isInteger(retryIntervalMs) || retryIntervalMs < 0 || retryIntervalMs > 3600000) {
|
||||||
|
throw new ValidationError('retryIntervalMs must be an integer between 0 and 3600000');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (windowMinutes !== undefined) {
|
||||||
|
if (!Number.isInteger(windowMinutes) || windowMinutes < 0 || windowMinutes > 1440) {
|
||||||
|
throw new ValidationError('windowMinutes must be an integer between 0 and 1440');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const policy = await autoRestartManager.setPolicy(serviceId, {
|
||||||
|
...(enabled !== undefined && { enabled }),
|
||||||
|
...(maxRetries !== undefined && { maxRetries }),
|
||||||
|
...(retryIntervalMs !== undefined && { retryIntervalMs }),
|
||||||
|
...(windowMinutes !== undefined && { windowMinutes }),
|
||||||
|
});
|
||||||
|
|
||||||
|
success(res, { policy, message: `Policy ${serviceId} saved` });
|
||||||
|
}, 'auto-restart-set'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DELETE /auto-restart/policies/:serviceId
|
||||||
|
* Remove a restart policy.
|
||||||
|
*/
|
||||||
|
router.delete('/policies/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
|
||||||
|
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||||
|
throw new ValidationError('Invalid service ID format');
|
||||||
|
}
|
||||||
|
|
||||||
|
const removed = await autoRestartManager.removePolicy(serviceId);
|
||||||
|
if (!removed) {
|
||||||
|
throw new NotFoundError(`Auto-restart policy for "${serviceId}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, { message: `Policy for "${serviceId}" removed` });
|
||||||
|
}, 'auto-restart-delete'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /auto-restart/policies/:serviceId/test
|
||||||
|
* Dry-run: simulate a restart attempt without actually restarting.
|
||||||
|
* Returns what *would* happen given the current policy state.
|
||||||
|
*/
|
||||||
|
router.post('/policies/:serviceId/test', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
|
||||||
|
if (!serviceId || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/.test(serviceId)) {
|
||||||
|
throw new ValidationError('Invalid service ID format');
|
||||||
|
}
|
||||||
|
|
||||||
|
const policy = autoRestartManager.getPolicy(serviceId);
|
||||||
|
if (!policy) {
|
||||||
|
throw new NotFoundError(`Auto-restart policy for "${serviceId}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const inCooldown = policy.cooldownUntil && now < policy.cooldownUntil;
|
||||||
|
const wouldRetry = !inCooldown && policy.currentRetries < policy.maxRetries;
|
||||||
|
const nextAttempt = policy.currentRetries + 1;
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
dryRun: true,
|
||||||
|
serviceId,
|
||||||
|
policy: {
|
||||||
|
enabled: policy.enabled,
|
||||||
|
currentRetries: policy.currentRetries,
|
||||||
|
maxRetries: policy.maxRetries,
|
||||||
|
cooldownUntil: policy.cooldownUntil,
|
||||||
|
inCooldown,
|
||||||
|
},
|
||||||
|
wouldRestart: policy.enabled && wouldRetry,
|
||||||
|
wouldMaxOut: !wouldRetry && !inCooldown,
|
||||||
|
nextAttempt: wouldRetry ? nextAttempt : null,
|
||||||
|
message: !policy.enabled
|
||||||
|
? 'Policy is disabled — no restart would occur'
|
||||||
|
: inCooldown
|
||||||
|
? `In cooldown until ${new Date(policy.cooldownUntil).toISOString()} — would skip`
|
||||||
|
: wouldRetry
|
||||||
|
? `Would attempt restart ${nextAttempt}/${policy.maxRetries}`
|
||||||
|
: `Max retries (${policy.maxRetries}) already reached — would enter cooldown`,
|
||||||
|
});
|
||||||
|
}, 'auto-restart-test'));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
};
|
||||||
@@ -1,16 +1,470 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const { success } = require('../response-helpers');
|
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');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Backups routes factory
|
* Backups routes factory
|
||||||
* @param {Object} deps - Explicit dependencies
|
* @param {Object} deps - Explicit dependencies
|
||||||
* @param {Object} deps.backupManager - Backup management module
|
* @param {Object} deps.backupManager - Backup management module
|
||||||
|
* @param {Object} deps.licenseManager - License manager for premium gating
|
||||||
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||||
* @returns {express.Router}
|
* @returns {express.Router}
|
||||||
*/
|
*/
|
||||||
module.exports = function({ backupManager, asyncHandler }) {
|
module.exports = function({ backupManager, licenseManager, asyncHandler }) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
// ==================== SCHEDULE ENDPOINTS (PREMIUM) ====================
|
||||||
|
|
||||||
|
// Apply premium gating to schedule-related routes
|
||||||
|
const premiumGating = licenseManager.requirePremium('auto-backup');
|
||||||
|
|
||||||
|
// Get all scheduled backup configs
|
||||||
|
router.get('/backups/schedule', premiumGating, asyncHandler(async (req, res) => {
|
||||||
|
const config = backupManager.getConfig();
|
||||||
|
const backups = config.backups || {};
|
||||||
|
|
||||||
|
// Calculate next run times based on schedule and last history entry
|
||||||
|
const history = backupManager.getHistory(1000);
|
||||||
|
const schedules = Object.entries(backups).map(([appId, backup]) => {
|
||||||
|
const appHistory = history.filter(h => h.name === appId && h.status === 'success');
|
||||||
|
const lastRun = appHistory.length > 0 ? new Date(appHistory[0].timestamp) : null;
|
||||||
|
const nextRun = calculateNextRun(lastRun, backup.schedule);
|
||||||
|
|
||||||
|
return {
|
||||||
|
appId,
|
||||||
|
enabled: backup.enabled || false,
|
||||||
|
schedule: backup.schedule || 'daily',
|
||||||
|
retention: backup.retention || { keep: 7, olderThan: null },
|
||||||
|
runImmediately: backup.runImmediately || false,
|
||||||
|
destination: backup.destination || 'local',
|
||||||
|
destinationPath: backup.destinationPath || DEFAULT_BACKUP_DIR,
|
||||||
|
lastRun: lastRun ? lastRun.toISOString() : null,
|
||||||
|
nextRun: nextRun ? nextRun.toISOString() : null,
|
||||||
|
lastBackupId: appHistory.length > 0 ? appHistory[0].id : null
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
success(res, { schedules });
|
||||||
|
}, 'backups-schedule-list'));
|
||||||
|
|
||||||
|
// 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 } = req.body;
|
||||||
|
|
||||||
|
if (!appId) {
|
||||||
|
const { ValidationError } = require('../errors');
|
||||||
|
throw new ValidationError('appId is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = backupManager.getConfig();
|
||||||
|
if (!config.backups) config.backups = {};
|
||||||
|
|
||||||
|
// Build the backup config for this app
|
||||||
|
const backupConfig = {
|
||||||
|
enabled: enabled !== undefined ? enabled : true,
|
||||||
|
schedule: schedule || 'daily',
|
||||||
|
retention: retention || { keep: 7, olderThan: null },
|
||||||
|
runImmediately: runImmediately || false,
|
||||||
|
destination: destination || 'local',
|
||||||
|
destinationPath: destinationPath || DEFAULT_BACKUP_DIR,
|
||||||
|
include: ['all'],
|
||||||
|
destinations: [{ type: destination || 'local', path: destinationPath || DEFAULT_BACKUP_DIR }]
|
||||||
|
};
|
||||||
|
|
||||||
|
config.backups[appId] = backupConfig;
|
||||||
|
backupManager.updateConfig(config);
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: `Backup schedule ${enabled === false ? 'disabled' : 'updated'} for ${appId}`,
|
||||||
|
schedule: {
|
||||||
|
appId,
|
||||||
|
...backupConfig,
|
||||||
|
retention: backupConfig.retention
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 'backups-schedule-update'));
|
||||||
|
|
||||||
|
// Remove scheduled backup for an app
|
||||||
|
router.delete('/backups/schedule/:appId', premiumGating, asyncHandler(async (req, res) => {
|
||||||
|
const { appId } = req.params;
|
||||||
|
const config = backupManager.getConfig();
|
||||||
|
|
||||||
|
if (!config.backups || !config.backups[appId]) {
|
||||||
|
const { NotFoundError } = require('../errors');
|
||||||
|
throw new NotFoundError(`No backup schedule found for app: ${appId}`, 'DC-404');
|
||||||
|
}
|
||||||
|
|
||||||
|
delete config.backups[appId];
|
||||||
|
backupManager.updateConfig(config);
|
||||||
|
|
||||||
|
success(res, { message: `Backup schedule removed for ${appId}` });
|
||||||
|
}, 'backups-schedule-delete'));
|
||||||
|
|
||||||
|
// List backup files on disk
|
||||||
|
router.get('/backups/files', asyncHandler(async (req, res) => {
|
||||||
|
const backupDir = DEFAULT_BACKUP_DIR;
|
||||||
|
const files = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(backupDir)) {
|
||||||
|
const entries = fs.readdirSync(backupDir, { withFileTypes: true });
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry.isFile() && entry.name.endsWith('.backup')) {
|
||||||
|
try {
|
||||||
|
const filepath = path.join(backupDir, entry.name);
|
||||||
|
const stats = fs.statSync(filepath);
|
||||||
|
const nameWithoutExt = entry.name.replace('.backup', '');
|
||||||
|
const parts = nameWithoutExt.split('-');
|
||||||
|
const appId = parts[0];
|
||||||
|
const timestamp = parts.length > 1 ? parseInt(parts[parts.length - 1]) : stats.mtimeMs;
|
||||||
|
|
||||||
|
files.push({
|
||||||
|
name: entry.name,
|
||||||
|
appId,
|
||||||
|
size: stats.size,
|
||||||
|
sizeFormatted: formatBytes(stats.size),
|
||||||
|
timestamp: new Date(timestamp).toISOString(),
|
||||||
|
path: filepath
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// Skip malformed filenames
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Directory might not exist yet
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by timestamp descending (newest first)
|
||||||
|
files.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
|
||||||
|
|
||||||
|
success(res, { files, total: files.length });
|
||||||
|
}, 'backups-files-list'));
|
||||||
|
|
||||||
|
// Trigger immediate backup for an app
|
||||||
|
router.post('/backups/backup/:appId', asyncHandler(async (req, res) => {
|
||||||
|
const { appId } = req.params;
|
||||||
|
const config = backupManager.getConfig();
|
||||||
|
|
||||||
|
const backupConfig = config.backups && config.backups[appId];
|
||||||
|
if (!backupConfig) {
|
||||||
|
const { NotFoundError } = require('../errors');
|
||||||
|
throw new NotFoundError(`No backup schedule found for app: ${appId}`, 'DC-404');
|
||||||
|
}
|
||||||
|
|
||||||
|
const backup = await backupManager.executeBackup(appId, {
|
||||||
|
...backupConfig,
|
||||||
|
destinations: backupConfig.destinations || [{ type: backupConfig.destination || 'local', path: backupConfig.destinationPath || DEFAULT_BACKUP_DIR }]
|
||||||
|
});
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: `Backup started for ${appId}`,
|
||||||
|
backup: {
|
||||||
|
id: backup.id,
|
||||||
|
name: backup.name,
|
||||||
|
timestamp: backup.timestamp,
|
||||||
|
size: backup.size,
|
||||||
|
status: backup.status
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 'backups-backup-trigger'));
|
||||||
|
|
||||||
|
// List backup files for a specific app
|
||||||
|
router.get('/backups/files/:appId', asyncHandler(async (req, res) => {
|
||||||
|
const { appId } = req.params;
|
||||||
|
const backupDir = DEFAULT_BACKUP_DIR;
|
||||||
|
const files = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(backupDir)) {
|
||||||
|
const entries = fs.readdirSync(backupDir, { withFileTypes: true });
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry.isFile() && entry.name.endsWith('.backup')) {
|
||||||
|
try {
|
||||||
|
const nameWithoutExt = entry.name.replace('.backup', '');
|
||||||
|
const parts = nameWithoutExt.split('-');
|
||||||
|
const fileAppId = parts[0];
|
||||||
|
|
||||||
|
// Only include files for the requested app
|
||||||
|
if (fileAppId !== appId) continue;
|
||||||
|
|
||||||
|
const filepath = path.join(backupDir, entry.name);
|
||||||
|
const stats = fs.statSync(filepath);
|
||||||
|
const timestamp = parts.length > 1 ? parseInt(parts[parts.length - 1]) : stats.mtimeMs;
|
||||||
|
|
||||||
|
files.push({
|
||||||
|
name: entry.name,
|
||||||
|
appId: fileAppId,
|
||||||
|
size: stats.size,
|
||||||
|
sizeFormatted: formatBytes(stats.size),
|
||||||
|
timestamp: new Date(timestamp).toISOString(),
|
||||||
|
path: filepath
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// Skip malformed filenames
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Directory might not exist yet
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by timestamp descending (newest first)
|
||||||
|
files.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
|
||||||
|
|
||||||
|
success(res, { files, total: files.length });
|
||||||
|
}, 'backups-files-app'));
|
||||||
|
|
||||||
|
// Restore from a specific backup file on disk
|
||||||
|
router.post('/backups/restore-file/:filename', asyncHandler(async (req, res) => {
|
||||||
|
const { filename } = req.params;
|
||||||
|
const { encryptionKey, restartContainers } = req.body || {};
|
||||||
|
|
||||||
|
// Security: prevent path traversal
|
||||||
|
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||||
|
const { ValidationError } = require('../errors');
|
||||||
|
throw new ValidationError('Invalid filename');
|
||||||
|
}
|
||||||
|
|
||||||
|
const filepath = path.join(DEFAULT_BACKUP_DIR, filename);
|
||||||
|
if (!fs.existsSync(filepath)) {
|
||||||
|
const { NotFoundError } = require('../errors');
|
||||||
|
throw new NotFoundError(`Backup file not found: ${filename}`, 'DC-404');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the backup file
|
||||||
|
let fileData = fs.readFileSync(filepath);
|
||||||
|
|
||||||
|
// Decrypt if needed (format: iv:authTag:encrypted base64)
|
||||||
|
if (encryptionKey) {
|
||||||
|
try {
|
||||||
|
fileData = await backupManager.decryptBackup(fileData, encryptionKey);
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error('Failed to decrypt backup: ' + err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress
|
||||||
|
const backupData = await backupManager.decompressBackup(fileData);
|
||||||
|
|
||||||
|
// Extract to temp directory for inspection/restoration
|
||||||
|
const os = require('os');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const tempDir = path.join(os.tmpdir(), `dashcaddy-restore-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`);
|
||||||
|
fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Write the decompressed JSON as a tar.gz to extract
|
||||||
|
const tarPath = path.join(tempDir, 'backup.tar.gz');
|
||||||
|
fs.writeFileSync(tarPath, backupData);
|
||||||
|
|
||||||
|
// Extract tar.gz
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
try {
|
||||||
|
execSync(`cd "${tempDir}" && tar -xzf backup.tar.gz`, { stdio: 'pipe' });
|
||||||
|
} catch (tarErr) {
|
||||||
|
throw new Error('Failed to extract backup archive: ' + tarErr.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read manifest if present
|
||||||
|
const manifestPath = path.join(tempDir, 'manifest.json');
|
||||||
|
let manifest = null;
|
||||||
|
if (fs.existsSync(manifestPath)) {
|
||||||
|
try {
|
||||||
|
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||||
|
} catch (_) { /* ignore malformed manifest */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read extracted data files
|
||||||
|
const restoreData = {
|
||||||
|
services: null,
|
||||||
|
config: null,
|
||||||
|
credentials: null,
|
||||||
|
volumes: null
|
||||||
|
};
|
||||||
|
|
||||||
|
const servicesPath = path.join(tempDir, 'services.json');
|
||||||
|
if (fs.existsSync(servicesPath)) {
|
||||||
|
try { restoreData.services = JSON.parse(fs.readFileSync(servicesPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
const configPath = path.join(tempDir, 'config.json');
|
||||||
|
if (fs.existsSync(configPath)) {
|
||||||
|
try { restoreData.config = JSON.parse(fs.readFileSync(configPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
const credsPath = path.join(tempDir, 'credentials.json');
|
||||||
|
if (fs.existsSync(credsPath)) {
|
||||||
|
try { restoreData.credentials = JSON.parse(fs.readFileSync(credsPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
const volumesPath = path.join(tempDir, 'volumes.json');
|
||||||
|
if (fs.existsSync(volumesPath)) {
|
||||||
|
try { restoreData.volumes = JSON.parse(fs.readFileSync(volumesPath, 'utf8')); } catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If restartContainers is true, actually perform the restore
|
||||||
|
if (restartContainers) {
|
||||||
|
if (restoreData.services) {
|
||||||
|
backupManager.restoreServices(restoreData.services);
|
||||||
|
}
|
||||||
|
if (restoreData.config) {
|
||||||
|
backupManager.restoreConfig(restoreData.config);
|
||||||
|
}
|
||||||
|
if (restoreData.credentials) {
|
||||||
|
backupManager.restoreCredentials(restoreData.credentials);
|
||||||
|
}
|
||||||
|
if (restoreData.volumes) {
|
||||||
|
await backupManager.restoreVolumes(restoreData.volumes);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cleanup temp dir
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
restored: {
|
||||||
|
services: !!restoreData.services,
|
||||||
|
config: !!restoreData.config,
|
||||||
|
credentials: !!restoreData.credentials,
|
||||||
|
volumes: !!restoreData.volumes
|
||||||
|
},
|
||||||
|
message: 'Backup restored successfully'
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Preview mode: return what would be restored
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
success(res, {
|
||||||
|
preview: true,
|
||||||
|
filename,
|
||||||
|
size: fs.statSync(filepath).size,
|
||||||
|
sizeFormatted: formatBytes(fs.statSync(filepath).size),
|
||||||
|
manifest,
|
||||||
|
restoreData: {
|
||||||
|
hasServices: !!restoreData.services,
|
||||||
|
hasConfig: !!restoreData.config,
|
||||||
|
hasCredentials: !!restoreData.credentials,
|
||||||
|
hasVolumes: !!restoreData.volumes
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Cleanup on error
|
||||||
|
try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch (_) {}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}, 'backups-restore-file'));
|
||||||
|
|
||||||
|
// Compare a backup file against current state
|
||||||
|
router.post('/backups/compare/:filename', asyncHandler(async (req, res) => {
|
||||||
|
const { filename } = req.params;
|
||||||
|
const { encryptionKey } = req.body || {};
|
||||||
|
|
||||||
|
// Security: prevent path traversal
|
||||||
|
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
|
||||||
|
const { ValidationError } = require('../errors');
|
||||||
|
throw new ValidationError('Invalid filename');
|
||||||
|
}
|
||||||
|
|
||||||
|
const filepath = path.join(DEFAULT_BACKUP_DIR, filename);
|
||||||
|
if (!fs.existsSync(filepath)) {
|
||||||
|
const { NotFoundError } = require('../errors');
|
||||||
|
throw new NotFoundError(`Backup file not found: ${filename}`, 'DC-404');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the backup file
|
||||||
|
let fileData = fs.readFileSync(filepath);
|
||||||
|
|
||||||
|
// Decrypt if needed
|
||||||
|
if (encryptionKey) {
|
||||||
|
try {
|
||||||
|
fileData = await backupManager.decryptBackup(fileData, encryptionKey);
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error('Failed to decrypt backup: ' + err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress
|
||||||
|
const backupData = await backupManager.decompressBackup(fileData);
|
||||||
|
|
||||||
|
// Extract to temp directory
|
||||||
|
const os = require('os');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const tempDir = path.join(os.tmpdir(), `dashcaddy-compare-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`);
|
||||||
|
fs.mkdirSync(tempDir, { recursive: true });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tarPath = path.join(tempDir, 'backup.tar.gz');
|
||||||
|
fs.writeFileSync(tarPath, backupData);
|
||||||
|
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
try {
|
||||||
|
execSync(`cd "${tempDir}" && tar -xzf backup.tar.gz`, { stdio: 'pipe' });
|
||||||
|
} catch (tarErr) {
|
||||||
|
throw new Error('Failed to extract backup archive: ' + tarErr.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build diff
|
||||||
|
const diff = {
|
||||||
|
filename,
|
||||||
|
timestamp: fs.statSync(filepath).mtime.toISOString(),
|
||||||
|
size: fs.statSync(filepath).size,
|
||||||
|
sizeFormatted: formatBytes(fs.statSync(filepath).size),
|
||||||
|
services: null,
|
||||||
|
config: null
|
||||||
|
};
|
||||||
|
|
||||||
|
// Compare services.json
|
||||||
|
const servicesPath = path.join(tempDir, 'services.json');
|
||||||
|
if (fs.existsSync(servicesPath)) {
|
||||||
|
try {
|
||||||
|
const backupServices = JSON.parse(fs.readFileSync(servicesPath, 'utf8'));
|
||||||
|
const currentServicesPath = process.env.SERVICES_FILE || path.join(__dirname, 'services.json');
|
||||||
|
let currentServices = null;
|
||||||
|
if (fs.existsSync(currentServicesPath)) {
|
||||||
|
currentServices = JSON.parse(fs.readFileSync(currentServicesPath, 'utf8'));
|
||||||
|
}
|
||||||
|
diff.services = {
|
||||||
|
backup: backupServices,
|
||||||
|
current: currentServices,
|
||||||
|
hasChanges: JSON.stringify(backupServices) !== JSON.stringify(currentServices),
|
||||||
|
backupCount: Array.isArray(backupServices) ? backupServices.length : 0,
|
||||||
|
currentCount: Array.isArray(currentServices) ? currentServices.length : 0
|
||||||
|
};
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare config.json
|
||||||
|
const configPath = path.join(tempDir, 'config.json');
|
||||||
|
if (fs.existsSync(configPath)) {
|
||||||
|
try {
|
||||||
|
const backupConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
||||||
|
const currentConfigPath = process.env.CONFIG_FILE || path.join(__dirname, 'config.json');
|
||||||
|
let currentConfig = null;
|
||||||
|
if (fs.existsSync(currentConfigPath)) {
|
||||||
|
currentConfig = JSON.parse(fs.readFileSync(currentConfigPath, 'utf8'));
|
||||||
|
}
|
||||||
|
diff.config = {
|
||||||
|
backup: backupConfig,
|
||||||
|
current: currentConfig,
|
||||||
|
hasChanges: JSON.stringify(backupConfig) !== JSON.stringify(currentConfig)
|
||||||
|
};
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
success(res, { diff });
|
||||||
|
} catch (err) {
|
||||||
|
try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch (_) {}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}, 'backups-compare'));
|
||||||
|
|
||||||
|
// ==================== EXISTING ENDPOINTS ====================
|
||||||
|
|
||||||
// Get backup configuration
|
// Get backup configuration
|
||||||
router.get('/backups/config', asyncHandler(async (req, res) => {
|
router.get('/backups/config', asyncHandler(async (req, res) => {
|
||||||
const config = backupManager.getConfig();
|
const config = backupManager.getConfig();
|
||||||
@@ -154,3 +608,48 @@ module.exports = function({ backupManager, asyncHandler }) {
|
|||||||
|
|
||||||
return router;
|
return router;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Helper functions
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate next run time based on schedule and last run
|
||||||
|
*/
|
||||||
|
function calculateNextRun(lastRun, schedule) {
|
||||||
|
if (!lastRun) return null;
|
||||||
|
|
||||||
|
const intervals = {
|
||||||
|
'hourly': 60 * 60 * 1000,
|
||||||
|
'daily': 24 * 60 * 60 * 1000,
|
||||||
|
'weekly': 7 * 24 * 60 * 60 * 1000,
|
||||||
|
'monthly': 30 * 24 * 60 * 60 * 1000
|
||||||
|
};
|
||||||
|
|
||||||
|
const baseInterval = intervals[schedule];
|
||||||
|
|
||||||
|
if (baseInterval) {
|
||||||
|
return new Date(lastRun.getTime() + baseInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom interval (e.g., "6h", "30m", "6" for 6 minutes)
|
||||||
|
const match = schedule.match(/^(\d+)([mh])?$/);
|
||||||
|
if (match) {
|
||||||
|
const value = parseInt(match[1]);
|
||||||
|
const unit = match[2] || 'm'; // default to minutes
|
||||||
|
const ms = unit === 'h' ? value * 60 * 60 * 1000 : value * 60 * 1000;
|
||||||
|
return new Date(lastRun.getTime() + ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default to daily
|
||||||
|
return new Date(lastRun.getTime() + intervals.daily);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format bytes to human readable string
|
||||||
|
*/
|
||||||
|
function formatBytes(bytes) {
|
||||||
|
if (bytes === 0) return '0 B';
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
/**
|
||||||
|
* Config Drift Detection Routes
|
||||||
|
*
|
||||||
|
* API endpoints for running drift detection, reading cached reports,
|
||||||
|
* auto-fixing drift, and controlling periodic polling.
|
||||||
|
*
|
||||||
|
* @module routes/config-drift
|
||||||
|
*/
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const { success } = require('../response-helpers');
|
||||||
|
const { ValidationError, NotFoundError } = require('../errors');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Config-drift route factory
|
||||||
|
*
|
||||||
|
* @param {Object} deps - Explicit dependencies
|
||||||
|
* @param {Object} deps.driftDetector - ConfigDriftDetector instance
|
||||||
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||||
|
* @param {Function} deps.logError - Error logging function
|
||||||
|
* @returns {express.Router}
|
||||||
|
*/
|
||||||
|
module.exports = function ({ driftDetector, asyncHandler, logError }) {
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /config-drift/report
|
||||||
|
* Run a fresh drift detection and return the full report.
|
||||||
|
*/
|
||||||
|
router.get('/report', asyncHandler(async (_req, res) => {
|
||||||
|
const report = await driftDetector.detect();
|
||||||
|
success(res, { report });
|
||||||
|
}, 'drift-report'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /config-drift/last
|
||||||
|
* Return the last cached drift report (no re-detection).
|
||||||
|
*/
|
||||||
|
router.get('/last', asyncHandler(async (_req, res) => {
|
||||||
|
if (!driftDetector.lastReport) {
|
||||||
|
throw new NotFoundError('No cached drift report — run detection first');
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, { report: driftDetector.lastReport });
|
||||||
|
}, 'drift-last'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /config-drift/fix
|
||||||
|
* Auto-fix detected drift: remove stale records, flag unknown containers.
|
||||||
|
*/
|
||||||
|
router.post('/fix', asyncHandler(async (_req, res) => {
|
||||||
|
const result = await driftDetector.autoFix();
|
||||||
|
success(res, {
|
||||||
|
message: 'Auto-fix applied',
|
||||||
|
staleRemoved: result.staleRemoved,
|
||||||
|
unknownFlagged: result.unknownFlagged,
|
||||||
|
});
|
||||||
|
}, 'drift-fix'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /config-drift/polling
|
||||||
|
* Enable or disable periodic drift detection polling.
|
||||||
|
*
|
||||||
|
* Body: { enabled: boolean, intervalMs?: number }
|
||||||
|
*/
|
||||||
|
router.post('/polling', asyncHandler(async (req, res) => {
|
||||||
|
const { enabled, intervalMs } = req.body;
|
||||||
|
|
||||||
|
if (typeof enabled !== 'boolean') {
|
||||||
|
throw new ValidationError('enabled must be a boolean');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (intervalMs !== undefined) {
|
||||||
|
if (!Number.isInteger(intervalMs) || intervalMs < 10000 || intervalMs > 86400000) {
|
||||||
|
throw new ValidationError('intervalMs must be an integer between 10000 and 86400000 (10s – 24h)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (enabled) {
|
||||||
|
driftDetector.startPolling(intervalMs || 300000);
|
||||||
|
success(res, {
|
||||||
|
message: 'Drift polling enabled',
|
||||||
|
intervalMs: intervalMs || 300000,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
driftDetector.stopPolling();
|
||||||
|
success(res, { message: 'Drift polling disabled' });
|
||||||
|
}
|
||||||
|
}, 'drift-polling'));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
};
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
/**
|
||||||
|
* Dependencies Route — REST API for service dependency tracking
|
||||||
|
*
|
||||||
|
* Endpoints:
|
||||||
|
* GET /dependencies/graph Full dependency graph
|
||||||
|
* GET /dependencies/validate Validate a proposed dep chain
|
||||||
|
* GET /dependencies/:serviceId Direct deps for one service
|
||||||
|
* GET /dependencies/:serviceId/chain Ordered restart chain
|
||||||
|
* GET /dependencies/:serviceId/status Dependency health status
|
||||||
|
* POST /dependencies/:serviceId Set dependencies
|
||||||
|
* DELETE /dependencies/:serviceId Remove all dependencies
|
||||||
|
* POST /dependencies/:serviceId/restart Restart with dependency chain
|
||||||
|
*
|
||||||
|
* @module routes/dependencies
|
||||||
|
*/
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const { success, error: errorResponse } = require('../response-helpers');
|
||||||
|
const { NotFoundError, ValidationError } = require('../errors');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dependencies route factory
|
||||||
|
*
|
||||||
|
* @param {Object} deps - Explicit dependencies
|
||||||
|
* @param {Object} deps.dependencyManager - DependencyManager instance
|
||||||
|
* @param {Object} deps.servicesStateManager - State manager for services.json
|
||||||
|
* @param {Object} deps.docker - Docker client wrapper
|
||||||
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||||
|
* @param {Function} deps.logError - Error logging function
|
||||||
|
* @param {Function} deps.resyncHealthChecker - Health checker resync function
|
||||||
|
* @param {Object} deps.log - Logger instance
|
||||||
|
* @returns {express.Router}
|
||||||
|
*/
|
||||||
|
module.exports = function({
|
||||||
|
dependencyManager,
|
||||||
|
servicesStateManager,
|
||||||
|
docker,
|
||||||
|
asyncHandler,
|
||||||
|
logError,
|
||||||
|
resyncHealthChecker,
|
||||||
|
log,
|
||||||
|
}) {
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// GET /dependencies/graph — Full dependency graph
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.get('/graph', asyncHandler(async (req, res) => {
|
||||||
|
const graph = await dependencyManager.getDependencyGraph();
|
||||||
|
success(res, { graph });
|
||||||
|
}, 'dep-graph'));
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// GET /dependencies/validate — Validate a proposed dep chain (query params)
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.get('/validate', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId, dependsOn } = req.query;
|
||||||
|
|
||||||
|
if (!serviceId) {
|
||||||
|
throw new ValidationError('serviceId query parameter is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// dependsOn may be a comma-separated string or already an array
|
||||||
|
let parsed;
|
||||||
|
if (Array.isArray(dependsOn)) {
|
||||||
|
parsed = dependsOn;
|
||||||
|
} else if (typeof dependsOn === 'string' && dependsOn.length > 0) {
|
||||||
|
parsed = dependsOn.split(',').map(s => s.trim()).filter(Boolean);
|
||||||
|
} else {
|
||||||
|
parsed = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await dependencyManager.validateDependencies(serviceId, parsed);
|
||||||
|
success(res, result);
|
||||||
|
}, 'dep-validate'));
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// GET /dependencies/:serviceId — Direct deps for one service
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.get('/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
const dependencies = await dependencyManager.getDependencies(serviceId);
|
||||||
|
const dependents = await dependencyManager.getDependents(serviceId);
|
||||||
|
|
||||||
|
// Read the service's current dependsOn array
|
||||||
|
const services = await servicesStateManager.read();
|
||||||
|
const allServices = Array.isArray(services) ? services : (services.services || []);
|
||||||
|
const service = allServices.find(s => s.id === serviceId);
|
||||||
|
|
||||||
|
if (!service) {
|
||||||
|
throw new NotFoundError(`Service "${serviceId}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
serviceId,
|
||||||
|
dependsOn: service.dependsOn || [],
|
||||||
|
dependencies,
|
||||||
|
dependents: dependents.map(d => ({ id: d.id, name: d.name })),
|
||||||
|
});
|
||||||
|
}, 'dep-get'));
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// GET /dependencies/:serviceId/chain — Ordered restart chain
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.get('/:serviceId/chain', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
const chain = await dependencyManager.getOrderedRestartChain(serviceId);
|
||||||
|
success(res, { serviceId, chain });
|
||||||
|
}, 'dep-chain'));
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// GET /dependencies/:serviceId/status — Dependency health status
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.get('/:serviceId/status', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
const statuses = await dependencyManager.getDependencyStatus(serviceId);
|
||||||
|
success(res, { serviceId, statuses });
|
||||||
|
}, 'dep-status'));
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// POST /dependencies/:serviceId — Set dependencies
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.post('/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
const { dependsOn } = req.body;
|
||||||
|
|
||||||
|
if (!Array.isArray(dependsOn)) {
|
||||||
|
throw new ValidationError('Request body must include dependsOn as an array of service IDs');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate first
|
||||||
|
const validation = await dependencyManager.validateDependencies(serviceId, dependsOn);
|
||||||
|
if (!validation.valid) {
|
||||||
|
return errorResponse(res, validation.errors.join('; '), 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the service
|
||||||
|
let found = false;
|
||||||
|
await servicesStateManager.update(services => {
|
||||||
|
const arr = Array.isArray(services) ? services : [];
|
||||||
|
return arr.map(s => {
|
||||||
|
if (s.id === serviceId) {
|
||||||
|
found = true;
|
||||||
|
return { ...s, dependsOn: dependsOn.slice() };
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!found) {
|
||||||
|
throw new NotFoundError(`Service "${serviceId}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info('dependency', 'Dependencies updated', { serviceId, dependsOn });
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: `Dependencies updated for "${serviceId}"`,
|
||||||
|
serviceId,
|
||||||
|
dependsOn,
|
||||||
|
});
|
||||||
|
}, 'dep-set'));
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// DELETE /dependencies/:serviceId — Remove all dependencies for a service
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.delete('/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
|
||||||
|
let found = false;
|
||||||
|
await servicesStateManager.update(services => {
|
||||||
|
const arr = Array.isArray(services) ? services : [];
|
||||||
|
return arr.map(s => {
|
||||||
|
if (s.id === serviceId) {
|
||||||
|
found = true;
|
||||||
|
const updated = { ...s };
|
||||||
|
delete updated.dependsOn;
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!found) {
|
||||||
|
throw new NotFoundError(`Service "${serviceId}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info('dependency', 'Dependencies removed', { serviceId });
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: `All dependencies removed for "${serviceId}"`,
|
||||||
|
serviceId,
|
||||||
|
});
|
||||||
|
}, 'dep-delete'));
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// POST /dependencies/:serviceId/restart — Restart with dependency chain
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
router.post('/:serviceId/restart', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
|
||||||
|
// Verify the service exists
|
||||||
|
const services = await servicesStateManager.read();
|
||||||
|
const allServices = Array.isArray(services) ? services : (services.services || []);
|
||||||
|
if (!allServices.find(s => s.id === serviceId)) {
|
||||||
|
throw new NotFoundError(`Service "${serviceId}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the chain first for the response (before async restart begins)
|
||||||
|
let chain;
|
||||||
|
try {
|
||||||
|
chain = await dependencyManager.getOrderedRestartChain(serviceId);
|
||||||
|
} catch (err) {
|
||||||
|
return errorResponse(res, err.message, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Respond immediately with the chain order
|
||||||
|
success(res, {
|
||||||
|
message: `Dependency restart initiated for "${serviceId}"`,
|
||||||
|
serviceId,
|
||||||
|
chain,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run the restart chain asynchronously so the client doesn't block
|
||||||
|
dependencyManager.restartWithDependencies(serviceId).catch(err => {
|
||||||
|
if (log) {
|
||||||
|
log.error('dependency', 'Async dependency restart failed', {
|
||||||
|
serviceId,
|
||||||
|
error: err.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 'dep-restart'));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
};
|
||||||
+228
-8
@@ -26,7 +26,8 @@ module.exports = function({
|
|||||||
log,
|
log,
|
||||||
safeErrorMessage,
|
safeErrorMessage,
|
||||||
fetchT,
|
fetchT,
|
||||||
credentialManager
|
credentialManager,
|
||||||
|
dnsPropagationChecker
|
||||||
}) {
|
}) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -41,7 +42,137 @@ module.exports = function({
|
|||||||
return serverIp;
|
return serverIp;
|
||||||
}
|
}
|
||||||
|
|
||||||
// DELETE /record — Delete a DNS record from Technitium
|
// ===== DNS PROVIDER ENDPOINTS =====
|
||||||
|
|
||||||
|
// GET /providers — List all available DNS providers
|
||||||
|
router.get('/providers', asyncHandler(async (req, res) => {
|
||||||
|
const providers = dns.getAvailableProviders ? dns.getAvailableProviders() : [];
|
||||||
|
const activeProvider = dns.getProviderId ? dns.getProviderId() : 'technitium';
|
||||||
|
success(res, { providers, activeProvider });
|
||||||
|
}, 'dns-providers-list'));
|
||||||
|
|
||||||
|
// GET /provider/status — Get active provider status
|
||||||
|
router.get('/provider/status', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
return success(res, { providerId: 'technitium', capabilities: ['create-record', 'delete-record', 'resolve', 'list-records', 'logs', 'restart', 'update-check', 'credentials', 'zones'] });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
const status = await provider.getStatus();
|
||||||
|
success(res, status);
|
||||||
|
} catch (err) {
|
||||||
|
errorResponse(res, safeErrorMessage(err), 500);
|
||||||
|
}
|
||||||
|
}, 'dns-provider-status'));
|
||||||
|
|
||||||
|
// ===== UNIVERSAL RECORD ENDPOINTS (work with any provider) =====
|
||||||
|
|
||||||
|
// POST /universal/record — Create a DNS record via any provider
|
||||||
|
router.post('/universal/record', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
// Fallback to legacy Technitium route
|
||||||
|
return res.redirect(307, '/api/dns/record');
|
||||||
|
}
|
||||||
|
const { domain, ip, ttl, type, server } = req.body;
|
||||||
|
if (!domain || !ip) throw new ValidationError('domain and ip are required');
|
||||||
|
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||||
|
if (!validatorLib.isIP(ip)) throw new ValidationError('[DC-210] Invalid IP address');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
if (!provider.supportsCapability('create-record')) {
|
||||||
|
const result = await provider.createRecord({
|
||||||
|
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A', value: ip, ttl: ttl || 300, overwrite: true
|
||||||
|
});
|
||||||
|
return success(res, {
|
||||||
|
message: result.message || `DNS record instructions provided`,
|
||||||
|
manual: true,
|
||||||
|
instructions: result.instructions
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await provider.createRecord({
|
||||||
|
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A', value: ip, ttl: ttl || 300, overwrite: true
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start propagation check in background
|
||||||
|
if (dnsPropagationChecker && ip) {
|
||||||
|
dnsPropagationChecker.startVerification(domain, ip).catch(err => {
|
||||||
|
log('DNS propagation check start failed:', err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: result.status === 'manual' ? result.message : `DNS record ${domain} -> ${ip} created`,
|
||||||
|
provider: dns.getProviderId(),
|
||||||
|
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'Universal DNS record creation error', { error: error.message });
|
||||||
|
errorResponse(res, safeErrorMessage(error), 500);
|
||||||
|
}
|
||||||
|
}, 'dns-universal-create'));
|
||||||
|
|
||||||
|
// DELETE /universal/record — Delete a DNS record via any provider
|
||||||
|
router.delete('/universal/record', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
return res.redirect(307, '/api/dns/record');
|
||||||
|
}
|
||||||
|
const { domain, type, value } = req.query;
|
||||||
|
if (!domain) throw new ValidationError('domain is required');
|
||||||
|
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
const result = await provider.deleteRecord({
|
||||||
|
domain, type: type || 'A', value
|
||||||
|
});
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: result.status === 'manual' ? result.message : `DNS record ${domain} deleted`,
|
||||||
|
provider: dns.getProviderId(),
|
||||||
|
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'Universal DNS record deletion error', { error: error.message });
|
||||||
|
errorResponse(res, safeErrorMessage(error), 500);
|
||||||
|
}
|
||||||
|
}, 'dns-universal-delete'));
|
||||||
|
|
||||||
|
// GET /universal/resolve — Resolve a domain via any provider
|
||||||
|
router.get('/universal/resolve', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
return res.redirect(307, '/api/dns/resolve');
|
||||||
|
}
|
||||||
|
const { domain, type } = req.query;
|
||||||
|
if (!domain) throw new ValidationError('domain is required');
|
||||||
|
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
const result = await provider.resolveRecords({
|
||||||
|
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.response?.records?.length > 0) {
|
||||||
|
const ipAddresses = result.response.records
|
||||||
|
.filter(r => r.type === (type || 'A'))
|
||||||
|
.map(r => r.rData?.ipAddress || r.content || r.rData?.address)
|
||||||
|
.filter(Boolean);
|
||||||
|
success(res, { answer: ipAddresses });
|
||||||
|
} else {
|
||||||
|
throw new NotFoundError('No records found for domain');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'Universal DNS resolve error', { error: error.message });
|
||||||
|
errorResponse(res, safeErrorMessage(error), error.statusCode || 500);
|
||||||
|
}
|
||||||
|
}, 'dns-universal-resolve'));
|
||||||
|
|
||||||
|
// ===== LEGACY TECHNITIUM-SPECIFIC ROUTES (unchanged) =====
|
||||||
router.delete('/record', asyncHandler(async (req, res) => {
|
router.delete('/record', asyncHandler(async (req, res) => {
|
||||||
const { domain, type, token, server, ipAddress } = req.query;
|
const { domain, type, token, server, ipAddress } = req.query;
|
||||||
|
|
||||||
@@ -139,6 +270,14 @@ module.exports = function({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (result.status === 'ok') {
|
if (result.status === 'ok') {
|
||||||
|
// Start DNS propagation verification in background
|
||||||
|
if (dnsPropagationChecker && ip) {
|
||||||
|
const fullDomain = domain;
|
||||||
|
dnsPropagationChecker.startVerification(fullDomain, ip).catch(err => {
|
||||||
|
log('DNS propagation check start failed:', err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
success(res, { message: `DNS record ${domain} -> ${ip} created` });
|
success(res, { message: `DNS record ${domain} -> ${ip} created` });
|
||||||
} else {
|
} else {
|
||||||
// Error handled by middleware
|
// Error handled by middleware
|
||||||
@@ -194,8 +333,13 @@ module.exports = function({
|
|||||||
}
|
}
|
||||||
}, 'dns-resolve'));
|
}, 'dns-resolve'));
|
||||||
|
|
||||||
// GET /logs — Fetch DNS query logs from Technitium
|
// GET /logs — Fetch DNS query logs (Technitium only)
|
||||||
router.get('/logs', asyncHandler(async (req, res) => {
|
router.get('/logs', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate: logs are provider-specific
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('logs')) {
|
||||||
|
return success(res, { server: 'N/A', count: 0, logs: [], message: 'DNS logs not supported by current provider' });
|
||||||
|
}
|
||||||
|
|
||||||
const { server, limit } = req.query;
|
const { server, limit } = req.query;
|
||||||
|
|
||||||
if (!server) {
|
if (!server) {
|
||||||
@@ -475,8 +619,13 @@ module.exports = function({
|
|||||||
success(res, { message: 'DNS credentials removed' });
|
success(res, { message: 'DNS credentials removed' });
|
||||||
}, 'dns-credentials-delete'));
|
}, 'dns-credentials-delete'));
|
||||||
|
|
||||||
// POST /restart/:dnsId — Restart a DNS server (proxied through backend for auth)
|
// POST /restart/:dnsId — Restart a DNS server (Technitium only)
|
||||||
router.post('/restart/:dnsId', asyncHandler(async (req, res) => {
|
router.post('/restart/:dnsId', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('restart')) {
|
||||||
|
return errorResponse(res, 'Server restart not supported by current DNS provider', 501);
|
||||||
|
}
|
||||||
|
|
||||||
const { dnsId } = req.params;
|
const { dnsId } = req.params;
|
||||||
const serverInfo = siteConfig.dnsServers?.[dnsId];
|
const serverInfo = siteConfig.dnsServers?.[dnsId];
|
||||||
if (!serverInfo?.ip) {
|
if (!serverInfo?.ip) {
|
||||||
@@ -518,8 +667,13 @@ module.exports = function({
|
|||||||
}
|
}
|
||||||
}, 'dns-refresh-token'));
|
}, 'dns-refresh-token'));
|
||||||
|
|
||||||
// GET /check-update — Check for Technitium DNS server updates
|
// GET /check-update — Check for DNS server updates (Technitium only)
|
||||||
router.get('/check-update', asyncHandler(async (req, res) => {
|
router.get('/check-update', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('update-check')) {
|
||||||
|
return success(res, { updateAvailable: false, message: 'Update check not supported by current DNS provider' });
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { server } = req.query;
|
const { server } = req.query;
|
||||||
if (!server) {
|
if (!server) {
|
||||||
@@ -576,10 +730,13 @@ module.exports = function({
|
|||||||
}
|
}
|
||||||
}, 'dns-check-update'));
|
}, 'dns-check-update'));
|
||||||
|
|
||||||
// POST /update — Update Technitium DNS server
|
// POST /update — Update DNS server (Technitium only)
|
||||||
// Note: Technitium v14+ has no installUpdate API. This endpoint checks for updates
|
|
||||||
// and returns download info. The frontend handles showing update instructions.
|
|
||||||
router.post('/update', asyncHandler(async (req, res) => {
|
router.post('/update', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('update-check')) {
|
||||||
|
return errorResponse(res, 'Server update not supported by current DNS provider', 501);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { server } = req.query;
|
const { server } = req.query;
|
||||||
if (!server) {
|
if (!server) {
|
||||||
@@ -641,5 +798,68 @@ module.exports = function({
|
|||||||
}
|
}
|
||||||
}, 'dns-update'));
|
}, 'dns-update'));
|
||||||
|
|
||||||
|
// ===== DNS PROPAGATION =====
|
||||||
|
|
||||||
|
// GET /propagation — Get all recent DNS propagation checks
|
||||||
|
router.get('/propagation', asyncHandler(async (req, res) => {
|
||||||
|
if (!dnsPropagationChecker) {
|
||||||
|
return success(res, { verifications: [], message: 'DNS propagation checker not available' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cleanup old entries
|
||||||
|
dnsPropagationChecker.cleanup();
|
||||||
|
|
||||||
|
const verifications = dnsPropagationChecker.getAllVerifications();
|
||||||
|
success(res, { verifications });
|
||||||
|
}, 'dns-propagation-all'));
|
||||||
|
|
||||||
|
// POST /propagation/verify — Manually trigger DNS propagation verification
|
||||||
|
router.post('/propagation/verify', asyncHandler(async (req, res) => {
|
||||||
|
if (!dnsPropagationChecker) {
|
||||||
|
return errorResponse(res, 'DNS propagation checker not available', 503);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { domain, expectedIp } = req.body;
|
||||||
|
|
||||||
|
if (!domain || !expectedIp) {
|
||||||
|
throw new ValidationError('domain and expectedIp are required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate domain format
|
||||||
|
if (!REGEX.DOMAIN.test(domain)) {
|
||||||
|
throw new ValidationError('[DC-301] Invalid domain format');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate IP address
|
||||||
|
const validatorLib = require('validator');
|
||||||
|
if (!validatorLib.isIP(expectedIp)) {
|
||||||
|
throw new ValidationError('[DC-210] Invalid IP address');
|
||||||
|
}
|
||||||
|
|
||||||
|
const job = dnsPropagationChecker.startVerification(domain, expectedIp);
|
||||||
|
success(res, {
|
||||||
|
message: 'DNS propagation verification started',
|
||||||
|
domain,
|
||||||
|
expectedIp,
|
||||||
|
status: job.status
|
||||||
|
});
|
||||||
|
}, 'dns-propagation-verify'));
|
||||||
|
|
||||||
|
// GET /propagation/:domain — Get propagation status for a specific domain
|
||||||
|
router.get('/propagation/:domain', asyncHandler(async (req, res) => {
|
||||||
|
if (!dnsPropagationChecker) {
|
||||||
|
return success(res, { verification: null, message: 'DNS propagation checker not available' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { domain } = req.params;
|
||||||
|
const status = dnsPropagationChecker.getVerificationStatus(domain);
|
||||||
|
|
||||||
|
if (!status) {
|
||||||
|
throw new NotFoundError(`No propagation check found for domain: ${domain}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, { verification: status });
|
||||||
|
}, 'dns-propagation-domain'));
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,9 +8,10 @@ const express = require('express');
|
|||||||
* @param {Object} deps.healthChecker - Health checker
|
* @param {Object} deps.healthChecker - Health checker
|
||||||
* @param {Object} deps.updateManager - Update manager
|
* @param {Object} deps.updateManager - Update manager
|
||||||
* @param {Function} deps.logError - Error logging function
|
* @param {Function} deps.logError - Error logging function
|
||||||
|
* @param {Object} deps.dependencyManager - Dependency manager for restart chain events
|
||||||
* @returns {express.Router}
|
* @returns {express.Router}
|
||||||
*/
|
*/
|
||||||
module.exports = function({ resourceMonitor, healthChecker, updateManager, logError }) {
|
module.exports = function({ resourceMonitor, healthChecker, updateManager, logError, dependencyManager, autoRestartManager, driftDetector, sslMonitor, dnsPropagationChecker }) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const clients = new Set();
|
const clients = new Set();
|
||||||
|
|
||||||
@@ -74,6 +75,48 @@ module.exports = function({ resourceMonitor, healthChecker, updateManager, logEr
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dependency manager events
|
||||||
|
if (dependencyManager) {
|
||||||
|
dependencyManager.on('dependency-restart-start', (data) => {
|
||||||
|
broadcast('dependency-restart-start', data);
|
||||||
|
});
|
||||||
|
dependencyManager.on('dependency-restart-progress', (data) => {
|
||||||
|
broadcast('dependency-restart-progress', data);
|
||||||
|
});
|
||||||
|
dependencyManager.on('dependency-restart-complete', (data) => {
|
||||||
|
broadcast('dependency-restart-complete', data);
|
||||||
|
});
|
||||||
|
dependencyManager.on('dependency-restart-failed', (data) => {
|
||||||
|
broadcast('dependency-restart-failed', data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-restart manager events
|
||||||
|
if (autoRestartManager) {
|
||||||
|
autoRestartManager.on('auto-restart-attempt', (data) => broadcast('auto-restart-attempt', data));
|
||||||
|
autoRestartManager.on('auto-restart-success', (data) => broadcast('auto-restart-success', data));
|
||||||
|
autoRestartManager.on('auto-restart-failed', (data) => broadcast('auto-restart-failed', data));
|
||||||
|
autoRestartManager.on('auto-restart-max-reached', (data) => broadcast('auto-restart-max-reached', data));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config drift detector events
|
||||||
|
if (driftDetector) {
|
||||||
|
driftDetector.on('drift-detected', (data) => broadcast('drift-detected', data));
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSL monitor events
|
||||||
|
if (sslMonitor) {
|
||||||
|
sslMonitor.on('cert-expiring', (data) => broadcast('cert-expiring', data));
|
||||||
|
sslMonitor.on('cert-critical', (data) => broadcast('cert-critical', data));
|
||||||
|
}
|
||||||
|
|
||||||
|
// DNS propagation checker events
|
||||||
|
if (dnsPropagationChecker) {
|
||||||
|
dnsPropagationChecker.on('propagation-check', (data) => broadcast('dns-propagation-check', data));
|
||||||
|
dnsPropagationChecker.on('propagation-complete', (data) => broadcast('dns-propagation-complete', data));
|
||||||
|
dnsPropagationChecker.on('propagation-timeout', (data) => broadcast('dns-propagation-timeout', data));
|
||||||
|
}
|
||||||
|
|
||||||
// SSE endpoint
|
// SSE endpoint
|
||||||
router.get('/stream', (req, res) => {
|
router.get('/stream', (req, res) => {
|
||||||
res.writeHead(200, {
|
res.writeHead(200, {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ const { success } = require('../response-helpers');
|
|||||||
* @param {Object} deps.log - Logger instance
|
* @param {Object} deps.log - Logger instance
|
||||||
* @returns {express.Router}
|
* @returns {express.Router}
|
||||||
*/
|
*/
|
||||||
module.exports = function({ resourceMonitor, docker, asyncHandler, log }) {
|
module.exports = function({ resourceMonitor, docker, asyncHandler, log, notificationManager }) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// ===== RESOURCE MONITORING ENDPOINTS =====
|
// ===== RESOURCE MONITORING ENDPOINTS =====
|
||||||
@@ -66,7 +66,86 @@ module.exports = function({ resourceMonitor, docker, asyncHandler, log }) {
|
|||||||
success(res, { aggregated, hours });
|
success(res, { aggregated, hours });
|
||||||
}, 'monitoring-aggregated'));
|
}, 'monitoring-aggregated'));
|
||||||
|
|
||||||
// Configure alerts
|
// ===== ALERT CONFIGURATION (bulk) =====
|
||||||
|
|
||||||
|
// Get all alert configs
|
||||||
|
router.get('/monitoring/alerts/config', asyncHandler(async (req, res) => {
|
||||||
|
const configs = resourceMonitor.getAllAlertConfigs();
|
||||||
|
success(res, { configs });
|
||||||
|
}, 'monitoring-alerts-config-get'));
|
||||||
|
|
||||||
|
// Set all alert configs (bulk update)
|
||||||
|
router.post('/monitoring/alerts/config', asyncHandler(async (req, res) => {
|
||||||
|
const { configs } = req.body;
|
||||||
|
if (!configs || typeof configs !== 'object') {
|
||||||
|
const { ValidationError } = require('../errors');
|
||||||
|
throw new ValidationError('configs object required');
|
||||||
|
}
|
||||||
|
for (const [containerId, config] of Object.entries(configs)) {
|
||||||
|
resourceMonitor.setAlertConfig(containerId, config);
|
||||||
|
}
|
||||||
|
success(res, { message: 'Alert configurations saved' });
|
||||||
|
}, 'monitoring-alerts-config-set'));
|
||||||
|
|
||||||
|
// Get alert history
|
||||||
|
router.get('/monitoring/alerts', asyncHandler(async (req, res) => {
|
||||||
|
const limit = parseInt(req.query.limit) || 50;
|
||||||
|
const history = resourceMonitor.getAlertHistory(limit);
|
||||||
|
success(res, { history });
|
||||||
|
}, 'monitoring-alerts-history'));
|
||||||
|
|
||||||
|
// Send test alert notification for a container
|
||||||
|
router.post('/monitoring/alerts/:containerId/test', asyncHandler(async (req, res) => {
|
||||||
|
const { containerId } = req.params;
|
||||||
|
|
||||||
|
// Get container name from docker
|
||||||
|
let containerName = containerId;
|
||||||
|
try {
|
||||||
|
const containers = await docker.client.listContainers({ all: false });
|
||||||
|
const containerInfo = containers.find(c => c.Id === containerId || c.Id.startsWith(containerId));
|
||||||
|
if (containerInfo) {
|
||||||
|
containerName = containerInfo.Names[0]?.replace(/^\//, '') || containerId;
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
const testAlert = {
|
||||||
|
containerId,
|
||||||
|
containerName,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
alerts: [{
|
||||||
|
type: 'test',
|
||||||
|
severity: 'info',
|
||||||
|
message: 'This is a test alert notification',
|
||||||
|
value: 0,
|
||||||
|
threshold: 0
|
||||||
|
}],
|
||||||
|
stats: null,
|
||||||
|
config: resourceMonitor.getAlertConfig(containerId) || {}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (notificationManager) {
|
||||||
|
await notificationManager.sendAlert(testAlert);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also log to alert history
|
||||||
|
resourceMonitor.addAlertHistoryEntry({
|
||||||
|
id: `test-${Date.now()}`,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
containerId,
|
||||||
|
containerName,
|
||||||
|
type: 'test',
|
||||||
|
metric: 'test',
|
||||||
|
value: 0,
|
||||||
|
threshold: 0,
|
||||||
|
severity: 'info',
|
||||||
|
notified: true,
|
||||||
|
autoRestartTriggered: false
|
||||||
|
});
|
||||||
|
|
||||||
|
success(res, { message: 'Test alert sent', alert: testAlert });
|
||||||
|
}, 'monitoring-alerts-test'));
|
||||||
|
|
||||||
|
// Configure alerts for a container
|
||||||
router.post('/monitoring/alerts/:containerId', asyncHandler(async (req, res) => {
|
router.post('/monitoring/alerts/:containerId', asyncHandler(async (req, res) => {
|
||||||
resourceMonitor.setAlertConfig(req.params.containerId, req.body);
|
resourceMonitor.setAlertConfig(req.params.containerId, req.body);
|
||||||
success(res, { message: 'Alert configuration saved' });
|
success(res, { message: 'Alert configuration saved' });
|
||||||
|
|||||||
@@ -218,5 +218,46 @@ module.exports = function({ notification, asyncHandler }) {
|
|||||||
});
|
});
|
||||||
}, 'notifications-health-check'));
|
}, 'notifications-health-check'));
|
||||||
|
|
||||||
|
// GET /status — Get notification system status
|
||||||
|
router.get('/status', asyncHandler(async (req, res) => {
|
||||||
|
const notificationConfig = notification.getConfig();
|
||||||
|
const providers = notificationConfig.providers || {};
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
enabled: notificationConfig.enabled,
|
||||||
|
providers: {
|
||||||
|
discord: providers.discord?.enabled && !!providers.discord?.webhookUrl,
|
||||||
|
telegram: providers.telegram?.enabled && !!providers.telegram?.botToken && !!providers.telegram?.chatId,
|
||||||
|
ntfy: providers.ntfy?.enabled && !!providers.ntfy?.topic,
|
||||||
|
email: providers.email?.enabled && !!providers.email?.host && !!providers.email?.to
|
||||||
|
},
|
||||||
|
lastSent: notification.lastSent,
|
||||||
|
healthCheck: notificationConfig.healthCheck?.enabled ? {
|
||||||
|
enabled: true,
|
||||||
|
lastCheck: notificationConfig.healthCheck.lastCheck,
|
||||||
|
intervalMinutes: notificationConfig.healthCheck.intervalMinutes
|
||||||
|
} : { enabled: false }
|
||||||
|
});
|
||||||
|
}, 'notifications-status'));
|
||||||
|
|
||||||
|
// POST /send — Manual test send (used by frontend "Send Test" button)
|
||||||
|
router.post('/send', asyncHandler(async (req, res) => {
|
||||||
|
const { event, data, type } = req.body;
|
||||||
|
|
||||||
|
if (!event) {
|
||||||
|
throw new ValidationError('Event type is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use 'test' as the event for manual sends
|
||||||
|
const result = await notification.send(event, data || {}, type || 'info');
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: result.success,
|
||||||
|
event,
|
||||||
|
results: result.results
|
||||||
|
});
|
||||||
|
}, 'notifications-send'));
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,272 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const http = require('http');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OpenClaw management routes
|
||||||
|
* Proxies gateway API calls through DashCaddy so the token never leaves the server.
|
||||||
|
*
|
||||||
|
* GET /openclaw/status → container info + gateway health
|
||||||
|
* POST /openclaw/deploy → deploy OpenClaw container
|
||||||
|
* GET /openclaw/proxy/* → proxy GET to gateway
|
||||||
|
* POST /openclaw/proxy/* → proxy POST to gateway
|
||||||
|
* DELETE /openclaw → remove container
|
||||||
|
*/
|
||||||
|
module.exports = function openClawRoutes(ctx) {
|
||||||
|
const router = express.Router();
|
||||||
|
const docker = ctx.docker;
|
||||||
|
const asyncHandler = ctx.asyncHandler;
|
||||||
|
const log = ctx.log || console;
|
||||||
|
|
||||||
|
// ── helpers ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function findOpenClawContainer() {
|
||||||
|
const containers = await docker.client.listContainers({ all: true });
|
||||||
|
return containers.find(function(c) {
|
||||||
|
return c.Image === 'ghcr.io/nousresearch/openclaw:latest' ||
|
||||||
|
(c.Labels && c.Labels['dashcaddy.managed'] === 'true' &&
|
||||||
|
c.Names.some(function(n) { return n.includes('openclaw'); }));
|
||||||
|
}) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getGatewayToken(containerId) {
|
||||||
|
try {
|
||||||
|
const info = await docker.client.containerInfo(containerId);
|
||||||
|
const entry = (info.Config.Env || []).find(function(e) {
|
||||||
|
return e.startsWith('OPENCLAW_GATEWAY_TOKEN=');
|
||||||
|
});
|
||||||
|
return entry ? entry.split('=')[1] : null;
|
||||||
|
} catch(err) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getContainerPort(containerId) {
|
||||||
|
try {
|
||||||
|
const containers = await docker.client.listContainers({ all: true });
|
||||||
|
const c = containers.find(function(x) {
|
||||||
|
return x.Id === containerId || x.Id.startsWith(containerId);
|
||||||
|
});
|
||||||
|
if (c && c.Ports) {
|
||||||
|
const p = c.Ports.find(function(x) { return x.PrivatePort === 18792; });
|
||||||
|
if (p && p.PublicPort) return String(p.PublicPort);
|
||||||
|
}
|
||||||
|
return '18792';
|
||||||
|
} catch(err) {
|
||||||
|
return '18792';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function gatewayHealth(baseUrl, token) {
|
||||||
|
return new Promise(function(resolve) {
|
||||||
|
const headers = {};
|
||||||
|
if (token) headers['Authorization'] = 'Bearer ' + token;
|
||||||
|
const req = http.get(baseUrl + '/health', { headers: headers }, function(res) {
|
||||||
|
let data = '';
|
||||||
|
res.on('data', function(d) { data += d; });
|
||||||
|
res.on('end', function() {
|
||||||
|
try { resolve({ ok: true, data: JSON.parse(data) }); }
|
||||||
|
catch(e) { resolve({ ok: true, data: data }); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', function(e) { resolve({ ok: false, error: e.message }); });
|
||||||
|
req.setTimeout(5000, function() { req.destroy(); resolve({ ok: false, error: 'timeout' }); });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function proxyRequest(req, res, targetBase, path, token) {
|
||||||
|
const headers = {};
|
||||||
|
if (token) headers['Authorization'] = 'Bearer ' + token;
|
||||||
|
headers['X-Forwarded-For'] = req.ip;
|
||||||
|
headers['X-Forwarded-Proto'] = req.protocol;
|
||||||
|
|
||||||
|
const url = targetBase + '/' + path;
|
||||||
|
const method = req.method;
|
||||||
|
|
||||||
|
if (['POST', 'PUT', 'PATCH'].includes(method)) {
|
||||||
|
const body = JSON.stringify(req.body);
|
||||||
|
headers['Content-Type'] = 'application/json';
|
||||||
|
headers['Content-Length'] = Buffer.byteLength(body);
|
||||||
|
|
||||||
|
const proxyReq = http.request(url, { method: method, headers: headers }, function(proxyRes) {
|
||||||
|
res.set(proxyRes.headers);
|
||||||
|
res.status(proxyRes.statusCode);
|
||||||
|
proxyRes.on('data', function(d) { res.write(d); });
|
||||||
|
proxyRes.on('end', function() { res.end(); });
|
||||||
|
});
|
||||||
|
proxyReq.on('error', function(e) { res.status(502).json({ success: false, error: e.message }); });
|
||||||
|
proxyReq.setTimeout(15000, function() { proxyReq.destroy(); res.status(504).json({ success: false, error: 'gateway timeout' }); });
|
||||||
|
proxyReq.write(body);
|
||||||
|
proxyReq.end();
|
||||||
|
} else {
|
||||||
|
const proxyReq = http.get(url, { headers: headers }, function(proxyRes) {
|
||||||
|
res.set(proxyRes.headers);
|
||||||
|
res.status(proxyRes.statusCode);
|
||||||
|
proxyRes.on('data', function(d) { res.write(d); });
|
||||||
|
proxyRes.on('end', function() { res.end(); });
|
||||||
|
});
|
||||||
|
proxyReq.on('error', function(e) { res.status(502).json({ success: false, error: e.message }); });
|
||||||
|
proxyReq.setTimeout(15000, function() { proxyReq.destroy(); res.status(504).json({ success: false, error: 'gateway timeout' }); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GET /openclaw/status ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
router.get('/status', asyncHandler(async function(req, res) {
|
||||||
|
const container = await findOpenClawContainer();
|
||||||
|
|
||||||
|
if (!container) {
|
||||||
|
return res.json({ success: true, deployed: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await getGatewayToken(container.Id);
|
||||||
|
const port = await getContainerPort(container.Id);
|
||||||
|
const baseUrl = 'http://localhost:' + port;
|
||||||
|
const health = await gatewayHealth(baseUrl, token);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
deployed: true,
|
||||||
|
container: {
|
||||||
|
id: container.Id.slice(0, 12),
|
||||||
|
name: container.Name,
|
||||||
|
state: container.State,
|
||||||
|
status: container.Status,
|
||||||
|
created: container.Created,
|
||||||
|
image: container.Image
|
||||||
|
},
|
||||||
|
gateway: {
|
||||||
|
url: baseUrl,
|
||||||
|
port: port,
|
||||||
|
healthy: health.ok,
|
||||||
|
healthData: health.data || null,
|
||||||
|
tokenSet: !!token
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ── POST /openclaw/deploy ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
router.post('/deploy', asyncHandler(async function(req, res) {
|
||||||
|
const existing = await findOpenClawContainer();
|
||||||
|
if (existing) {
|
||||||
|
return res.status(409).json({ success: false, error: 'OpenClaw is already deployed' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const image = 'ghcr.io/nousresearch/openclaw:latest';
|
||||||
|
const name = 'openclaw-' + Date.now();
|
||||||
|
const gatewayToken = generateToken();
|
||||||
|
|
||||||
|
// Pull image
|
||||||
|
log.info('Pulling ' + image + '...');
|
||||||
|
try {
|
||||||
|
await new Promise(function(resolve, reject) {
|
||||||
|
docker.client.pull(image, function(err, stream) {
|
||||||
|
if (err) return reject(err);
|
||||||
|
docker.client.modem.followProgress(stream, function(err2) {
|
||||||
|
if (err2) return reject(err2);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch(e) {
|
||||||
|
log.error('OpenClaw pull failed: ' + e.message);
|
||||||
|
return res.status(500).json({ success: false, error: 'Failed to pull image: ' + e.message });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create + start container
|
||||||
|
try {
|
||||||
|
const container = await docker.client.createContainer({
|
||||||
|
name: name,
|
||||||
|
Image: image,
|
||||||
|
Env: [
|
||||||
|
'OPENCLAW_GATEWAY_MODE=local',
|
||||||
|
'OPENCLAW_GATEWAY_TOKEN=' + gatewayToken
|
||||||
|
],
|
||||||
|
HostConfig: {
|
||||||
|
PortBindings: { '18792/tcp': [{ HostPort: '18792' }] },
|
||||||
|
RestartPolicy: { Name: 'unless-stopped' },
|
||||||
|
Labels: {
|
||||||
|
'dashcaddy.managed': 'true',
|
||||||
|
'dashcaddy.app': 'openclaw'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ExposedPorts: { '18792/tcp': {} }
|
||||||
|
});
|
||||||
|
|
||||||
|
await container.start();
|
||||||
|
log.info('OpenClaw deployed: ' + container.id.slice(0, 12));
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
deployed: true,
|
||||||
|
container: { id: container.id.slice(0, 12), name: name },
|
||||||
|
gateway: {
|
||||||
|
url: 'http://localhost:18792',
|
||||||
|
token: gatewayToken
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch(e) {
|
||||||
|
log.error('OpenClaw deploy failed: ' + e.message);
|
||||||
|
res.status(500).json({ success: false, error: 'Deploy failed: ' + e.message });
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ── GET /openclaw/proxy/* ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
router.get('/proxy/*', asyncHandler(async function(req, res) {
|
||||||
|
const container = await findOpenClawContainer();
|
||||||
|
if (!container) return res.status(404).json({ success: false, error: 'OpenClaw not deployed' });
|
||||||
|
|
||||||
|
const token = await getGatewayToken(container.Id);
|
||||||
|
const port = await getContainerPort(container.Id);
|
||||||
|
const baseUrl = 'http://localhost:' + port;
|
||||||
|
const path = req.params[0];
|
||||||
|
|
||||||
|
proxyRequest(req, res, baseUrl, path, token);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ── POST /openclaw/proxy/* ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
router.post('/proxy/*', asyncHandler(async function(req, res) {
|
||||||
|
const container = await findOpenClawContainer();
|
||||||
|
if (!container) return res.status(404).json({ success: false, error: 'OpenClaw not deployed' });
|
||||||
|
|
||||||
|
const token = await getGatewayToken(container.Id);
|
||||||
|
const port = await getContainerPort(container.Id);
|
||||||
|
const baseUrl = 'http://localhost:' + port;
|
||||||
|
const path = req.params[0];
|
||||||
|
|
||||||
|
proxyRequest(req, res, baseUrl, path, token);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ── DELETE /openclaw ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
router.delete('/', asyncHandler(async function(req, res) {
|
||||||
|
const container = await findOpenClawContainer();
|
||||||
|
if (!container) return res.status(404).json({ success: false, error: 'OpenClaw not deployed' });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const c = docker.client.container(container.Id);
|
||||||
|
await c.stop().catch(function() {});
|
||||||
|
await c.remove({ force: true });
|
||||||
|
log.info('OpenClaw container ' + container.Id.slice(0, 12) + ' removed');
|
||||||
|
res.json({ success: true, message: 'OpenClaw removed' });
|
||||||
|
} catch(e) {
|
||||||
|
log.error('Failed to remove OpenClaw: ' + e.message);
|
||||||
|
res.status(500).json({ success: false, error: e.message });
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── token generator ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function generateToken() {
|
||||||
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||||
|
let result = '';
|
||||||
|
for (let i = 0; i < 32; i++) {
|
||||||
|
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -513,9 +520,8 @@ module.exports = function({
|
|||||||
|
|
||||||
if (oldSubdomain !== newSubdomain) {
|
if (oldSubdomain !== newSubdomain) {
|
||||||
try {
|
try {
|
||||||
const dnsToken = dns.getToken();
|
await dns.universalDeleteRecord(oldDomain);
|
||||||
await dns.call(siteConfig.dnsServerIp, '/api/zones/records/delete', { token: dnsToken, domain: oldDomain, type: 'A' });
|
await dns.universalCreateRecord(newSubdomain, ip || 'localhost');
|
||||||
await dns.createRecord(newSubdomain, ip || 'localhost');
|
|
||||||
results.dns = 'updated';
|
results.dns = 'updated';
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
results.dns = `failed: ${e.message}`;
|
results.dns = `failed: ${e.message}`;
|
||||||
@@ -542,6 +548,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';
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
|||||||
|
|
||||||
if (createDns) {
|
if (createDns) {
|
||||||
try {
|
try {
|
||||||
await dns.createRecord(subdomain, siteConfig.dnsServerIp);
|
await dns.universalCreateRecord(subdomain, siteConfig.dnsServerIp);
|
||||||
log.info('dns', 'DNS record created for external proxy', { domain, ip: siteConfig.dnsServerIp });
|
log.info('dns', 'DNS record created for external proxy', { domain, ip: siteConfig.dnsServerIp });
|
||||||
} catch (dnsError) {
|
} catch (dnsError) {
|
||||||
dnsWarning = `DNS creation failed: ${dnsError.message}. You may need to create the DNS record manually.`;
|
dnsWarning = `DNS creation failed: ${dnsError.message}. You may need to create the DNS record manually.`;
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
/**
|
||||||
|
* SSL Monitor Routes
|
||||||
|
* REST API endpoints for SSL certificate monitoring.
|
||||||
|
*
|
||||||
|
* @module routes/ssl-monitor
|
||||||
|
*/
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const { success, error: errorResponse, notFound } = require('../response-helpers');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SSL Monitor route factory
|
||||||
|
* @param {Object} deps - Explicit dependencies
|
||||||
|
* @param {Object} deps.sslMonitor - SSLMonitor instance
|
||||||
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||||
|
* @param {Function} deps.logError - Error logging function
|
||||||
|
* @returns {express.Router}
|
||||||
|
*/
|
||||||
|
module.exports = function({ sslMonitor, asyncHandler, logError }) {
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /ssl/certificates
|
||||||
|
* Get all SSL certificate statuses
|
||||||
|
*/
|
||||||
|
router.get('/certificates', asyncHandler(async (req, res) => {
|
||||||
|
const status = sslMonitor.getStatus();
|
||||||
|
success(res, { certificates: status });
|
||||||
|
}, 'ssl-certificates'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /ssl/certificates/:serviceId
|
||||||
|
* Get SSL certificate status for a specific service
|
||||||
|
*/
|
||||||
|
router.get('/certificates/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
const certStatus = sslMonitor.getServiceCertStatus(serviceId);
|
||||||
|
|
||||||
|
if (!certStatus) {
|
||||||
|
return notFound(res, `No SSL certificate status found for service: ${serviceId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, { certificate: certStatus });
|
||||||
|
}, 'ssl-certificate-service'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /ssl/check
|
||||||
|
* Trigger an on-demand check of all SSL certificates
|
||||||
|
*/
|
||||||
|
router.post('/check', asyncHandler(async (req, res) => {
|
||||||
|
const results = await sslMonitor.checkAll();
|
||||||
|
success(res, { certificates: results, message: 'SSL check completed' });
|
||||||
|
}, 'ssl-check-all'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /ssl/check/:serviceId
|
||||||
|
* Check the SSL certificate for a specific service
|
||||||
|
*/
|
||||||
|
router.post('/check/:serviceId', asyncHandler(async (req, res) => {
|
||||||
|
const { serviceId } = req.params;
|
||||||
|
|
||||||
|
// Look up the existing cert status to find the hostname
|
||||||
|
const existingCert = sslMonitor.getServiceCertStatus(serviceId);
|
||||||
|
if (!existingCert) {
|
||||||
|
return notFound(res, `No HTTPS URL found for service: ${serviceId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await sslMonitor.checkCert(existingCert.hostname, existingCert.port);
|
||||||
|
success(res, { certificate: { ...result, serviceId } });
|
||||||
|
} catch (err) {
|
||||||
|
errorResponse(res, `Failed to check SSL certificate: ${err.message}`, 500);
|
||||||
|
}
|
||||||
|
}, 'ssl-check-service'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /ssl/config
|
||||||
|
* Get current SSL monitoring configuration
|
||||||
|
*/
|
||||||
|
router.get('/config', asyncHandler(async (req, res) => {
|
||||||
|
const config = sslMonitor.getConfig();
|
||||||
|
success(res, { config });
|
||||||
|
}, 'ssl-config-get'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /ssl/config
|
||||||
|
* Update SSL monitoring configuration
|
||||||
|
* Body: { enabled: boolean, intervalMs: number }
|
||||||
|
*/
|
||||||
|
router.post('/config', asyncHandler(async (req, res) => {
|
||||||
|
const { enabled, intervalMs } = req.body;
|
||||||
|
|
||||||
|
// Validate inputs
|
||||||
|
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
||||||
|
return errorResponse(res, 'enabled must be a boolean', 400);
|
||||||
|
}
|
||||||
|
if (intervalMs !== undefined) {
|
||||||
|
if (typeof intervalMs !== 'number' || intervalMs < 60000) {
|
||||||
|
return errorResponse(res, 'intervalMs must be a number >= 60000 (1 minute)', 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updates = {};
|
||||||
|
if (enabled !== undefined) updates.enabled = enabled;
|
||||||
|
if (intervalMs !== undefined) updates.intervalMs = intervalMs;
|
||||||
|
|
||||||
|
sslMonitor.updateConfig(updates);
|
||||||
|
const config = sslMonitor.getConfig();
|
||||||
|
success(res, { config, message: 'SSL monitoring config updated' });
|
||||||
|
}, 'ssl-config-update'));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
};
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
const express = require('express');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Workflows routes factory
|
||||||
|
* @param {Object} deps - Explicit dependencies
|
||||||
|
* @param {Object} deps.workflowEngine - WorkflowEngine instance
|
||||||
|
* @param {Object} deps.licenseManager - License manager for premium gating
|
||||||
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
||||||
|
* @returns {express.Router}
|
||||||
|
*/
|
||||||
|
module.exports = function({ workflowEngine, licenseManager, asyncHandler }) {
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Apply premium gating to all workflows routes
|
||||||
|
router.use(licenseManager.requirePremium('workflows'));
|
||||||
|
|
||||||
|
// ===== WORKFLOW MANAGEMENT ENDPOINTS =====
|
||||||
|
|
||||||
|
// List all bundled workflows
|
||||||
|
router.get('/workflows', asyncHandler(async (req, res) => {
|
||||||
|
const workflows = workflowEngine.listWorkflows();
|
||||||
|
res.json({ success: true, workflows });
|
||||||
|
}, 'workflows-list'));
|
||||||
|
|
||||||
|
// Enable a workflow
|
||||||
|
router.post('/workflows/:workflowId/enable', asyncHandler(async (req, res) => {
|
||||||
|
const { workflowId } = req.params;
|
||||||
|
const result = workflowEngine.setWorkflowEnabled(workflowId, true);
|
||||||
|
res.json({ success: true, ...result });
|
||||||
|
}, 'workflows-enable'));
|
||||||
|
|
||||||
|
// Disable a workflow
|
||||||
|
router.post('/workflows/:workflowId/disable', asyncHandler(async (req, res) => {
|
||||||
|
const { workflowId } = req.params;
|
||||||
|
const result = workflowEngine.setWorkflowEnabled(workflowId, false);
|
||||||
|
res.json({ success: true, ...result });
|
||||||
|
}, 'workflows-disable'));
|
||||||
|
|
||||||
|
// Manually trigger a workflow
|
||||||
|
router.post('/workflows/:workflowId/run', asyncHandler(async (req, res) => {
|
||||||
|
const { workflowId } = req.params;
|
||||||
|
const triggerData = req.body || {};
|
||||||
|
triggerData.trigger = 'manual';
|
||||||
|
|
||||||
|
const result = await workflowEngine.executeWorkflow(workflowId, triggerData);
|
||||||
|
res.json({ success: true, result });
|
||||||
|
}, 'workflows-run'));
|
||||||
|
|
||||||
|
// Get execution history for a workflow
|
||||||
|
router.get('/workflows/:workflowId/history', asyncHandler(async (req, res) => {
|
||||||
|
const { workflowId } = req.params;
|
||||||
|
const limit = parseInt(req.query.limit) || 50;
|
||||||
|
const history = workflowEngine.getHistory(workflowId, limit);
|
||||||
|
res.json({ success: true, history });
|
||||||
|
}, 'workflows-history'));
|
||||||
|
|
||||||
|
// Get all workflow execution history
|
||||||
|
router.get('/workflows/history', asyncHandler(async (req, res) => {
|
||||||
|
const limit = parseInt(req.query.limit) || 100;
|
||||||
|
const history = workflowEngine.getHistory(null, limit);
|
||||||
|
res.json({ success: true, history });
|
||||||
|
}, 'workflows-all-history'));
|
||||||
|
|
||||||
|
return router;
|
||||||
|
};
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
+39
-1
@@ -67,9 +67,38 @@ process.on('uncaughtException', (error) => {
|
|||||||
const portLockManager = require('./port-lock-manager');
|
const portLockManager = require('./port-lock-manager');
|
||||||
|
|
||||||
// Optional modules
|
// Optional modules
|
||||||
let dockerMaintenance, logDigest;
|
let dockerMaintenance, logDigest, bundledWorkflows;
|
||||||
try { dockerMaintenance = require('./docker-maintenance'); } catch { /* optional */ }
|
try { dockerMaintenance = require('./docker-maintenance'); } catch { /* optional */ }
|
||||||
try { logDigest = require('./log-digest'); } catch { /* optional */ }
|
try { logDigest = require('./log-digest'); } catch { /* optional */ }
|
||||||
|
try { bundledWorkflows = require('./bundled-workflows'); } catch { /* optional */ }
|
||||||
|
|
||||||
|
// Initialize workflow engine if bundled-workflows is available
|
||||||
|
// NOTE: createApp() already initializes the workflow engine in src/app.js
|
||||||
|
// This block is kept for backward compat with entry points that don't use createApp()
|
||||||
|
let workflowEngine = null;
|
||||||
|
if (bundledWorkflows) {
|
||||||
|
try {
|
||||||
|
const { fetchT } = require('./src/utils/http');
|
||||||
|
const { WorkflowEngine } = bundledWorkflows;
|
||||||
|
// Create a context with needed services
|
||||||
|
const workflowCtx = {
|
||||||
|
docker: { client: require('dockerode')() },
|
||||||
|
notification: require('./notification-manager')({
|
||||||
|
NOTIFICATIONS_FILE: process.env.NOTIFICATIONS_FILE || require('./platform-paths').notificationsFile,
|
||||||
|
fetchT,
|
||||||
|
log,
|
||||||
|
config
|
||||||
|
}),
|
||||||
|
backupManager,
|
||||||
|
resourceMonitor,
|
||||||
|
servicesStateManager
|
||||||
|
};
|
||||||
|
workflowEngine = new WorkflowEngine(workflowCtx);
|
||||||
|
log.info('server', 'Workflow engine initialized');
|
||||||
|
} catch (err) {
|
||||||
|
log.error('server', 'Workflow engine failed to initialize', { error: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
log.info('server', 'Starting feature modules');
|
log.info('server', 'Starting feature modules');
|
||||||
|
|
||||||
@@ -81,6 +110,10 @@ process.on('uncaughtException', (error) => {
|
|||||||
// Resource monitoring
|
// Resource monitoring
|
||||||
try {
|
try {
|
||||||
resourceMonitor.start();
|
resourceMonitor.start();
|
||||||
|
// Connect workflow engine to resource monitor for resource-alert events
|
||||||
|
if (workflowEngine) {
|
||||||
|
resourceMonitor.setWorkflowEngine(workflowEngine);
|
||||||
|
}
|
||||||
log.info('server', 'Resource monitoring started');
|
log.info('server', 'Resource monitoring started');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.error('server', 'Resource monitoring failed to start', { error: err.message });
|
log.error('server', 'Resource monitoring failed to start', { error: err.message });
|
||||||
@@ -94,6 +127,11 @@ process.on('uncaughtException', (error) => {
|
|||||||
log.error('server', 'Backup manager failed to start', { error: err.message });
|
log.error('server', 'Backup manager failed to start', { error: err.message });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Connect workflow engine to update manager for pre-update events
|
||||||
|
if (workflowEngine) {
|
||||||
|
updateManager.setWorkflowEngine(workflowEngine);
|
||||||
|
}
|
||||||
|
|
||||||
// Health checker (with service sync)
|
// Health checker (with service sync)
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
+138
-4
@@ -39,6 +39,13 @@ let dockerMaintenance, logDigest;
|
|||||||
try { dockerMaintenance = require('../docker-maintenance'); } catch (_) { /* optional module */ }
|
try { dockerMaintenance = require('../docker-maintenance'); } catch (_) { /* optional module */ }
|
||||||
try { logDigest = require('../log-digest'); } catch (_) { /* optional module */ }
|
try { logDigest = require('../log-digest'); } catch (_) { /* optional module */ }
|
||||||
|
|
||||||
|
// Workflow engine (bundled workflows)
|
||||||
|
let bundledWorkflowsModule;
|
||||||
|
let workflowEngine = null;
|
||||||
|
try {
|
||||||
|
bundledWorkflowsModule = require('../bundled-workflows');
|
||||||
|
} catch (_) { /* optional module */ }
|
||||||
|
|
||||||
// Templates
|
// Templates
|
||||||
const { APP_TEMPLATES, TEMPLATE_CATEGORIES, DIFFICULTY_LEVELS } = require('../app-templates');
|
const { APP_TEMPLATES, TEMPLATE_CATEGORIES, DIFFICULTY_LEVELS } = require('../app-templates');
|
||||||
const { RECIPE_TEMPLATES, RECIPE_CATEGORIES } = require('../recipe-templates');
|
const { RECIPE_TEMPLATES, RECIPE_CATEGORIES } = require('../recipe-templates');
|
||||||
@@ -69,6 +76,16 @@ const recipesRoutes = require('../routes/recipes');
|
|||||||
const themesRoutes = require('../routes/themes');
|
const themesRoutes = require('../routes/themes');
|
||||||
const dockerResourcesRoutes = require('../routes/docker-resources');
|
const dockerResourcesRoutes = require('../routes/docker-resources');
|
||||||
const eventsRoutes = require('../routes/events');
|
const eventsRoutes = require('../routes/events');
|
||||||
|
const workflowsRoutes = require('../routes/workflows');
|
||||||
|
const dependenciesRoutes = require('../routes/dependencies');
|
||||||
|
const DependencyManager = require('../dependency-manager');
|
||||||
|
const autoRestartRoutes = require('../routes/auto-restart');
|
||||||
|
const configDriftRoutes = require('../routes/config-drift');
|
||||||
|
const sslMonitorRoutes = require('../routes/ssl-monitor');
|
||||||
|
const { AutoRestartManager } = require('../auto-restart-manager');
|
||||||
|
const { ConfigDriftDetector } = require('../config-drift-detector');
|
||||||
|
const SSLMonitor = require('../ssl-monitor');
|
||||||
|
const DNSPropagationChecker = require('../dns-propagation');
|
||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
const { APP } = require('../constants');
|
const { APP } = require('../constants');
|
||||||
@@ -308,9 +325,88 @@ async function createApp() {
|
|||||||
app,
|
app,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Initialize workflow engine if bundled-workflows is available
|
||||||
|
if (bundledWorkflowsModule && ctx.docker) {
|
||||||
|
try {
|
||||||
|
const { WorkflowEngine } = bundledWorkflowsModule;
|
||||||
|
const workflowCtx = {
|
||||||
|
docker: ctx.docker,
|
||||||
|
notification: ctx.notification,
|
||||||
|
backupManager: ctx.backupManager,
|
||||||
|
resourceMonitor: ctx.resourceMonitor,
|
||||||
|
servicesStateManager: ctx.servicesStateManager
|
||||||
|
};
|
||||||
|
workflowEngine = new WorkflowEngine(workflowCtx);
|
||||||
|
ctx.workflowEngine = workflowEngine;
|
||||||
|
log.info('app', 'Workflow engine initialized');
|
||||||
|
} catch (err) {
|
||||||
|
log.error('app', 'Failed to initialize workflow engine', { error: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize dependency manager
|
||||||
|
const dependencyManager = new DependencyManager({
|
||||||
|
servicesStateManager,
|
||||||
|
docker: ctx.docker,
|
||||||
|
notification: ctx.notification,
|
||||||
|
log,
|
||||||
|
});
|
||||||
|
ctx.dependencyManager = dependencyManager;
|
||||||
|
log.info('app', 'Dependency manager initialized');
|
||||||
|
|
||||||
|
// Initialize auto-restart manager
|
||||||
|
const autoRestartManager = new AutoRestartManager(ctx);
|
||||||
|
ctx.autoRestartManager = autoRestartManager;
|
||||||
|
autoRestartManager.start();
|
||||||
|
log.info('app', 'Auto-restart manager initialized');
|
||||||
|
|
||||||
|
// Initialize config drift detector
|
||||||
|
const driftDetector = new ConfigDriftDetector(ctx);
|
||||||
|
ctx.driftDetector = driftDetector;
|
||||||
|
driftDetector.startPolling(300000); // 5 min
|
||||||
|
log.info('app', 'Config drift detector initialized');
|
||||||
|
|
||||||
|
// Initialize SSL monitor
|
||||||
|
const sslMonitor = new SSLMonitor(ctx);
|
||||||
|
ctx.sslMonitor = sslMonitor;
|
||||||
|
sslMonitor.start(3600000); // 1 hour
|
||||||
|
log.info('app', 'SSL monitor initialized');
|
||||||
|
|
||||||
|
// Initialize DNS propagation checker
|
||||||
|
const dnsPropagationChecker = new DNSPropagationChecker(ctx);
|
||||||
|
ctx.dnsPropagationChecker = dnsPropagationChecker;
|
||||||
|
log.info('app', 'DNS propagation checker initialized');
|
||||||
|
|
||||||
// Build versioned API router
|
// Build versioned API router
|
||||||
const apiRouter = express.Router();
|
const apiRouter = express.Router();
|
||||||
|
|
||||||
|
// Wire up notification listeners for resourceMonitor and backupManager
|
||||||
|
if (ctx.notification && ctx.resourceMonitor) {
|
||||||
|
ctx.resourceMonitor.on('alert', (alertData) => {
|
||||||
|
ctx.notification.sendAlert(alertData).catch(err => {
|
||||||
|
log.error('notification', 'Failed to send alert', { error: err.message });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
ctx.resourceMonitor.on('auto-restart', (data) => {
|
||||||
|
ctx.notification.sendServiceEvent('auto-restart', data).catch(err => {
|
||||||
|
log.error('notification', 'Failed to send auto-restart notification', { error: err.message });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx.notification && ctx.backupManager) {
|
||||||
|
ctx.backupManager.on('backup-complete', (data) => {
|
||||||
|
ctx.notification.send('backup-complete', data).catch(err => {
|
||||||
|
log.error('notification', 'Failed to send backup-complete', { error: err.message });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
ctx.backupManager.on('backup-failed', (data) => {
|
||||||
|
ctx.notification.send('backup-failed', data).catch(err => {
|
||||||
|
log.error('notification', 'Failed to send backup-failed', { error: err.message });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Mount route modules
|
// Mount route modules
|
||||||
apiRouter.use(authRoutes(ctx));
|
apiRouter.use(authRoutes(ctx));
|
||||||
apiRouter.use(configRoutes(ctx));
|
apiRouter.use(configRoutes(ctx));
|
||||||
@@ -321,7 +417,8 @@ async function createApp() {
|
|||||||
log: ctx.log,
|
log: ctx.log,
|
||||||
safeErrorMessage: ctx.safeErrorMessage,
|
safeErrorMessage: ctx.safeErrorMessage,
|
||||||
fetchT: ctx.fetchT,
|
fetchT: ctx.fetchT,
|
||||||
credentialManager: ctx.credentialManager
|
credentialManager: ctx.credentialManager,
|
||||||
|
dnsPropagationChecker: ctx.dnsPropagationChecker
|
||||||
}));
|
}));
|
||||||
apiRouter.use('/notifications', notificationRoutes({
|
apiRouter.use('/notifications', notificationRoutes({
|
||||||
notification: ctx.notification,
|
notification: ctx.notification,
|
||||||
@@ -330,7 +427,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,
|
||||||
@@ -361,7 +459,8 @@ async function createApp() {
|
|||||||
resourceMonitor: ctx.resourceMonitor,
|
resourceMonitor: ctx.resourceMonitor,
|
||||||
docker: ctx.docker,
|
docker: ctx.docker,
|
||||||
asyncHandler: ctx.asyncHandler,
|
asyncHandler: ctx.asyncHandler,
|
||||||
log: ctx.log
|
log: ctx.log,
|
||||||
|
notificationManager: ctx.notification
|
||||||
}));
|
}));
|
||||||
apiRouter.use(updatesRoutes({
|
apiRouter.use(updatesRoutes({
|
||||||
updateManager: ctx.updateManager,
|
updateManager: ctx.updateManager,
|
||||||
@@ -404,6 +503,7 @@ async function createApp() {
|
|||||||
}));
|
}));
|
||||||
apiRouter.use(backupsRoutes({
|
apiRouter.use(backupsRoutes({
|
||||||
backupManager: ctx.backupManager,
|
backupManager: ctx.backupManager,
|
||||||
|
licenseManager: ctx.licenseManager,
|
||||||
asyncHandler: ctx.asyncHandler
|
asyncHandler: ctx.asyncHandler
|
||||||
}));
|
}));
|
||||||
apiRouter.use('/ca', caRoutes(ctx));
|
apiRouter.use('/ca', caRoutes(ctx));
|
||||||
@@ -432,7 +532,41 @@ async function createApp() {
|
|||||||
resourceMonitor: ctx.resourceMonitor,
|
resourceMonitor: ctx.resourceMonitor,
|
||||||
healthChecker: ctx.healthChecker,
|
healthChecker: ctx.healthChecker,
|
||||||
updateManager: ctx.updateManager,
|
updateManager: ctx.updateManager,
|
||||||
logError: ctx.logError
|
logError: ctx.logError,
|
||||||
|
dependencyManager: ctx.dependencyManager,
|
||||||
|
autoRestartManager: ctx.autoRestartManager,
|
||||||
|
driftDetector: ctx.driftDetector,
|
||||||
|
sslMonitor: ctx.sslMonitor,
|
||||||
|
dnsPropagationChecker: ctx.dnsPropagationChecker
|
||||||
|
}));
|
||||||
|
apiRouter.use('/workflows', workflowsRoutes({
|
||||||
|
workflowEngine: ctx.workflowEngine,
|
||||||
|
licenseManager: ctx.licenseManager,
|
||||||
|
asyncHandler: ctx.asyncHandler
|
||||||
|
}));
|
||||||
|
apiRouter.use('/dependencies', dependenciesRoutes({
|
||||||
|
dependencyManager: ctx.dependencyManager,
|
||||||
|
servicesStateManager: ctx.servicesStateManager,
|
||||||
|
docker: ctx.docker,
|
||||||
|
asyncHandler: ctx.asyncHandler,
|
||||||
|
logError: ctx.logError,
|
||||||
|
resyncHealthChecker: ctx.resyncHealthChecker,
|
||||||
|
log: ctx.log,
|
||||||
|
}));
|
||||||
|
apiRouter.use(autoRestartRoutes({
|
||||||
|
autoRestartManager: ctx.autoRestartManager,
|
||||||
|
asyncHandler: ctx.asyncHandler,
|
||||||
|
logError: ctx.logError,
|
||||||
|
}));
|
||||||
|
apiRouter.use(configDriftRoutes({
|
||||||
|
driftDetector: ctx.driftDetector,
|
||||||
|
asyncHandler: ctx.asyncHandler,
|
||||||
|
logError: ctx.logError,
|
||||||
|
}));
|
||||||
|
apiRouter.use(sslMonitorRoutes({
|
||||||
|
sslMonitor: ctx.sslMonitor,
|
||||||
|
asyncHandler: ctx.asyncHandler,
|
||||||
|
logError: ctx.logError,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Inline API routes
|
// Inline API routes
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
/**
|
/**
|
||||||
* DNS context - Technitium DNS operations and token management
|
* DNS context - Technitium DNS operations and token management
|
||||||
|
*
|
||||||
|
* DEPRECATED: This module is kept for backward compatibility.
|
||||||
|
* New code should use src/context/provider-dns.js which supports multiple providers.
|
||||||
|
*
|
||||||
|
* This module now delegates to the provider system internally.
|
||||||
*/
|
*/
|
||||||
const { TIMEOUTS, SESSION_TTL, CADDY } = require('../../constants');
|
const { TIMEOUTS, SESSION_TTL, CADDY } = require('../../constants');
|
||||||
const { createCache, CACHE_CONFIGS } = require('../../cache-config');
|
const { createCache, CACHE_CONFIGS } = require('../../cache-config');
|
||||||
|
const { createProviderDnsContext } = require('./provider-dns');
|
||||||
|
|
||||||
// DNS token management
|
// DNS token management
|
||||||
let dnsToken = process.env.DNS_ADMIN_TOKEN || '';
|
let dnsToken = process.env.DNS_ADMIN_TOKEN || '';
|
||||||
@@ -281,6 +287,10 @@ function invalidateTokenForServer(serverIp) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE) {
|
function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE) {
|
||||||
|
// Create the new provider-aware context
|
||||||
|
const providerCtx = createProviderDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE);
|
||||||
|
|
||||||
|
// Legacy Technitium-specific wrappers (kept for backward compat)
|
||||||
const ensureToken = () => ensureValidDnsToken(siteConfig, credentialManager, fetchT, log);
|
const ensureToken = () => ensureValidDnsToken(siteConfig, credentialManager, fetchT, log);
|
||||||
const require = (providedToken) => requireDnsToken(providedToken, siteConfig, credentialManager, fetchT, log);
|
const require = (providedToken) => requireDnsToken(providedToken, siteConfig, credentialManager, fetchT, log);
|
||||||
const getForServer = (server, role) => getTokenForServer(server, siteConfig, credentialManager, fetchT, log, role);
|
const getForServer = (server, role) => getTokenForServer(server, siteConfig, credentialManager, fetchT, log, role);
|
||||||
@@ -289,6 +299,7 @@ function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, ht
|
|||||||
const call = (server, apiPath, params) => callDns(server, apiPath, params, fetchT, httpsAgent);
|
const call = (server, apiPath, params) => callDns(server, apiPath, params, fetchT, httpsAgent);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
// Legacy Technitium-specific interface (unchanged)
|
||||||
call,
|
call,
|
||||||
buildUrl: buildDnsUrl,
|
buildUrl: buildDnsUrl,
|
||||||
requireToken: require,
|
requireToken: require,
|
||||||
@@ -302,6 +313,17 @@ function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, ht
|
|||||||
invalidateTokenForServer,
|
invalidateTokenForServer,
|
||||||
refresh,
|
refresh,
|
||||||
credentialsFile: DNS_CREDENTIALS_FILE,
|
credentialsFile: DNS_CREDENTIALS_FILE,
|
||||||
|
|
||||||
|
// Provider-aware methods (new)
|
||||||
|
getProviderId: providerCtx.getProviderId,
|
||||||
|
getActiveProvider: providerCtx.getActiveProvider,
|
||||||
|
getAvailableProviders: providerCtx.getAvailableProviders,
|
||||||
|
supportsCapability: providerCtx.supportsCapability,
|
||||||
|
|
||||||
|
// Universal DNS helpers (delegated to provider context)
|
||||||
|
universalCreateRecord: providerCtx.universalCreateRecord,
|
||||||
|
universalDeleteRecord: providerCtx.universalDeleteRecord,
|
||||||
|
universalResolveRecord: providerCtx.universalResolveRecord,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const { createDockerContext } = require('./docker');
|
|||||||
const { createCaddyContext } = require('./caddy');
|
const { createCaddyContext } = require('./caddy');
|
||||||
const { createDnsContext } = require('./dns');
|
const { createDnsContext } = require('./dns');
|
||||||
const { createSessionContext } = require('./session');
|
const { createSessionContext } = require('./session');
|
||||||
|
const NotificationManager = require('../../notification-manager');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Assemble the full application context
|
* Assemble the full application context
|
||||||
@@ -85,11 +86,14 @@ function assembleContext({
|
|||||||
const dns = createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE);
|
const dns = createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE);
|
||||||
const session = createSessionContext(middlewareResult);
|
const session = createSessionContext(middlewareResult);
|
||||||
|
|
||||||
// Notification context (inline for now - could be extracted)
|
// Create notification manager
|
||||||
const notification = {
|
const notification = new NotificationManager({
|
||||||
// These will be populated by server.js for now
|
NOTIFICATIONS_FILE,
|
||||||
// TODO: Extract notification module
|
fetchT,
|
||||||
};
|
docker,
|
||||||
|
log,
|
||||||
|
config: siteConfig
|
||||||
|
});
|
||||||
|
|
||||||
// Tailscale context (inline for now - could be extracted)
|
// Tailscale context (inline for now - could be extracted)
|
||||||
const tailscale = {
|
const tailscale = {
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
/**
|
||||||
|
* Provider-aware DNS Context
|
||||||
|
* Replaces the Technitium-only context with a provider-agnostic layer.
|
||||||
|
* Delegates to the active DNS provider adapter based on config.
|
||||||
|
*
|
||||||
|
* Falls back to legacy Technitium context for backward compatibility
|
||||||
|
* when no provider is explicitly configured.
|
||||||
|
*/
|
||||||
|
const { createCache, CACHE_CONFIGS } = require('../../cache-config');
|
||||||
|
const { TIMEOUTS, SESSION_TTL, CADDY } = require('../../constants');
|
||||||
|
const registry = require('../../dns-providers/registry');
|
||||||
|
|
||||||
|
// Per-server token cache (legacy Technitium)
|
||||||
|
const dnsServerTokens = createCache(CACHE_CONFIGS.dnsTokens);
|
||||||
|
let dnsToken = '';
|
||||||
|
let dnsTokenExpiry = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a provider-aware DNS context.
|
||||||
|
* This wraps both the new provider system and the legacy Technitium context
|
||||||
|
* for seamless migration.
|
||||||
|
*/
|
||||||
|
function createProviderDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE) {
|
||||||
|
/** Resolve the active provider from config */
|
||||||
|
function getProviderId() {
|
||||||
|
// New explicit provider field
|
||||||
|
if (siteConfig.dns?.provider) return siteConfig.dns.provider;
|
||||||
|
// Legacy: if dns.ip is set, default to technitium
|
||||||
|
if (siteConfig.dnsServerIp || siteConfig.dns?.ip) return 'technitium';
|
||||||
|
// No DNS configured
|
||||||
|
return 'manual';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get provider-specific config from site config */
|
||||||
|
function getProviderConfig(providerId) {
|
||||||
|
const dnsConfig = siteConfig.dns || {};
|
||||||
|
|
||||||
|
switch (providerId) {
|
||||||
|
case 'technitium':
|
||||||
|
return {
|
||||||
|
serverIp: siteConfig.dnsServerIp || dnsConfig.ip || '',
|
||||||
|
serverPort: siteConfig.dnsServerPort || dnsConfig.port || '5380',
|
||||||
|
dnsServers: siteConfig.dnsServers || {},
|
||||||
|
dnsId: Object.keys(siteConfig.dnsServers || {})[0] || 'dns1'
|
||||||
|
};
|
||||||
|
case 'cloudflare':
|
||||||
|
return {
|
||||||
|
apiToken: dnsConfig.apiToken || '',
|
||||||
|
zoneId: dnsConfig.zoneId || '',
|
||||||
|
domain: siteConfig.domain || ''
|
||||||
|
};
|
||||||
|
case 'rfc2136':
|
||||||
|
return {
|
||||||
|
server: dnsConfig.server || siteConfig.dnsServerIp || '',
|
||||||
|
port: dnsConfig.port || 53,
|
||||||
|
zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
tsigAlgorithm: dnsConfig.tsigAlgorithm || 'hmac-sha256',
|
||||||
|
tsigKeyName: dnsConfig.tsigKeyName || '',
|
||||||
|
tsigSecret: dnsConfig.tsigSecret || ''
|
||||||
|
};
|
||||||
|
case 'manual':
|
||||||
|
return {};
|
||||||
|
default:
|
||||||
|
return dnsConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get or create the active provider adapter */
|
||||||
|
function getActiveProvider() {
|
||||||
|
const providerId = getProviderId();
|
||||||
|
const config = getProviderConfig(providerId);
|
||||||
|
const ctx = { log, credentialManager, fetchT, httpsAgent };
|
||||||
|
return registry.getProvider(providerId, config, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Legacy Technitium helpers (kept for backward compat) =====
|
||||||
|
function buildDnsUrl(server, apiPath, params) {
|
||||||
|
const protocol = server.match(/^\d+\.\d+\.\d+\.\d+$/) ? 'http' : 'https';
|
||||||
|
const port = protocol === 'http' ? `:${CADDY.DEFAULT_DNS_PORT}` : '';
|
||||||
|
const qs = params instanceof URLSearchParams ? params.toString() : new URLSearchParams(params).toString();
|
||||||
|
return `${protocol}://${server}${port}${apiPath}?${qs}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function callDns(server, apiPath, params) {
|
||||||
|
const url = buildDnsUrl(server, apiPath, params);
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' },
|
||||||
|
agent: httpsAgent
|
||||||
|
}, TIMEOUTS.HTTP_LONG);
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshDnsToken(username, password, server) {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ user: username, pass: password, includeInfo: 'false' });
|
||||||
|
const response = await fetchT(
|
||||||
|
`http://${server}:5380/api/user/login?${params.toString()}`,
|
||||||
|
{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 10000 }
|
||||||
|
);
|
||||||
|
const result = await response.json();
|
||||||
|
if (result.status === 'ok' && result.token) {
|
||||||
|
dnsToken = result.token;
|
||||||
|
dnsTokenExpiry = new Date(Date.now() + SESSION_TTL.DNS_TOKEN).toISOString();
|
||||||
|
log.info('dns', 'DNS token refreshed', { expires: dnsTokenExpiry });
|
||||||
|
return { success: true, token: dnsToken };
|
||||||
|
}
|
||||||
|
return { success: false, error: result.errorMessage || 'Login failed' };
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'DNS token refresh error', { error: error.message });
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dnsIpToDnsId(serverIp) {
|
||||||
|
for (const [dnsId, info] of Object.entries(siteConfig.dnsServers || {})) {
|
||||||
|
if (info.ip === serverIp) return dnsId;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureValidDnsToken() {
|
||||||
|
if (dnsToken && dnsTokenExpiry && new Date() < new Date(dnsTokenExpiry)) {
|
||||||
|
return { success: true, token: dnsToken };
|
||||||
|
}
|
||||||
|
const primaryIp = siteConfig.dnsServerIp;
|
||||||
|
if (primaryIp) {
|
||||||
|
const dnsId = dnsIpToDnsId(primaryIp);
|
||||||
|
if (dnsId) {
|
||||||
|
for (const role of ['admin', 'readonly']) {
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve(`dns.${dnsId}.${role}.username`);
|
||||||
|
const password = await credentialManager.retrieve(`dns.${dnsId}.${role}.password`);
|
||||||
|
if (username && password) return await refreshDnsToken(username, password, primaryIp);
|
||||||
|
} catch (err) { /* try next */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve('dns.username');
|
||||||
|
const password = await credentialManager.retrieve('dns.password');
|
||||||
|
const server = await credentialManager.retrieve('dns.server');
|
||||||
|
if (username && password) return await refreshDnsToken(username, password, server || primaryIp);
|
||||||
|
} catch (err) { /* no global creds */ }
|
||||||
|
return { success: false, error: 'No DNS credentials configured' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getTokenForServer(targetServer, role = 'readonly') {
|
||||||
|
const cacheKey = `${targetServer}:${role}`;
|
||||||
|
const cached = dnsServerTokens.get(cacheKey);
|
||||||
|
if (cached?.token && cached?.expiry && new Date() < new Date(cached.expiry)) {
|
||||||
|
return { success: true, token: cached.token };
|
||||||
|
}
|
||||||
|
const serverPort = siteConfig.dnsServerPort || '5380';
|
||||||
|
async function authToServer(username, password) {
|
||||||
|
const params = new URLSearchParams({ user: username, pass: password, includeInfo: 'false' });
|
||||||
|
const response = await fetchT(
|
||||||
|
`http://${targetServer}:${serverPort}/api/user/login?${params.toString()}`,
|
||||||
|
{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } }
|
||||||
|
);
|
||||||
|
const result = await response.json();
|
||||||
|
if (result.status === 'ok' && result.token) {
|
||||||
|
dnsServerTokens.set(cacheKey, { token: result.token, expiry: new Date(Date.now() + SESSION_TTL.DNS_TOKEN).toISOString() });
|
||||||
|
log.info('dns', 'DNS token obtained for server', { server: targetServer, role });
|
||||||
|
return { success: true, token: result.token };
|
||||||
|
}
|
||||||
|
return { success: false, error: result.errorMessage || 'Login failed' };
|
||||||
|
}
|
||||||
|
const dnsId = dnsIpToDnsId(targetServer);
|
||||||
|
if (dnsId) {
|
||||||
|
for (const r of [role, role === 'readonly' ? 'admin' : 'readonly']) {
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve(`dns.${dnsId}.${r}.username`);
|
||||||
|
const password = await credentialManager.retrieve(`dns.${dnsId}.${r}.password`);
|
||||||
|
if (username && password) return await authToServer(username, password);
|
||||||
|
} catch { /* try next */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve('dns.username');
|
||||||
|
const password = await credentialManager.retrieve('dns.password');
|
||||||
|
if (username && password) return await authToServer(username, password);
|
||||||
|
} catch { /* no global creds */ }
|
||||||
|
return { success: false, error: 'No DNS credentials configured' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireDnsToken(providedToken) {
|
||||||
|
if (providedToken) return providedToken;
|
||||||
|
const result = await ensureValidDnsToken();
|
||||||
|
if (result.success) return result.token;
|
||||||
|
const err = new Error('No valid DNS token available. ' + result.error);
|
||||||
|
err.statusCode = 401;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidateTokenForServer(serverIp) {
|
||||||
|
dnsServerTokens.delete(`${serverIp}:readonly`);
|
||||||
|
dnsServerTokens.delete(`${serverIp}:admin`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Public context API =====
|
||||||
|
// This maintains the same interface as the old createDnsContext()
|
||||||
|
// but adds provider-aware methods on top.
|
||||||
|
|
||||||
|
return {
|
||||||
|
// --- Provider-aware methods ---
|
||||||
|
/** Get the active provider ID */
|
||||||
|
getProviderId,
|
||||||
|
|
||||||
|
/** Get the active provider adapter instance */
|
||||||
|
getActiveProvider,
|
||||||
|
|
||||||
|
/** Get metadata for all available providers */
|
||||||
|
getAvailableProviders: () => registry.getProviderMeta(),
|
||||||
|
|
||||||
|
/** Check if the active provider supports a capability */
|
||||||
|
supportsCapability: (cap) => {
|
||||||
|
try { return getActiveProvider().supportsCapability(cap); }
|
||||||
|
catch { return false; }
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Legacy Technitium context (backward compat) ---
|
||||||
|
call: callDns,
|
||||||
|
buildUrl: buildDnsUrl,
|
||||||
|
requireToken: requireDnsToken,
|
||||||
|
ensureToken: ensureValidDnsToken,
|
||||||
|
getToken: () => dnsToken,
|
||||||
|
setToken: (t) => { dnsToken = t; },
|
||||||
|
getTokenExpiry: () => dnsTokenExpiry,
|
||||||
|
setTokenExpiry: (e) => { dnsTokenExpiry = e; },
|
||||||
|
getTokenForServer,
|
||||||
|
invalidateTokenForServer,
|
||||||
|
refresh: refreshDnsToken,
|
||||||
|
credentialsFile: DNS_CREDENTIALS_FILE,
|
||||||
|
|
||||||
|
// --- Universal DNS helpers (provider-agnostic) ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a DNS A record using the active provider.
|
||||||
|
* Gracefully handles manual adapters that return instructions instead of performing the action.
|
||||||
|
*/
|
||||||
|
async universalCreateRecord(subdomain, ip) {
|
||||||
|
const provider = getActiveProvider();
|
||||||
|
const result = await provider.createRecord({
|
||||||
|
domain: buildDomain(subdomain),
|
||||||
|
zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: 'A',
|
||||||
|
value: ip,
|
||||||
|
ttl: 300,
|
||||||
|
overwrite: true,
|
||||||
|
});
|
||||||
|
// Manual adapter returns instructions instead of performing the action
|
||||||
|
if (result?.manual || result?.instructions) {
|
||||||
|
return { success: true, manual: true, instructions: result.instructions || result };
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a DNS A record using the active provider.
|
||||||
|
* Gracefully handles manual adapters that return instructions instead of performing the action.
|
||||||
|
*/
|
||||||
|
async universalDeleteRecord(domain, ip) {
|
||||||
|
const provider = getActiveProvider();
|
||||||
|
const result = await provider.deleteRecord({
|
||||||
|
domain,
|
||||||
|
type: 'A',
|
||||||
|
value: ip,
|
||||||
|
});
|
||||||
|
if (result?.manual || result?.instructions) {
|
||||||
|
return { success: true, manual: true, instructions: result.instructions || result };
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve DNS records using the active provider.
|
||||||
|
* Returns parsed IP addresses from the result.
|
||||||
|
*/
|
||||||
|
async universalResolveRecord(domain, type) {
|
||||||
|
const provider = getActiveProvider();
|
||||||
|
const result = await provider.resolveRecords({
|
||||||
|
domain,
|
||||||
|
zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A',
|
||||||
|
});
|
||||||
|
// Parse IP addresses from the result
|
||||||
|
if (Array.isArray(result)) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (result?.records) {
|
||||||
|
return result.records.map(r => r.ipAddress || r.value || r.address || r).filter(Boolean);
|
||||||
|
}
|
||||||
|
if (result?.ips) {
|
||||||
|
return result.ips;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createProviderDnsContext };
|
||||||
@@ -94,8 +94,12 @@ async function logError(ERROR_LOG_FILE, MAX_ERROR_LOG_SIZE, context, error, addi
|
|||||||
* Return a safe error message without leaking internals
|
* Return a safe error message without leaking internals
|
||||||
*/
|
*/
|
||||||
function safeErrorMessage(error) {
|
function safeErrorMessage(error) {
|
||||||
|
if (!error) return 'An internal error occurred';
|
||||||
const msg = error.message || String(error);
|
const msg = error.message || String(error);
|
||||||
|
|
||||||
|
// Always expose DC-prefixed user-facing errors
|
||||||
|
if (/\[DC-\d+\]/.test(msg)) return msg;
|
||||||
|
|
||||||
// Detect port conflict errors
|
// Detect port conflict errors
|
||||||
const portMatch = msg.match(/exposing port TCP [^:]*:(\d+)/);
|
const portMatch = msg.match(/exposing port TCP [^:]*:(\d+)/);
|
||||||
if (portMatch || msg.includes('port is already allocated') || msg.includes('ports are not available')) {
|
if (portMatch || msg.includes('port is already allocated') || msg.includes('ports are not available')) {
|
||||||
@@ -103,7 +107,7 @@ function safeErrorMessage(error) {
|
|||||||
return `[DC-200] Port ${port} is already in use. Try a different port or stop the service using that port first.`;
|
return `[DC-200] Port ${port} is already in use. Try a different port or stop the service using that port first.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only expose short, user-facing messages
|
// Only expose short, user-facing messages (no paths, stack traces, or internal details)
|
||||||
if (msg.length < 200 && !msg.includes('/') && !msg.includes('\\') && !msg.includes(' at ')) {
|
if (msg.length < 200 && !msg.includes('/') && !msg.includes('\\') && !msg.includes(' at ')) {
|
||||||
return msg;
|
return msg;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,411 @@
|
|||||||
|
/**
|
||||||
|
* SSL Certificate Monitor
|
||||||
|
* Periodically checks SSL certificates on services with HTTPS URLs.
|
||||||
|
* Alerts at 30, 14, and 7 days before expiry.
|
||||||
|
*
|
||||||
|
* @module ssl-monitor
|
||||||
|
*/
|
||||||
|
|
||||||
|
const tls = require('tls');
|
||||||
|
const EventEmitter = require('events');
|
||||||
|
const path = require('path');
|
||||||
|
const { readJsonFile, writeJsonFile } = require('./fs-helpers');
|
||||||
|
const { resolveServiceUrl } = require('./url-resolver');
|
||||||
|
|
||||||
|
/** Default check interval: 1 hour */
|
||||||
|
const DEFAULT_INTERVAL_MS = 3600000;
|
||||||
|
|
||||||
|
/** Alert thresholds in days */
|
||||||
|
const THRESHOLDS = {
|
||||||
|
WARNING: 30,
|
||||||
|
URGENT: 14,
|
||||||
|
CRITICAL: 7
|
||||||
|
};
|
||||||
|
|
||||||
|
/** TLS connection timeout in milliseconds */
|
||||||
|
const TLS_TIMEOUT_MS = 10000;
|
||||||
|
|
||||||
|
class SSLMonitor extends EventEmitter {
|
||||||
|
/**
|
||||||
|
* Create an SSLMonitor instance.
|
||||||
|
* @param {Object} ctx - Shared application context
|
||||||
|
* @param {Object} ctx.servicesStateManager - State manager for reading services
|
||||||
|
* @param {Function} ctx.buildServiceUrl - URL builder helper
|
||||||
|
* @param {Object} ctx.siteConfig - Site configuration
|
||||||
|
* @param {Object} ctx.notification - NotificationManager instance
|
||||||
|
* @param {Object} ctx.log - Logger instance
|
||||||
|
* @param {string} [ctx.SSL_CACHE_FILE] - Path to persist SSL cache
|
||||||
|
*/
|
||||||
|
constructor(ctx) {
|
||||||
|
super();
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.log = ctx.log || console;
|
||||||
|
|
||||||
|
/** @type {Map<string, Object>} hostname → last cert check result */
|
||||||
|
this.certStatus = new Map();
|
||||||
|
|
||||||
|
/** @type {Map<string, number>} hostname → last notified threshold level */
|
||||||
|
this.notifiedThresholds = new Map();
|
||||||
|
|
||||||
|
/** @type {Map<string, string>} hostname → service ID mapping */
|
||||||
|
this.hostnameToServiceId = new Map();
|
||||||
|
|
||||||
|
/** @type {NodeJS.Timeout|null} */
|
||||||
|
this.intervalHandle = null;
|
||||||
|
|
||||||
|
/** Current config */
|
||||||
|
this.config = {
|
||||||
|
enabled: true,
|
||||||
|
intervalMs: DEFAULT_INTERVAL_MS
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Cache file path */
|
||||||
|
this.cacheFile = ctx.SSL_CACHE_FILE ||
|
||||||
|
path.join(path.dirname(ctx.SERVICES_FILE || './data'), 'ssl-cache.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check the SSL certificate for a given hostname and port.
|
||||||
|
* Connects via TLS with rejectUnauthorized: false to retrieve certificate info.
|
||||||
|
*
|
||||||
|
* @param {string} hostname - The hostname to check
|
||||||
|
* @param {number} [port=443] - The port to connect to
|
||||||
|
* @returns {Promise<Object>} Certificate information
|
||||||
|
*/
|
||||||
|
async checkCert(hostname, port = 443) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const socket = tls.connect({
|
||||||
|
host: hostname,
|
||||||
|
port,
|
||||||
|
rejectUnauthorized: false,
|
||||||
|
servername: hostname,
|
||||||
|
timeout: TLS_TIMEOUT_MS
|
||||||
|
}, () => {
|
||||||
|
try {
|
||||||
|
const cert = socket.getPeerCertificate();
|
||||||
|
|
||||||
|
if (!cert || Object.keys(cert).length === 0) {
|
||||||
|
socket.destroy();
|
||||||
|
return reject(new Error(`No certificate returned for ${hostname}:${port}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
const validFrom = new Date(cert.valid_from);
|
||||||
|
const validTo = new Date(cert.valid_to);
|
||||||
|
const now = new Date();
|
||||||
|
const msRemaining = validTo.getTime() - now.getTime();
|
||||||
|
const daysRemaining = Math.ceil(msRemaining / (1000 * 60 * 60 * 24));
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
hostname,
|
||||||
|
port,
|
||||||
|
subject: cert.subject?.CN || cert.subject?.O || 'Unknown',
|
||||||
|
issuer: cert.issuer?.CN || cert.issuer?.O || 'Unknown',
|
||||||
|
validFrom: cert.valid_from,
|
||||||
|
validTo: cert.valid_to,
|
||||||
|
daysRemaining,
|
||||||
|
fingerprint: cert.fingerprint || null,
|
||||||
|
isExpiring: daysRemaining <= THRESHOLDS.WARNING,
|
||||||
|
checkedAt: new Date().toISOString()
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.destroy();
|
||||||
|
resolve(result);
|
||||||
|
} catch (err) {
|
||||||
|
socket.destroy();
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('error', (err) => {
|
||||||
|
reject(new Error(`TLS connect error for ${hostname}:${port}: ${err.message}`));
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.setTimeout(TLS_TIMEOUT_MS, () => {
|
||||||
|
socket.destroy(new Error(`TLS connection timeout for ${hostname}:${port}`));
|
||||||
|
reject(new Error(`TLS connection timeout for ${hostname}:${port}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check SSL certificates for all services that have HTTPS URLs.
|
||||||
|
* Reads services from ctx.servicesStateManager, resolves URLs, and checks each HTTPS cert.
|
||||||
|
*
|
||||||
|
* @returns {Promise<Object>} Map of hostname → cert status
|
||||||
|
*/
|
||||||
|
async checkAll() {
|
||||||
|
if (!this.config.enabled) {
|
||||||
|
this.log.info('ssl-monitor', 'SSL monitoring is disabled, skipping check');
|
||||||
|
return this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
let servicesData;
|
||||||
|
try {
|
||||||
|
servicesData = await this.ctx.servicesStateManager.read();
|
||||||
|
} catch (err) {
|
||||||
|
this.log.error('ssl-monitor', 'Failed to read services', { error: err.message });
|
||||||
|
return this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
const services = Array.isArray(servicesData) ? servicesData : (servicesData.services || []);
|
||||||
|
|
||||||
|
for (const service of services) {
|
||||||
|
const serviceId = service.id || service.name?.toLowerCase();
|
||||||
|
if (!serviceId) continue;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = resolveServiceUrl(serviceId, service, this.ctx.siteConfig, this.ctx.buildServiceUrl);
|
||||||
|
if (!url) continue;
|
||||||
|
|
||||||
|
const parsed = new URL(url);
|
||||||
|
if (parsed.protocol !== 'https:') continue;
|
||||||
|
|
||||||
|
const hostname = parsed.hostname;
|
||||||
|
const port = parseInt(parsed.port) || 443;
|
||||||
|
|
||||||
|
// Map hostname back to service ID
|
||||||
|
this.hostnameToServiceId.set(hostname, serviceId);
|
||||||
|
|
||||||
|
const result = await this.checkCert(hostname, port);
|
||||||
|
|
||||||
|
// Store result
|
||||||
|
this.certStatus.set(hostname, result);
|
||||||
|
|
||||||
|
// Emit check event
|
||||||
|
this.emit('cert-check', { serviceId, hostname, result });
|
||||||
|
|
||||||
|
// Check alert thresholds
|
||||||
|
await this._checkAndNotify(hostname, result, serviceId);
|
||||||
|
} catch (err) {
|
||||||
|
this.log.warn('ssl-monitor', `Failed to check cert for service ${serviceId}`, {
|
||||||
|
error: err.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist results
|
||||||
|
await this._saveCache();
|
||||||
|
|
||||||
|
return this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start periodic SSL certificate checking.
|
||||||
|
*
|
||||||
|
* @param {number} [intervalMs=3600000] - Check interval in milliseconds
|
||||||
|
*/
|
||||||
|
start(intervalMs) {
|
||||||
|
if (intervalMs !== undefined) {
|
||||||
|
this.config.intervalMs = intervalMs;
|
||||||
|
}
|
||||||
|
if (this.intervalHandle) {
|
||||||
|
this.log.warn('ssl-monitor', 'SSL monitor is already running');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.config.enabled = true;
|
||||||
|
|
||||||
|
// Load cached data
|
||||||
|
this._loadCache().catch(err => {
|
||||||
|
this.log.warn('ssl-monitor', 'Failed to load SSL cache', { error: err.message });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Initial check (non-blocking)
|
||||||
|
this.checkAll().catch(err => {
|
||||||
|
this.log.error('ssl-monitor', 'Initial SSL check failed', { error: err.message });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Schedule periodic checks
|
||||||
|
this.intervalHandle = setInterval(() => {
|
||||||
|
this.checkAll().catch(err => {
|
||||||
|
this.log.error('ssl-monitor', 'Periodic SSL check failed', { error: err.message });
|
||||||
|
});
|
||||||
|
}, this.config.intervalMs);
|
||||||
|
|
||||||
|
this.log.info('ssl-monitor', 'SSL monitoring started', {
|
||||||
|
intervalMs: this.config.intervalMs
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop periodic SSL certificate checking.
|
||||||
|
*/
|
||||||
|
stop() {
|
||||||
|
if (this.intervalHandle) {
|
||||||
|
clearInterval(this.intervalHandle);
|
||||||
|
this.intervalHandle = null;
|
||||||
|
}
|
||||||
|
this.config.enabled = false;
|
||||||
|
this.log.info('ssl-monitor', 'SSL monitoring stopped');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current SSL certificate status for all checked hostnames.
|
||||||
|
*
|
||||||
|
* @returns {Object} Map of hostname → cert status
|
||||||
|
*/
|
||||||
|
getStatus() {
|
||||||
|
const status = {};
|
||||||
|
for (const [hostname, cert] of this.certStatus.entries()) {
|
||||||
|
status[hostname] = { ...cert };
|
||||||
|
}
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the SSL certificate status for a specific service.
|
||||||
|
*
|
||||||
|
* @param {string} serviceId - The service ID to look up
|
||||||
|
* @returns {Object|null} Certificate status or null if not found
|
||||||
|
*/
|
||||||
|
getServiceCertStatus(serviceId) {
|
||||||
|
// Find hostname mapped to this service
|
||||||
|
for (const [hostname, id] of this.hostnameToServiceId.entries()) {
|
||||||
|
if (id === serviceId) {
|
||||||
|
const cert = this.certStatus.get(hostname);
|
||||||
|
return cert ? { ...cert, serviceId } : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current monitoring configuration.
|
||||||
|
*
|
||||||
|
* @returns {Object} Config with interval and enabled state
|
||||||
|
*/
|
||||||
|
getConfig() {
|
||||||
|
return { ...this.config };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update monitoring configuration.
|
||||||
|
*
|
||||||
|
* @param {Object} updates - Config updates
|
||||||
|
* @param {boolean} [updates.enabled] - Enable/disable monitoring
|
||||||
|
* @param {number} [updates.intervalMs] - Check interval in milliseconds
|
||||||
|
*/
|
||||||
|
updateConfig(updates) {
|
||||||
|
if (typeof updates.enabled === 'boolean') {
|
||||||
|
this.config.enabled = updates.enabled;
|
||||||
|
if (!updates.enabled && this.intervalHandle) {
|
||||||
|
this.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (typeof updates.intervalMs === 'number' && updates.intervalMs >= 60000) {
|
||||||
|
this.config.intervalMs = updates.intervalMs;
|
||||||
|
// Restart interval if running
|
||||||
|
if (this.intervalHandle) {
|
||||||
|
clearInterval(this.intervalHandle);
|
||||||
|
this.intervalHandle = setInterval(() => {
|
||||||
|
this.checkAll().catch(err => {
|
||||||
|
this.log.error('ssl-monitor', 'Periodic SSL check failed', { error: err.message });
|
||||||
|
});
|
||||||
|
}, this.config.intervalMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Private Methods =====
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check alert thresholds and send notifications if thresholds are crossed.
|
||||||
|
* Only sends one notification per threshold per hostname.
|
||||||
|
*
|
||||||
|
* @param {string} hostname
|
||||||
|
* @param {Object} certResult
|
||||||
|
* @param {string} serviceId
|
||||||
|
*/
|
||||||
|
async _checkAndNotify(hostname, certResult, serviceId) {
|
||||||
|
const { daysRemaining } = certResult;
|
||||||
|
const key = hostname;
|
||||||
|
const lastNotified = this.notifiedThresholds.get(key) || Infinity;
|
||||||
|
|
||||||
|
let level = null;
|
||||||
|
let eventType = null;
|
||||||
|
let message = null;
|
||||||
|
|
||||||
|
if (daysRemaining <= THRESHOLDS.CRITICAL) {
|
||||||
|
level = THRESHOLDS.CRITICAL;
|
||||||
|
eventType = 'cert-critical';
|
||||||
|
message = `🔒 CRITICAL: SSL certificate for ${hostname} expires in ${daysRemaining} days!`;
|
||||||
|
} else if (daysRemaining <= THRESHOLDS.URGENT) {
|
||||||
|
level = THRESHOLDS.URGENT;
|
||||||
|
eventType = 'cert-expiring';
|
||||||
|
message = `⚠️ URGENT: SSL certificate for ${hostname} expires in ${daysRemaining} days`;
|
||||||
|
} else if (daysRemaining <= THRESHOLDS.WARNING) {
|
||||||
|
level = THRESHOLDS.WARNING;
|
||||||
|
eventType = 'cert-expiring';
|
||||||
|
message = `⚠️ SSL certificate for ${hostname} expires in ${daysRemaining} days`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (level !== null && level < lastNotified) {
|
||||||
|
// New threshold crossed — send notification
|
||||||
|
this.notifiedThresholds.set(key, level);
|
||||||
|
this.emit(eventType, { hostname, serviceId, daysRemaining, level });
|
||||||
|
|
||||||
|
if (this.ctx.notification) {
|
||||||
|
try {
|
||||||
|
await this.ctx.notification.send('ssl-cert-expiry', {
|
||||||
|
text: message,
|
||||||
|
hostname,
|
||||||
|
serviceId,
|
||||||
|
daysRemaining,
|
||||||
|
level,
|
||||||
|
validTo: certResult.validTo
|
||||||
|
}, level <= THRESHOLDS.CRITICAL ? 'error' : 'warning');
|
||||||
|
} catch (err) {
|
||||||
|
this.log.error('ssl-monitor', 'Failed to send SSL notification', { error: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (level === null) {
|
||||||
|
// Cert is healthy — reset notification tracking
|
||||||
|
this.notifiedThresholds.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persist cert status cache to disk.
|
||||||
|
*/
|
||||||
|
async _saveCache() {
|
||||||
|
try {
|
||||||
|
const data = {
|
||||||
|
lastChecked: new Date().toISOString(),
|
||||||
|
certs: {},
|
||||||
|
hostnameToServiceId: Object.fromEntries(this.hostnameToServiceId)
|
||||||
|
};
|
||||||
|
for (const [hostname, cert] of this.certStatus.entries()) {
|
||||||
|
data.certs[hostname] = cert;
|
||||||
|
}
|
||||||
|
await writeJsonFile(this.cacheFile, data);
|
||||||
|
} catch (err) {
|
||||||
|
this.log.warn('ssl-monitor', 'Failed to save SSL cache', { error: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load cert status cache from disk.
|
||||||
|
*/
|
||||||
|
async _loadCache() {
|
||||||
|
try {
|
||||||
|
const data = await readJsonFile(this.cacheFile, null);
|
||||||
|
if (data && data.certs) {
|
||||||
|
for (const [hostname, cert] of Object.entries(data.certs)) {
|
||||||
|
this.certStatus.set(hostname, cert);
|
||||||
|
}
|
||||||
|
if (data.hostnameToServiceId) {
|
||||||
|
for (const [hostname, serviceId] of Object.entries(data.hostnameToServiceId)) {
|
||||||
|
this.hostnameToServiceId.set(hostname, serviceId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.log.info('ssl-monitor', 'Loaded SSL cache', {
|
||||||
|
certCount: this.certStatus.size
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.log.warn('ssl-monitor', 'Failed to load SSL cache', { error: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = SSLMonitor;
|
||||||
@@ -64,6 +64,38 @@ class UpdateManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger bundled workflows for an event
|
||||||
|
*/
|
||||||
|
triggerWorkflows(eventType, eventData) {
|
||||||
|
if (!this.workflowEngine) {
|
||||||
|
console.log('[UpdateManager] Workflow engine not set, skipping workflow trigger');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.workflowEngine.triggerForEvent(eventType, eventData)
|
||||||
|
.then(results => {
|
||||||
|
if (results && results.length > 0) {
|
||||||
|
console.log(`[UpdateManager] Triggered ${results.length} workflow(s) for ${eventType}`);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.error('[UpdateManager] Workflow trigger error:', err.message);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[UpdateManager] Error triggering workflows:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the workflow engine for triggering workflows
|
||||||
|
*/
|
||||||
|
setWorkflowEngine(workflowEngine) {
|
||||||
|
this.workflowEngine = workflowEngine;
|
||||||
|
console.log('[UpdateManager] Workflow engine configured');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check for updates for all containers
|
* Check for updates for all containers
|
||||||
*/
|
*/
|
||||||
@@ -281,6 +313,12 @@ class UpdateManager extends EventEmitter {
|
|||||||
timestamp: new Date().toISOString()
|
timestamp: new Date().toISOString()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Emit pre-update event for bundled workflows (e.g., backup-before-update)
|
||||||
|
this.emit('pre-update', { containerId, containerName, imageName, backup });
|
||||||
|
|
||||||
|
// Also trigger workflows for pre-update event directly
|
||||||
|
this.triggerWorkflows('pre-update', { containerId, containerName, appId: containerName, imageName });
|
||||||
|
|
||||||
// Pull latest image
|
// Pull latest image
|
||||||
console.log(`[UpdateManager] Pulling latest image: ${imageName}`);
|
console.log(`[UpdateManager] Pulling latest image: ${imageName}`);
|
||||||
await this.pullImage(imageName);
|
await this.pullImage(imageName);
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# =============================================================================
|
||||||
|
# DashCaddy Gitea — Off-host backup to Dropbox
|
||||||
|
# =============================================================================
|
||||||
|
# - Stops gitea container briefly to ensure SQLite DB consistency
|
||||||
|
# - Syncs /var/lib/docker/volumes/gitea-data to dropbox:/Apps/dashcaddy-gitea-backups/<date>/
|
||||||
|
# - Date-stamped snapshots (one per day), kept for 7 days locally
|
||||||
|
# - Restarts gitea even if sync fails
|
||||||
|
# - Logs to /var/log/gitea-backup.log
|
||||||
|
# =============================================================================
|
||||||
|
set -u # don't use -e: we want to always restart gitea
|
||||||
|
|
||||||
|
LOG=/var/log/gitea-backup.log
|
||||||
|
DATA_SRC=/var/lib/docker/volumes/gitea-data/_data
|
||||||
|
DEST="dropbox:/Apps/dashcaddy-gitea-backups"
|
||||||
|
TODAY=$(date -u +%Y-%m-%d)
|
||||||
|
BACKUP_PATH="${DEST}/${TODAY}"
|
||||||
|
RETENTION_DAYS=7
|
||||||
|
|
||||||
|
log() { echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*" | tee -a "$LOG"; }
|
||||||
|
|
||||||
|
log "=== Backup start ==="
|
||||||
|
|
||||||
|
# 0. Sanity checks
|
||||||
|
if [ ! -d "$DATA_SRC" ]; then
|
||||||
|
log "ERROR: data dir $DATA_SRC missing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 1. Stop gitea to flush SQLite
|
||||||
|
log "Stopping gitea container..."
|
||||||
|
docker stop gitea >> "$LOG" 2>&1
|
||||||
|
STOP_RC=$?
|
||||||
|
if [ $STOP_RC -ne 0 ]; then
|
||||||
|
log "WARNING: docker stop returned $STOP_RC — container may not be running"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. Sync (use copy so source files are preserved as-is, no --delete)
|
||||||
|
log "Syncing $DATA_SRC -> $BACKUP_PATH"
|
||||||
|
rclone copy "$DATA_SRC" "$BACKUP_PATH" \
|
||||||
|
--transfers 4 \
|
||||||
|
--checkers 8 \
|
||||||
|
--retries 3 \
|
||||||
|
--low-level-retries 10 \
|
||||||
|
--stats 30s \
|
||||||
|
--log-file "$LOG" \
|
||||||
|
--log-level INFO
|
||||||
|
SYNC_RC=$?
|
||||||
|
|
||||||
|
# 3. Always restart gitea
|
||||||
|
log "Starting gitea container..."
|
||||||
|
docker start gitea >> "$LOG" 2>&1
|
||||||
|
START_RC=$?
|
||||||
|
|
||||||
|
# Wait for gitea to be ready
|
||||||
|
for i in {1..30}; do
|
||||||
|
if curl -sf http://localhost:3000/api/v1/version > /dev/null 2>&1; then
|
||||||
|
log "Gitea is up after ${i}s"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
|
# 4. Cleanup old backups (older than RETENTION_DAYS)
|
||||||
|
log "Pruning local + remote snapshots older than ${RETENTION_DAYS} days..."
|
||||||
|
CUTOFF=$(date -u -d "${RETENTION_DAYS} days ago" +%Y-%m-%d)
|
||||||
|
rclone lsf "$DEST/" --dirs-only 2>/dev/null | while read -r d; do
|
||||||
|
# rclone returns names with trailing /
|
||||||
|
name="${d%/}"
|
||||||
|
if [[ "$name" < "$CUTOFF" ]]; then
|
||||||
|
log " removing old: $name"
|
||||||
|
rclone purge "${DEST}/${name}" >> "$LOG" 2>&1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# 5. Report
|
||||||
|
if [ $SYNC_RC -eq 0 ] && [ $START_RC -eq 0 ]; then
|
||||||
|
log "=== Backup OK ==="
|
||||||
|
exit 0
|
||||||
|
else
|
||||||
|
log "=== Backup completed with errors (sync=$SYNC_RC, start=$START_RC) ==="
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
Executable
+379
@@ -0,0 +1,379 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# DashCaddy Host-Side Updater
|
||||||
|
# Triggered by systemd path unit when the container writes trigger.json.
|
||||||
|
# Reads the trigger, backs up current API + data/, copies new files, rebuilds container.
|
||||||
|
# Writes result.json so the new container knows the outcome.
|
||||||
|
#
|
||||||
|
# This runs on the HOST, outside the container.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
readonly UPDATES_DIR="/opt/dashcaddy/updates"
|
||||||
|
readonly TRIGGER_FILE="${UPDATES_DIR}/trigger.json"
|
||||||
|
readonly RESULT_FILE="${UPDATES_DIR}/result.json"
|
||||||
|
readonly BACKUPS_DIR="${UPDATES_DIR}/backups"
|
||||||
|
readonly CONTAINER_NAME="dashcaddy-api"
|
||||||
|
readonly IMAGE_TAG="dashcaddy-dashcaddy-api:latest"
|
||||||
|
readonly MAX_BACKUPS=3
|
||||||
|
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') $*"; }
|
||||||
|
|
||||||
|
write_result() {
|
||||||
|
local success="$1" version="$2" duration="$3"
|
||||||
|
shift 3
|
||||||
|
local error="${1:-}"
|
||||||
|
|
||||||
|
if [[ "$success" == "true" ]]; then
|
||||||
|
cat > "$RESULT_FILE" <<EOF
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"version": "${version}",
|
||||||
|
"duration": ${duration},
|
||||||
|
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
else
|
||||||
|
cat > "$RESULT_FILE" <<EOF
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"version": "${version}",
|
||||||
|
"duration": ${duration},
|
||||||
|
"error": "${error}",
|
||||||
|
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup_old_backups() {
|
||||||
|
local count
|
||||||
|
count=$(find "$BACKUPS_DIR" -maxdepth 1 -mindepth 1 -type d 2>/dev/null | wc -l)
|
||||||
|
if (( count > MAX_BACKUPS )); then
|
||||||
|
log "Cleaning old backups (${count} > ${MAX_BACKUPS})"
|
||||||
|
find "$BACKUPS_DIR" -maxdepth 1 -mindepth 1 -type d -printf '%T+ %p\n' \
|
||||||
|
| sort | head -n $(( count - MAX_BACKUPS )) | cut -d' ' -f2- \
|
||||||
|
| xargs rm -rf
|
||||||
|
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() {
|
||||||
|
local port="${1:-3001}"
|
||||||
|
local timeout="$HEALTH_TIMEOUT"
|
||||||
|
local elapsed=0
|
||||||
|
|
||||||
|
log "Waiting for health check (timeout: ${timeout}s)..."
|
||||||
|
while (( elapsed < timeout )); do
|
||||||
|
if curl -fsSL --max-time 3 "http://localhost:${port}/health" &>/dev/null; then
|
||||||
|
log "Health check passed after ${elapsed}s"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
elapsed=$(( elapsed + 2 ))
|
||||||
|
done
|
||||||
|
|
||||||
|
log "Health check FAILED after ${timeout}s"
|
||||||
|
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
|
||||||
|
if [[ -d "$backup_dir/dns-providers" ]]; then
|
||||||
|
rm -rf "$api_source_dir/dns-providers"
|
||||||
|
cp -rf "$backup_dir/dns-providers" "$api_source_dir/dns-providers"
|
||||||
|
fi
|
||||||
|
restore_data_dir "$backup_dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Deployment mode ───────────────────────────────────────────────────────────
|
||||||
|
# Reproduce the SAME container the install created so an auto-update keeps every
|
||||||
|
# volume + env var (docker socket, Caddyfile, config/credentials, updates mount),
|
||||||
|
# not a minimal subset. Standard installs use docker-compose (compose file in the
|
||||||
|
# api source dir); the publish/dev host uses /opt/dashcaddy/start.sh; otherwise a
|
||||||
|
# bare docker run is the last resort. build_image() and restart_container() both
|
||||||
|
# honor the detected mode so build and run stay consistent.
|
||||||
|
deploy_mode() {
|
||||||
|
if [[ -f "$api_source_dir/docker-compose.yml" || -f "$api_source_dir/compose.yml" || -f "$api_source_dir/compose.yaml" ]]; then
|
||||||
|
echo compose
|
||||||
|
elif [[ -x /opt/dashcaddy/start.sh ]]; then
|
||||||
|
echo startsh
|
||||||
|
else
|
||||||
|
echo run
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build the API image using whatever the install is wired for. Returns the build
|
||||||
|
# command's exit status so callers can detect failure.
|
||||||
|
build_image() {
|
||||||
|
cd "$api_source_dir" || return 1
|
||||||
|
case "$(deploy_mode)" in
|
||||||
|
compose) docker compose build 2>&1 || docker-compose build 2>&1 ;;
|
||||||
|
*) docker build -t "$IMAGE_TAG" . 2>&1 ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Shared container restart — recreate with the full, install-defined spec ───
|
||||||
|
# Recreates (rm + run / compose up) so new code AND new env vars take effect.
|
||||||
|
restart_container() {
|
||||||
|
cd "$api_source_dir" 2>/dev/null || true
|
||||||
|
case "$(deploy_mode)" in
|
||||||
|
compose)
|
||||||
|
log "Recreating container via docker compose (full compose spec)..."
|
||||||
|
docker compose up -d 2>&1 || docker-compose up -d 2>&1
|
||||||
|
;;
|
||||||
|
startsh)
|
||||||
|
log "Recreating container via /opt/dashcaddy/start.sh (full container spec)..."
|
||||||
|
bash /opt/dashcaddy/start.sh
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
log "Recreating container via minimal docker run (fallback)..."
|
||||||
|
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
|
||||||
|
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_TAG"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
log "Container recreated"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── 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
|
||||||
|
if [[ -d "$backup_dir/dns-providers" ]]; then
|
||||||
|
rm -rf "$api_source_dir/dns-providers"
|
||||||
|
cp -rf "$backup_dir/dns-providers" "$api_source_dir/dns-providers"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
local start_time
|
||||||
|
start_time=$(date +%s)
|
||||||
|
|
||||||
|
# 1. Read trigger
|
||||||
|
if [[ ! -f "$TRIGGER_FILE" ]]; then
|
||||||
|
log "No trigger file found — nothing to do"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Parse trigger.json (uses python3 which is available on all supported distros)
|
||||||
|
local action version from_version staging_dir api_source_dir commit
|
||||||
|
local frontend_staging_dir frontend_target_dir
|
||||||
|
action=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['action'])")
|
||||||
|
version=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['version'])")
|
||||||
|
from_version=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['fromVersion'])")
|
||||||
|
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'])")
|
||||||
|
commit=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('commit') 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 '')")
|
||||||
|
# Handle action=rollback (no new version to deploy)
|
||||||
|
local to_version="${version}"
|
||||||
|
|
||||||
|
log "=== ${action^^}: v${from_version} -> v${to_version} ==="
|
||||||
|
log "Staging: ${staging_dir}"
|
||||||
|
log "API source: ${api_source_dir}"
|
||||||
|
|
||||||
|
# Consume the trigger immediately so we don't re-process on failure
|
||||||
|
mv "$TRIGGER_FILE" "${TRIGGER_FILE}.processing"
|
||||||
|
|
||||||
|
# ── Handle rollback ────────────────────────────────────────────────────────
|
||||||
|
if [[ "$action" == "rollback" ]]; then
|
||||||
|
local backup_dir="${BACKUPS_DIR}/${version}"
|
||||||
|
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"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "Performing rollback to v${version}..."
|
||||||
|
rollback_restore "$backup_dir"
|
||||||
|
|
||||||
|
# Rebuild old code
|
||||||
|
log "Rebuilding container..."
|
||||||
|
build_image 2>&1 | tail -3 || true
|
||||||
|
|
||||||
|
restart_container
|
||||||
|
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}"
|
||||||
|
mkdir -p "$backup_dir"
|
||||||
|
log "Backing up current API files to ${backup_dir}"
|
||||||
|
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
|
||||||
|
done
|
||||||
|
[[ -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/dns-providers" ]] && cp -rf "$api_source_dir/dns-providers" "$backup_dir/"
|
||||||
|
|
||||||
|
# Backup data/ directory (services.json, config.json, credentials, etc.)
|
||||||
|
backup_data_dir "$backup_dir"
|
||||||
|
|
||||||
|
cleanup_old_backups
|
||||||
|
|
||||||
|
# 3. Copy new files from staging to API source
|
||||||
|
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
|
||||||
|
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
if [[ -d "$staging_dir/routes" ]]; then
|
||||||
|
rm -rf "$api_source_dir/routes"
|
||||||
|
cp -rf "$staging_dir/routes" "$api_source_dir/routes"
|
||||||
|
fi
|
||||||
|
if [[ -d "$staging_dir/src" ]]; then
|
||||||
|
rm -rf "$api_source_dir/src"
|
||||||
|
cp -rf "$staging_dir/src" "$api_source_dir/src"
|
||||||
|
fi
|
||||||
|
if [[ -d "$staging_dir/dns-providers" ]]; then
|
||||||
|
rm -rf "$api_source_dir/dns-providers"
|
||||||
|
cp -rf "$staging_dir/dns-providers" "$api_source_dir/dns-providers"
|
||||||
|
fi
|
||||||
|
if [[ -n "$commit" ]]; then
|
||||||
|
echo "$commit" > "$api_source_dir/VERSION"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3b. Sync frontend
|
||||||
|
if [[ -z "$frontend_staging_dir" ]]; then
|
||||||
|
parent_staging=$(dirname "$staging_dir")
|
||||||
|
[[ -d "$parent_staging/status" ]] && frontend_staging_dir="$parent_staging/status"
|
||||||
|
fi
|
||||||
|
if [[ -z "$frontend_target_dir" ]]; then
|
||||||
|
for candidate in /var/www/dashcaddy-status /etc/dashcaddy/sites/status; do
|
||||||
|
[[ -d "$candidate" ]] && frontend_target_dir="$candidate" && break
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [[ -n "$frontend_staging_dir" && -n "$frontend_target_dir" && -d "$frontend_staging_dir" ]]; then
|
||||||
|
log "Syncing frontend: $frontend_staging_dir -> $frontend_target_dir"
|
||||||
|
mkdir -p "$frontend_target_dir"
|
||||||
|
[[ -f "$frontend_staging_dir/index.html" ]] && cp -f "$frontend_staging_dir/index.html" "$frontend_target_dir/index.html"
|
||||||
|
[[ -f "$frontend_staging_dir/sw.js" ]] && cp -f "$frontend_staging_dir/sw.js" "$frontend_target_dir/sw.js"
|
||||||
|
for sub in dist css vendor js; do
|
||||||
|
if [[ -d "$frontend_staging_dir/$sub" ]]; then
|
||||||
|
mkdir -p "$frontend_target_dir/$sub"
|
||||||
|
cp -rf "$frontend_staging_dir/$sub/"* "$frontend_target_dir/$sub/" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [[ -d "$frontend_staging_dir/assets" ]]; then
|
||||||
|
mkdir -p "$frontend_target_dir/assets"
|
||||||
|
cp -rf "$frontend_staging_dir/assets/"* "$frontend_target_dir/assets/" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4. Rebuild container
|
||||||
|
log "Rebuilding container..."
|
||||||
|
local build_ok=false
|
||||||
|
if build_image; then
|
||||||
|
build_ok=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$build_ok" != "true" ]]; then
|
||||||
|
log "ERROR: Docker build failed — rolling back code + data"
|
||||||
|
code_restore "$backup_dir"
|
||||||
|
build_image 2>&1 | tail -3 || true
|
||||||
|
restart_container
|
||||||
|
wait_for_health || true
|
||||||
|
write_result "false" "$to_version" "$(( $(date +%s) - start_time ))" "Docker build failed"
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 5. Restart container (recreate so new code + env vars take effect)
|
||||||
|
restart_container
|
||||||
|
|
||||||
|
# 6. Health check
|
||||||
|
if wait_for_health; then
|
||||||
|
local duration=$(( $(date +%s) - start_time ))
|
||||||
|
log "=== Update successful: v${to_version} in ${duration}s ==="
|
||||||
|
write_result "true" "$to_version" "$duration"
|
||||||
|
else
|
||||||
|
local duration=$(( $(date +%s) - start_time ))
|
||||||
|
log "ERROR: Health check failed after update — rolling back code + data"
|
||||||
|
rollback_restore "$backup_dir"
|
||||||
|
build_image 2>&1 | tail -3 || true
|
||||||
|
restart_container
|
||||||
|
wait_for_health || log "WARNING: Rollback health check also failed"
|
||||||
|
write_result "false" "$to_version" "$duration" "Health check failed after update"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 7. Cleanup
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
rm -rf "${UPDATES_DIR}/staging" 2>/dev/null || true
|
||||||
|
|
||||||
|
log "=== Update process complete ==="
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
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
+11
-2
@@ -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>
|
||||||
@@ -390,8 +393,14 @@
|
|||||||
<!-- DNS Server Configuration -->
|
<!-- DNS Server Configuration -->
|
||||||
<div>
|
<div>
|
||||||
<label class="form-label-accent">
|
<label class="form-label-accent">
|
||||||
🗂️ DNS Server (Technitium)
|
🗂️ DNS Provider
|
||||||
</label>
|
</label>
|
||||||
|
<select id="setup-dns-provider" class="form-input-lg" style="margin-bottom: 12px;">
|
||||||
|
<option value="technitium">Technitium DNS (recommended)</option>
|
||||||
|
<option value="cloudflare">Cloudflare DNS</option>
|
||||||
|
<option value="rfc2136">RFC 2136 (BIND / PowerDNS / other)</option>
|
||||||
|
<option value="manual">Manual / External DNS</option>
|
||||||
|
</select>
|
||||||
<div style="display: grid; grid-template-columns: 1fr auto; gap: 8px;">
|
<div style="display: grid; grid-template-columns: 1fr auto; gap: 8px;">
|
||||||
<input type="text" id="setup-dns-ip" value="" placeholder="DNS server IP"
|
<input type="text" id="setup-dns-ip" value="" placeholder="DNS server IP"
|
||||||
style="padding: 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 1rem;" />
|
style="padding: 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 1rem;" />
|
||||||
@@ -406,7 +415,7 @@
|
|||||||
<!-- DNS Admin Token -->
|
<!-- DNS Admin Token -->
|
||||||
<div>
|
<div>
|
||||||
<label class="form-label-accent">
|
<label class="form-label-accent">
|
||||||
🔑 Technitium Admin Token
|
🔑 DNS Admin Token / API Key
|
||||||
</label>
|
</label>
|
||||||
<input type="password" id="setup-dns-token" placeholder="Paste your admin token here"
|
<input type="password" id="setup-dns-token" placeholder="Paste your admin token here"
|
||||||
class="form-input-lg" />
|
class="form-input-lg" />
|
||||||
|
|||||||
+439
-317
@@ -94,7 +94,9 @@
|
|||||||
<!-- Tab bar -->
|
<!-- Tab bar -->
|
||||||
<div class="panel-tabs">
|
<div class="panel-tabs">
|
||||||
<button class="panel-tab active" data-panel="backup-manual">Manual</button>
|
<button class="panel-tab active" data-panel="backup-manual">Manual</button>
|
||||||
<button class="panel-tab" data-panel="backup-automated">Automated</button>
|
<button class="panel-tab" data-panel="backup-schedules-tab">Schedules</button>
|
||||||
|
<button class="panel-tab" data-panel="backup-disk-tab">Backups on Disk</button>
|
||||||
|
<button class="panel-tab" data-panel="backup-pointintime-tab">Point-in-Time</button>
|
||||||
<button class="panel-tab" data-panel="backup-history-tab">History</button>
|
<button class="panel-tab" data-panel="backup-history-tab">History</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -143,12 +145,32 @@
|
|||||||
<div id="backup-result" style="display: none; margin-top: 16px; padding: 12px; border-radius: 8px;"></div>
|
<div id="backup-result" style="display: none; margin-top: 16px; padding: 12px; border-radius: 8px;"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Tab: Automated Backups -->
|
<!-- Tab: Schedules (Premium) -->
|
||||||
<div id="backup-automated" class="panel-section">
|
<div id="backup-schedules-tab" class="panel-section">
|
||||||
<div id="backup-schedule-container">
|
<div id="backup-schedules-container">
|
||||||
<div class="panel-empty">
|
<div class="panel-empty">
|
||||||
<span class="empty-icon">⏰</span>
|
<span class="empty-icon">⏰</span>
|
||||||
<span class="brand-spinner"></span> Loading backup schedule...
|
<span class="brand-spinner"></span> Loading schedules...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Backups on Disk -->
|
||||||
|
<div id="backup-disk-tab" class="panel-section">
|
||||||
|
<div id="backup-disk-container">
|
||||||
|
<div class="panel-empty">
|
||||||
|
<span class="empty-icon">💾</span>
|
||||||
|
<span class="brand-spinner"></span> Loading backup files...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Point-in-Time Restore -->
|
||||||
|
<div id="backup-pointintime-tab" class="panel-section">
|
||||||
|
<div id="pointintime-container">
|
||||||
|
<div class="panel-empty">
|
||||||
|
<span class="empty-icon">⏪</span>
|
||||||
|
<span class="brand-spinner"></span> Loading...
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -181,8 +203,10 @@
|
|||||||
var previewContent = document.getElementById('backup-preview-content');
|
var previewContent = document.getElementById('backup-preview-content');
|
||||||
var restoreBtn = document.getElementById('backup-do-restore-btn');
|
var restoreBtn = document.getElementById('backup-do-restore-btn');
|
||||||
var resultDiv = document.getElementById('backup-result');
|
var resultDiv = document.getElementById('backup-result');
|
||||||
var scheduleContainer = document.getElementById('backup-schedule-container');
|
var scheduleContainer = document.getElementById('backup-schedules-container');
|
||||||
var historyContainer = document.getElementById('backup-history-container');
|
var historyContainer = document.getElementById('backup-history-container');
|
||||||
|
var diskContainer = document.getElementById('backup-disk-container');
|
||||||
|
var pointintimeContainer = document.getElementById('pointintime-container');
|
||||||
|
|
||||||
var selectedBackup = null;
|
var selectedBackup = null;
|
||||||
|
|
||||||
@@ -383,357 +407,270 @@
|
|||||||
restoreBtn.innerHTML = '⚡ Restore Everything';
|
restoreBtn.innerHTML = '⚡ Restore Everything';
|
||||||
});
|
});
|
||||||
|
|
||||||
// === Automated Backups Tab ===
|
// === Schedules Tab (Premium) ===
|
||||||
// Holds the destination currently being edited in the form
|
async function loadSchedulesTab() {
|
||||||
var currentDestination = { type: 'local' };
|
|
||||||
|
|
||||||
async function loadBackupSchedule() {
|
|
||||||
if (!scheduleContainer) return;
|
if (!scheduleContainer) return;
|
||||||
|
scheduleContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';
|
||||||
try {
|
try {
|
||||||
var res = await fetch('/api/v1/backups/config');
|
var res = await fetch('/api/v1/backups/schedule');
|
||||||
var data = await res.json();
|
var data = await res.json();
|
||||||
if (!data.success) throw new Error(data.error || 'Failed to load config');
|
|
||||||
var cfg = data.config?.backups || {};
|
|
||||||
var autoKey = Object.keys(cfg)[0];
|
|
||||||
var auto = autoKey ? cfg[autoKey] : null;
|
|
||||||
|
|
||||||
// Pull existing destination (first one) — fall back to local
|
if (data.premiumRequired) {
|
||||||
var existingDest = (auto?.destinations && auto.destinations[0]) || { type: 'local' };
|
scheduleContainer.innerHTML = '<div class="panel-empty" style="padding: 24px; text-align: center;">' +
|
||||||
currentDestination = JSON.parse(JSON.stringify(existingDest));
|
'<div style="font-size: 2rem; margin-bottom: 12px;">⭐</div>' +
|
||||||
|
'<div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div>' +
|
||||||
var html = '<div style="padding: 16px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 10px; border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent); margin-bottom: 16px;">';
|
'<div style="font-size: 0.85rem; color: var(--muted);">Auto-backup scheduling requires a DashCaddy Premium subscription.</div>' +
|
||||||
html += '<h4 style="margin: 0 0 12px; color: var(--accent); font-size: 0.9rem;">⏰ Backup Schedule</h4>';
|
'<button onclick="showNotification(\'Upgrade to Premium to enable auto-backups!\', \'info\'); scrollToSection(\'license\');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
|
||||||
html += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">';
|
'</div>';
|
||||||
html += '<div><label style="font-size: 0.8rem; color: var(--muted);">Schedule:</label>';
|
|
||||||
html += ' <select id="backup-schedule-select" style="width: 100%;">';
|
|
||||||
html += ' <option value="disabled"' + (!auto?.enabled ? ' selected' : '') + '>Disabled</option>';
|
|
||||||
html += ' <option value="hourly"' + (auto?.schedule === 'hourly' ? ' selected' : '') + '>Hourly</option>';
|
|
||||||
html += ' <option value="daily"' + (auto?.schedule === 'daily' ? ' selected' : '') + '>Daily</option>';
|
|
||||||
html += ' <option value="weekly"' + (auto?.schedule === 'weekly' ? ' selected' : '') + '>Weekly</option>';
|
|
||||||
html += ' <option value="monthly"' + (auto?.schedule === 'monthly' ? ' selected' : '') + '>Monthly</option>';
|
|
||||||
html += ' </select></div>';
|
|
||||||
html += '<div><label style="font-size: 0.8rem; color: var(--muted);">Keep last:</label>';
|
|
||||||
html += ' <select id="backup-retention-select" style="width: 100%;">';
|
|
||||||
html += ' <option value="3"' + (auto?.retention?.keep === 3 ? ' selected' : '') + '>3 backups</option>';
|
|
||||||
html += ' <option value="5"' + (!auto?.retention || auto?.retention?.keep === 5 ? ' selected' : '') + '>5 backups</option>';
|
|
||||||
html += ' <option value="10"' + (auto?.retention?.keep === 10 ? ' selected' : '') + '>10 backups</option>';
|
|
||||||
html += ' <option value="30"' + (auto?.retention?.keep === 30 ? ' selected' : '') + '>30 backups</option>';
|
|
||||||
html += ' </select></div>';
|
|
||||||
html += '</div>';
|
|
||||||
html += '<div style="margin-top: 12px;">';
|
|
||||||
html += ' <label style="display: flex; align-items: center; gap: 8px; font-size: 0.85rem; cursor: pointer;">';
|
|
||||||
html += ' <input type="checkbox" id="backup-encrypt-toggle"' + (auto?.encrypt !== false ? ' checked' : '') + ' />';
|
|
||||||
html += ' Encrypt backups';
|
|
||||||
html += ' </label></div>';
|
|
||||||
html += '<div style="display: flex; gap: 8px; margin-top: 12px;">';
|
|
||||||
html += ' <button id="backup-save-schedule" style="padding: 8px 16px; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 6px; cursor: pointer; font-weight: 500;">Save Schedule</button>';
|
|
||||||
html += ' <button id="backup-run-now" style="padding: 8px 16px; border-radius: 6px; cursor: pointer;">▶️ Run Backup Now</button>';
|
|
||||||
html += '</div>';
|
|
||||||
html += '</div>';
|
|
||||||
|
|
||||||
// === Destination Section ===
|
|
||||||
html += '<div style="padding: 16px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 10px; border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent); margin-bottom: 16px;">';
|
|
||||||
html += '<h4 style="margin: 0 0 12px; color: var(--accent); font-size: 0.9rem;">☁️ Backup Destination</h4>';
|
|
||||||
html += '<div><label style="font-size: 0.8rem; color: var(--muted);">Where to store backups:</label>';
|
|
||||||
html += ' <select id="backup-dest-type" style="width: 100%;">';
|
|
||||||
html += ' <option value="local"' + (currentDestination.type === 'local' ? ' selected' : '') + '>💾 Local disk</option>';
|
|
||||||
html += ' <option value="dropbox"' + (currentDestination.type === 'dropbox' ? ' selected' : '') + '>📦 Dropbox</option>';
|
|
||||||
html += ' <option value="webdav"' + (currentDestination.type === 'webdav' ? ' selected' : '') + '>🌐 WebDAV (Nextcloud / ownCloud)</option>';
|
|
||||||
html += ' <option value="sftp"' + (currentDestination.type === 'sftp' ? ' selected' : '') + '>🔐 SFTP</option>';
|
|
||||||
html += ' </select></div>';
|
|
||||||
html += '<div id="backup-dest-form" style="margin-top: 12px;"></div>';
|
|
||||||
html += '<div id="backup-dest-result" style="display: none; margin-top: 10px; padding: 8px 10px; border-radius: 6px; font-size: 0.8rem;"></div>';
|
|
||||||
html += '</div>';
|
|
||||||
|
|
||||||
html += '<div id="backup-schedule-result" style="display: none; margin-top: 12px; padding: 10px; border-radius: 8px; font-size: 0.85rem;"></div>';
|
|
||||||
scheduleContainer.innerHTML = html;
|
|
||||||
|
|
||||||
document.getElementById('backup-save-schedule')?.addEventListener('click', saveSchedule);
|
|
||||||
document.getElementById('backup-run-now')?.addEventListener('click', runBackupNow);
|
|
||||||
|
|
||||||
var destTypeSel = document.getElementById('backup-dest-type');
|
|
||||||
destTypeSel?.addEventListener('change', function() {
|
|
||||||
currentDestination = { type: destTypeSel.value };
|
|
||||||
renderDestinationForm(destTypeSel.value);
|
|
||||||
});
|
|
||||||
renderDestinationForm(currentDestination.type);
|
|
||||||
} catch (e) {
|
|
||||||
scheduleContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed to load schedule: ' + escapeHtml(e.message) + '</div>';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Render the provider-specific form fields and load saved credentials (masked)
|
|
||||||
async function renderDestinationForm(type) {
|
|
||||||
var formEl = document.getElementById('backup-dest-form');
|
|
||||||
if (!formEl) return;
|
|
||||||
|
|
||||||
if (type === 'local') {
|
|
||||||
formEl.innerHTML = '<div style="font-size: 0.8rem; color: var(--muted); padding: 8px;">Backups are stored on the host filesystem. No additional configuration required.</div>';
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var html = '';
|
if (!data.success) throw new Error(data.error || 'Failed to load schedules');
|
||||||
|
|
||||||
if (type === 'dropbox') {
|
var schedules = data.schedules || [];
|
||||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Access Token:</label>';
|
|
||||||
html += '<input type="password" id="dest-dropbox-token" placeholder="sl.B..." style="width: 100%; margin-bottom: 8px;" />';
|
if (schedules.length === 0) {
|
||||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Folder path:</label>';
|
scheduleContainer.innerHTML = '<div class="panel-empty">' +
|
||||||
html += '<input type="text" id="dest-dropbox-path" placeholder="/dashcaddy-backups" value="' + escapeHtml(currentDestination.path || '/dashcaddy-backups') + '" style="width: 100%; margin-bottom: 8px;" />';
|
'<span class="empty-icon">⏰</span>' +
|
||||||
html += '<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 8px;">Generate a token at <a href="https://www.dropbox.com/developers/apps" target="_blank" style="color: var(--accent);">Dropbox App Console</a> with files.content.write + files.content.read scopes.</div>';
|
'<div>No backup schedules configured</div>' +
|
||||||
} else if (type === 'webdav') {
|
'<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Select apps below to enable auto-backup</div>' +
|
||||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Server URL:</label>';
|
'</div>';
|
||||||
html += '<input type="text" id="dest-webdav-url" placeholder="https://cloud.example.com/remote.php/dav/files/username" style="width: 100%; margin-bottom: 8px;" />';
|
return;
|
||||||
html += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">';
|
|
||||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Username:</label>';
|
|
||||||
html += ' <input type="text" id="dest-webdav-username" style="width: 100%;" /></div>';
|
|
||||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Password / App password:</label>';
|
|
||||||
html += ' <input type="password" id="dest-webdav-password" style="width: 100%;" /></div>';
|
|
||||||
html += '</div>';
|
|
||||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Folder path:</label>';
|
|
||||||
html += '<input type="text" id="dest-webdav-path" placeholder="/dashcaddy-backups" value="' + escapeHtml(currentDestination.path || '/dashcaddy-backups') + '" style="width: 100%; margin-bottom: 8px;" />';
|
|
||||||
} else if (type === 'sftp') {
|
|
||||||
html += '<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px; margin-bottom: 8px;">';
|
|
||||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Host:</label>';
|
|
||||||
html += ' <input type="text" id="dest-sftp-host" placeholder="backup.example.com" style="width: 100%;" /></div>';
|
|
||||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Port:</label>';
|
|
||||||
html += ' <input type="number" id="dest-sftp-port" value="22" style="width: 100%;" /></div>';
|
|
||||||
html += '</div>';
|
|
||||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Username:</label>';
|
|
||||||
html += '<input type="text" id="dest-sftp-username" style="width: 100%; margin-bottom: 8px;" />';
|
|
||||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Auth method:</label>';
|
|
||||||
html += '<select id="dest-sftp-authtype" style="width: 100%; margin-bottom: 8px;">';
|
|
||||||
html += ' <option value="password">Password</option>';
|
|
||||||
html += ' <option value="key">Private key</option>';
|
|
||||||
html += '</select>';
|
|
||||||
html += '<div id="dest-sftp-password-row"><label style="font-size: 0.8rem; color: var(--muted);">Password:</label>';
|
|
||||||
html += ' <input type="password" id="dest-sftp-password" style="width: 100%; margin-bottom: 8px;" /></div>';
|
|
||||||
html += '<div id="dest-sftp-key-row" style="display: none;"><label style="font-size: 0.8rem; color: var(--muted);">Private key (PEM):</label>';
|
|
||||||
html += ' <textarea id="dest-sftp-privatekey" rows="4" style="width: 100%; font-family: monospace; font-size: 0.75rem; margin-bottom: 8px;" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"></textarea></div>';
|
|
||||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Remote path:</label>';
|
|
||||||
html += '<input type="text" id="dest-sftp-path" placeholder="/home/user/dashcaddy-backups" value="' + escapeHtml(currentDestination.path || '/home/user/dashcaddy-backups') + '" style="width: 100%; margin-bottom: 8px;" />';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
html += '<div style="display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap;">';
|
var html = '<div style="display: flex; flex-direction: column; gap: 8px;">';
|
||||||
html += ' <button id="dest-save-creds" style="padding: 6px 12px; font-size: 0.8rem; border-radius: 6px; cursor: pointer;">💾 Save Credentials</button>';
|
for (var i = 0; i < schedules.length; i++) {
|
||||||
html += ' <button id="dest-test-conn" style="padding: 6px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 6px; cursor: pointer;">🔌 Test Connection</button>';
|
var sch = schedules[i];
|
||||||
html += ' <button id="dest-clear-creds" style="padding: 6px 12px; font-size: 0.8rem; border-radius: 6px; cursor: pointer; color: var(--bad-fg);">🗑️ Clear</button>';
|
var nextRunStr = sch.nextRun ? new Date(sch.nextRun).toLocaleString() : 'Not scheduled';
|
||||||
|
var lastRunStr = sch.lastRun ? new Date(sch.lastRun).toLocaleString() : 'Never';
|
||||||
|
|
||||||
|
html += '<div style="padding: 12px 14px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">' +
|
||||||
|
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">' +
|
||||||
|
' <div style="font-weight: 600; font-size: 0.9rem;">' + escapeHtml(sch.appId) + '</div>' +
|
||||||
|
' <label class="toggle-switch" style="display: flex; align-items: center; gap: 6px;">' +
|
||||||
|
' <input type="checkbox" class="schedule-toggle" data-appid="' + escapeHtml(sch.appId) + '"' + (sch.enabled ? ' checked' : '') + ' />' +
|
||||||
|
' <span style="font-size: 0.75rem; color: var(--muted);">' + (sch.enabled ? 'ON' : 'OFF') + '</span>' +
|
||||||
|
' </label>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.8rem; margin-bottom: 10px;">' +
|
||||||
|
' <div><span style="color: var(--muted);">Schedule:</span> <select class="schedule-select" data-appid="' + escapeHtml(sch.appId) + '" style="background: var(--base); border: 1px solid var(--border); border-radius: 4px; padding: 2px 6px;">' +
|
||||||
|
' <option value="hourly"' + (sch.schedule === 'hourly' ? ' selected' : '') + '>Hourly</option>' +
|
||||||
|
' <option value="daily"' + (sch.schedule === 'daily' ? ' selected' : '') + '>Daily</option>' +
|
||||||
|
' <option value="weekly"' + (sch.schedule === 'weekly' ? ' selected' : '') + '>Weekly</option>' +
|
||||||
|
' <option value="monthly"' + (sch.schedule === 'monthly' ? ' selected' : '') + '>Monthly</option>' +
|
||||||
|
' </select></div>' +
|
||||||
|
' <div><span style="color: var(--muted);">Keep last:</span> <input type="number" class="retention-input" data-appid="' + escapeHtml(sch.appId) + '" value="' + (sch.retention?.keep || 7) + '" min="1" max="100" style="width: 50px; background: var(--base); border: 1px solid var(--border); border-radius: 4px; padding: 2px 6px;" /></div>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 10px;">' +
|
||||||
|
' <div>Next run: ' + escapeHtml(nextRunStr) + '</div>' +
|
||||||
|
' <div>Last run: ' + escapeHtml(lastRunStr) + '</div>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div style="display: flex; gap: 6px;">' +
|
||||||
|
' <button class="schedule-run-now" data-appid="' + escapeHtml(sch.appId) + '" style="padding: 5px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--ok-fg) 20%, transparent); border: 1px solid var(--ok-fg); color: var(--ok-fg); border-radius: 6px; cursor: pointer;">▶️ Run Now</button>' +
|
||||||
|
' <button class="schedule-delete" data-appid="' + escapeHtml(sch.appId) + '" style="padding: 5px 12px; font-size: 0.8rem; background: transparent; border: 1px solid var(--bad-fg); color: var(--bad-fg); border-radius: 6px; cursor: pointer;">🗑️ Remove</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
}
|
||||||
html += '</div>';
|
html += '</div>';
|
||||||
|
|
||||||
formEl.innerHTML = html;
|
// Add "Add Schedule" section at bottom
|
||||||
|
html += '<div style="margin-top: 16px; padding: 16px; background: color-mix(in srgb, var(--accent) 5%, transparent); border-radius: 10px; border: 1px dashed var(--border);">' +
|
||||||
|
'<h4 style="margin: 0 0 12px; font-size: 0.85rem; color: var(--muted);">➕ Add New Schedule</h4>' +
|
||||||
|
'<div style="display: flex; gap: 8px; flex-wrap: wrap;">' +
|
||||||
|
' <input type="text" id="new-schedule-appid" placeholder="App ID (e.g., plex, sonarr)" style="flex: 1; min-width: 150px; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);" />' +
|
||||||
|
' <select id="new-schedule-interval" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);">' +
|
||||||
|
' <option value="hourly">Hourly</option>' +
|
||||||
|
' <option value="daily" selected>Daily</option>' +
|
||||||
|
' <option value="weekly">Weekly</option>' +
|
||||||
|
' <option value="monthly">Monthly</option>' +
|
||||||
|
' <option value="6h">Every 6 hours</option>' +
|
||||||
|
' <option value="30m">Every 30 minutes</option>' +
|
||||||
|
' </select>' +
|
||||||
|
' <input type="number" id="new-schedule-retention" value="7" min="1" max="100" placeholder="Keep" style="width: 70px; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);" />' +
|
||||||
|
' <button id="add-schedule-btn" style="padding: 8px 16px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Add Schedule</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
|
||||||
// SFTP auth type toggle
|
scheduleContainer.innerHTML = html;
|
||||||
if (type === 'sftp') {
|
|
||||||
var authSel = document.getElementById('dest-sftp-authtype');
|
// Wire up event listeners
|
||||||
var pwRow = document.getElementById('dest-sftp-password-row');
|
scheduleContainer.querySelectorAll('.schedule-toggle').forEach(function(toggle) {
|
||||||
var keyRow = document.getElementById('dest-sftp-key-row');
|
toggle.addEventListener('change', function() { updateSchedule(toggle.dataset.appid, { enabled: toggle.checked }); });
|
||||||
authSel?.addEventListener('change', function() {
|
|
||||||
if (authSel.value === 'key') { pwRow.style.display = 'none'; keyRow.style.display = ''; }
|
|
||||||
else { pwRow.style.display = ''; keyRow.style.display = 'none'; }
|
|
||||||
});
|
});
|
||||||
}
|
scheduleContainer.querySelectorAll('.schedule-select').forEach(function(sel) {
|
||||||
|
sel.addEventListener('change', function() { updateSchedule(sel.dataset.appid, { schedule: sel.value }); });
|
||||||
document.getElementById('dest-save-creds')?.addEventListener('click', function() { saveCredentials(type); });
|
|
||||||
document.getElementById('dest-test-conn')?.addEventListener('click', function() { testDestination(type); });
|
|
||||||
document.getElementById('dest-clear-creds')?.addEventListener('click', function() { clearCredentials(type); });
|
|
||||||
|
|
||||||
// Pull existing (masked) credentials
|
|
||||||
await loadCredentials(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
function destResult(msg, ok) {
|
|
||||||
var el = document.getElementById('backup-dest-result');
|
|
||||||
if (!el) return;
|
|
||||||
el.innerHTML = msg;
|
|
||||||
el.style.display = 'block';
|
|
||||||
el.style.background = ok ? 'color-mix(in srgb, var(--ok-fg) 15%, transparent)' : 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
|
||||||
el.style.border = ok ? '1px solid var(--ok-fg)' : '1px solid var(--bad-fg)';
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadCredentials(provider) {
|
|
||||||
try {
|
|
||||||
var res = await fetch('/api/v1/backups/credentials/' + provider);
|
|
||||||
var data = await res.json();
|
|
||||||
if (!data.success || !data.credentials) return;
|
|
||||||
var c = data.credentials;
|
|
||||||
if (provider === 'dropbox') {
|
|
||||||
var t = document.getElementById('dest-dropbox-token'); if (t && c.token) t.value = c.token;
|
|
||||||
} else if (provider === 'webdav') {
|
|
||||||
var u = document.getElementById('dest-webdav-url'); if (u && c.url) u.value = c.url;
|
|
||||||
var n = document.getElementById('dest-webdav-username'); if (n && c.username) n.value = c.username;
|
|
||||||
var p = document.getElementById('dest-webdav-password'); if (p && c.password) p.value = c.password;
|
|
||||||
} else if (provider === 'sftp') {
|
|
||||||
var h = document.getElementById('dest-sftp-host'); if (h && c.host) h.value = c.host;
|
|
||||||
var po = document.getElementById('dest-sftp-port'); if (po && c.port) po.value = c.port;
|
|
||||||
var un = document.getElementById('dest-sftp-username'); if (un && c.username) un.value = c.username;
|
|
||||||
var pw = document.getElementById('dest-sftp-password'); if (pw && c.password) pw.value = c.password;
|
|
||||||
var pk = document.getElementById('dest-sftp-privatekey'); if (pk && c.privateKey) pk.value = c.privateKey;
|
|
||||||
if (c.privateKey) {
|
|
||||||
var sel = document.getElementById('dest-sftp-authtype');
|
|
||||||
if (sel) { sel.value = 'key'; sel.dispatchEvent(new Event('change')); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) { /* no creds yet — silent */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
function collectCredentials(provider) {
|
|
||||||
if (provider === 'dropbox') {
|
|
||||||
return { token: document.getElementById('dest-dropbox-token')?.value };
|
|
||||||
}
|
|
||||||
if (provider === 'webdav') {
|
|
||||||
return {
|
|
||||||
url: document.getElementById('dest-webdav-url')?.value,
|
|
||||||
username: document.getElementById('dest-webdav-username')?.value,
|
|
||||||
password: document.getElementById('dest-webdav-password')?.value
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (provider === 'sftp') {
|
|
||||||
var auth = document.getElementById('dest-sftp-authtype')?.value;
|
|
||||||
var creds = {
|
|
||||||
host: document.getElementById('dest-sftp-host')?.value,
|
|
||||||
port: parseInt(document.getElementById('dest-sftp-port')?.value) || 22,
|
|
||||||
username: document.getElementById('dest-sftp-username')?.value
|
|
||||||
};
|
|
||||||
if (auth === 'key') creds.privateKey = document.getElementById('dest-sftp-privatekey')?.value;
|
|
||||||
else creds.password = document.getElementById('dest-sftp-password')?.value;
|
|
||||||
return creds;
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function saveCredentials(provider) {
|
|
||||||
try {
|
|
||||||
var creds = collectCredentials(provider);
|
|
||||||
var res = await secureFetch('/api/v1/backups/credentials/' + provider, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify(creds)
|
|
||||||
});
|
});
|
||||||
var data = await res.json();
|
scheduleContainer.querySelectorAll('.retention-input').forEach(function(inp) {
|
||||||
destResult(data.success ? '✅ Credentials saved' : '⚠️ ' + escapeHtml(data.error || 'Failed'), data.success);
|
inp.addEventListener('change', function() { updateSchedule(inp.dataset.appid, { retention: { keep: parseInt(inp.value) || 7 } }); });
|
||||||
|
});
|
||||||
|
scheduleContainer.querySelectorAll('.schedule-run-now').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() { runBackupNow(btn.dataset.appid); });
|
||||||
|
});
|
||||||
|
scheduleContainer.querySelectorAll('.schedule-delete').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() { deleteSchedule(btn.dataset.appid); });
|
||||||
|
});
|
||||||
|
document.getElementById('add-schedule-btn')?.addEventListener('click', addNewSchedule);
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
destResult('❌ ' + escapeHtml(e.message), false);
|
scheduleContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed to load: ' + escapeHtml(e.message) + '</div>';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function clearCredentials(provider) {
|
async function updateSchedule(appId, updates) {
|
||||||
if (!confirm('Delete saved ' + provider + ' credentials?')) return;
|
|
||||||
try {
|
try {
|
||||||
var res = await secureFetch('/api/v1/backups/credentials/' + provider, { method: 'DELETE' });
|
var res = await secureFetch('/api/v1/backups/schedule', {
|
||||||
var data = await res.json();
|
|
||||||
if (data.success) {
|
|
||||||
destResult('✅ Credentials cleared', true);
|
|
||||||
renderDestinationForm(provider);
|
|
||||||
} else {
|
|
||||||
destResult('⚠️ ' + escapeHtml(data.error || 'Failed'), false);
|
|
||||||
}
|
|
||||||
} catch (e) { destResult('❌ ' + escapeHtml(e.message), false); }
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildDestination(type) {
|
|
||||||
var dest = { type: type };
|
|
||||||
if (type === 'local') return dest;
|
|
||||||
if (type === 'dropbox') dest.path = document.getElementById('dest-dropbox-path')?.value || '/dashcaddy-backups';
|
|
||||||
else if (type === 'webdav') dest.path = document.getElementById('dest-webdav-path')?.value || '/dashcaddy-backups';
|
|
||||||
else if (type === 'sftp') dest.path = document.getElementById('dest-sftp-path')?.value || '/dashcaddy-backups';
|
|
||||||
return dest;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function testDestination(type) {
|
|
||||||
destResult('<span class="brand-spinner"></span> Testing connection...', true);
|
|
||||||
try {
|
|
||||||
var dest = buildDestination(type);
|
|
||||||
var res = await secureFetch('/api/v1/backups/test-destination', {
|
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(dest)
|
body: JSON.stringify({ appId, ...updates })
|
||||||
});
|
});
|
||||||
var data = await res.json();
|
var data = await res.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
var ms = data.elapsedMs ? ' (' + data.elapsedMs + 'ms)' : '';
|
showNotification('Schedule updated for ' + appId, 'success');
|
||||||
destResult('✅ Connection OK' + ms + ' — write/read/delete probe succeeded', true);
|
|
||||||
} else {
|
} else {
|
||||||
destResult('❌ ' + escapeHtml(data.error || 'Connection failed'), false);
|
showNotification('Update failed: ' + (data.error || 'Unknown'), 'error');
|
||||||
}
|
loadSchedulesTab(); // Refresh on failure
|
||||||
} catch (e) { destResult('❌ ' + escapeHtml(e.message), false); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function saveSchedule() {
|
|
||||||
var schedule = document.getElementById('backup-schedule-select')?.value;
|
|
||||||
var retention = parseInt(document.getElementById('backup-retention-select')?.value) || 5;
|
|
||||||
var encrypt = document.getElementById('backup-encrypt-toggle')?.checked ?? true;
|
|
||||||
var destType = document.getElementById('backup-dest-type')?.value || 'local';
|
|
||||||
var resultEl = document.getElementById('backup-schedule-result');
|
|
||||||
try {
|
|
||||||
var res = await secureFetch('/api/v1/backups/config', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({
|
|
||||||
backups: {
|
|
||||||
auto: {
|
|
||||||
enabled: schedule !== 'disabled',
|
|
||||||
schedule: schedule === 'disabled' ? 'daily' : schedule,
|
|
||||||
include: ['all'],
|
|
||||||
encrypt: encrypt,
|
|
||||||
verify: true,
|
|
||||||
retention: { keep: retention },
|
|
||||||
destinations: [buildDestination(destType)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
|
||||||
var data = await res.json();
|
|
||||||
if (resultEl) {
|
|
||||||
resultEl.innerHTML = data.success ? '✅ Schedule saved' : '⚠️ ' + escapeHtml(data.error);
|
|
||||||
resultEl.style.display = 'block';
|
|
||||||
resultEl.style.background = data.success ? 'color-mix(in srgb, var(--ok-fg) 15%, transparent)' : 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
|
||||||
resultEl.style.border = data.success ? '1px solid var(--ok-fg)' : '1px solid var(--bad-fg)';
|
|
||||||
setTimeout(function() { if (resultEl) resultEl.style.display = 'none'; }, 3000);
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (resultEl) {
|
showNotification('Error: ' + e.message, 'error');
|
||||||
resultEl.innerHTML = '❌ ' + escapeHtml(e.message);
|
|
||||||
resultEl.style.display = 'block';
|
|
||||||
resultEl.style.background = 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
|
||||||
resultEl.style.border = '1px solid var(--bad-fg)';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runBackupNow() {
|
async function runBackupNow(appId) {
|
||||||
var btn = document.getElementById('backup-run-now');
|
|
||||||
var resultEl = document.getElementById('backup-schedule-result');
|
|
||||||
var destType = document.getElementById('backup-dest-type')?.value || 'local';
|
|
||||||
if (btn) { btn.disabled = true; btn.innerHTML = '<span class="brand-spinner"></span> Running...'; }
|
|
||||||
try {
|
try {
|
||||||
var res = await secureFetch('/api/v1/backups/execute', {
|
var res = await secureFetch('/api/v1/backups/backup/' + encodeURIComponent(appId), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' }
|
||||||
body: JSON.stringify({ include: ['all'], destinations: [buildDestination(destType)] })
|
|
||||||
});
|
});
|
||||||
var data = await res.json();
|
var data = await res.json();
|
||||||
if (resultEl) {
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
var sizeMB = data.backup?.size ? (data.backup.size / 1024 / 1024).toFixed(2) : '?';
|
showNotification('Backup started for ' + appId + '!', 'success');
|
||||||
resultEl.innerHTML = '✅ Backup complete (' + sizeMB + ' MB)';
|
|
||||||
resultEl.style.background = 'color-mix(in srgb, var(--ok-fg) 15%, transparent)';
|
|
||||||
resultEl.style.border = '1px solid var(--ok-fg)';
|
|
||||||
} else {
|
} else {
|
||||||
resultEl.innerHTML = '⚠️ ' + escapeHtml(data.error);
|
showNotification('Backup failed: ' + (data.error || 'Unknown'), 'error');
|
||||||
resultEl.style.background = 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
|
||||||
resultEl.style.border = '1px solid var(--bad-fg)';
|
|
||||||
}
|
}
|
||||||
resultEl.style.display = 'block';
|
|
||||||
}
|
|
||||||
loadBackupHistory();
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (resultEl) {
|
showNotification('Error: ' + e.message, 'error');
|
||||||
resultEl.innerHTML = '❌ ' + escapeHtml(e.message);
|
|
||||||
resultEl.style.display = 'block';
|
|
||||||
resultEl.style.background = 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
|
||||||
resultEl.style.border = '1px solid var(--bad-fg)';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (btn) { btn.disabled = false; btn.innerHTML = '▶️ Run Backup Now'; }
|
|
||||||
|
async function deleteSchedule(appId) {
|
||||||
|
if (!confirm('Remove backup schedule for ' + appId + '?')) return;
|
||||||
|
try {
|
||||||
|
var res = await secureFetch('/api/v1/backups/schedule/' + encodeURIComponent(appId), { method: 'DELETE' });
|
||||||
|
var data = await res.json();
|
||||||
|
if (data.success) {
|
||||||
|
showNotification('Schedule removed for ' + appId, 'success');
|
||||||
|
loadSchedulesTab();
|
||||||
|
} else {
|
||||||
|
showNotification('Delete failed: ' + (data.error || 'Unknown'), 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showNotification('Error: ' + e.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addNewSchedule() {
|
||||||
|
var appId = document.getElementById('new-schedule-appid')?.value?.trim();
|
||||||
|
var interval = document.getElementById('new-schedule-interval')?.value || 'daily';
|
||||||
|
var retention = parseInt(document.getElementById('new-schedule-retention')?.value) || 7;
|
||||||
|
|
||||||
|
if (!appId) {
|
||||||
|
showNotification('Please enter an App ID', 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
var res = await secureFetch('/api/v1/backups/schedule', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ appId, schedule: interval, retention: { keep: retention }, enabled: true })
|
||||||
|
});
|
||||||
|
var data = await res.json();
|
||||||
|
if (data.success) {
|
||||||
|
showNotification('Schedule created for ' + appId, 'success');
|
||||||
|
loadSchedulesTab();
|
||||||
|
// Clear inputs
|
||||||
|
var appIdInput = document.getElementById('new-schedule-appid');
|
||||||
|
if (appIdInput) appIdInput.value = '';
|
||||||
|
} else {
|
||||||
|
showNotification('Failed: ' + (data.error || 'Unknown'), 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showNotification('Error: ' + e.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Backups on Disk Tab ===
|
||||||
|
async function loadDiskBackups() {
|
||||||
|
if (!diskContainer) return;
|
||||||
|
diskContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';
|
||||||
|
try {
|
||||||
|
var res = await fetch('/api/v1/backups/files');
|
||||||
|
var data = await res.json();
|
||||||
|
if (!data.success) throw new Error(data.error || 'Failed to load');
|
||||||
|
|
||||||
|
var files = data.files || [];
|
||||||
|
|
||||||
|
if (files.length === 0) {
|
||||||
|
diskContainer.innerHTML = '<div class="panel-empty">' +
|
||||||
|
'<span class="empty-icon">💾</span>' +
|
||||||
|
'<div>No backup files on disk</div>' +
|
||||||
|
'<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Run a backup to create backup files</div>' +
|
||||||
|
'</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group by appId
|
||||||
|
var byApp = {};
|
||||||
|
for (var i = 0; i < files.length; i++) {
|
||||||
|
var f = files[i];
|
||||||
|
var appId = f.appId || 'unknown';
|
||||||
|
if (!byApp[appId]) byApp[appId] = [];
|
||||||
|
byApp[appId].push(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
var html = '<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 12px;">' + files.length + ' backup file(s) across ' + Object.keys(byApp).length + ' app(s)</div>';
|
||||||
|
html += '<div style="display: flex; flex-direction: column; gap: 12px;">';
|
||||||
|
|
||||||
|
var appIds = Object.keys(byApp).sort();
|
||||||
|
for (var a = 0; a < appIds.length; a++) {
|
||||||
|
var appId = appIds[a];
|
||||||
|
var appFiles = byApp[appId];
|
||||||
|
html += '<div style="background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); overflow: hidden;">' +
|
||||||
|
'<div style="padding: 8px 12px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-bottom: 1px solid var(--border); font-weight: 600; font-size: 0.85rem;">' +
|
||||||
|
escapeHtml(appId) + ' <span style="font-weight: normal; color: var(--muted); font-size: 0.75rem;">(' + appFiles.length + ' backup(s))</span>' +
|
||||||
|
'</div>';
|
||||||
|
|
||||||
|
for (var j = 0; j < appFiles.length; j++) {
|
||||||
|
var f = appFiles[j];
|
||||||
|
var dateStr = new Date(f.timestamp).toLocaleString();
|
||||||
|
html += '<div style="padding: 10px 12px; border-bottom: 1px solid var(--border);">' +
|
||||||
|
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">' +
|
||||||
|
' <div style="font-weight: 500; font-size: 0.85rem;">' + escapeHtml(f.name) + '</div>' +
|
||||||
|
' <div style="font-size: 0.75rem; color: var(--muted);">' + f.sizeFormatted + '</div>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">' + dateStr + '</div>' +
|
||||||
|
'<div style="display: flex; gap: 6px;">' +
|
||||||
|
' <button class="disk-compare-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 3px 8px; font-size: 0.75rem; background: transparent; border: 1px solid var(--accent); color: var(--accent); border-radius: 5px; cursor: pointer;">Compare</button>' +
|
||||||
|
' <button class="disk-restore-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 3px 8px; font-size: 0.75rem; background: linear-gradient(135deg, var(--ok-fg), #27ae60); border: none; color: white; border-radius: 5px; cursor: pointer; font-weight: 500;">Restore</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
|
||||||
|
diskContainer.innerHTML = html;
|
||||||
|
|
||||||
|
// Wire up buttons
|
||||||
|
diskContainer.querySelectorAll('.disk-compare-btn').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() { compareBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||||
|
});
|
||||||
|
diskContainer.querySelectorAll('.disk-restore-btn').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() { restoreBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
diskContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed: ' + escapeHtml(e.message) + '</div>';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// === Backup History Tab ===
|
// === Backup History Tab ===
|
||||||
@@ -794,6 +731,191 @@
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Lazy-load tabs
|
// Lazy-load tabs
|
||||||
document.querySelector('[data-panel="backup-automated"]')?.addEventListener('click', loadBackupSchedule);
|
document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener('click', loadSchedulesTab);
|
||||||
|
document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener('click', loadDiskBackups);
|
||||||
|
document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener('click', loadPointInTimeTab);
|
||||||
document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener('click', loadBackupHistory);
|
document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener('click', loadBackupHistory);
|
||||||
|
|
||||||
|
// ===== Point-in-Time Restore Tab =====
|
||||||
|
async function loadPointInTimeTab() {
|
||||||
|
if (!pointintimeContainer) return;
|
||||||
|
|
||||||
|
// Check premium
|
||||||
|
try {
|
||||||
|
var licenseRes = await fetch('/api/v1/license/status');
|
||||||
|
var licenseData = await licenseRes.json();
|
||||||
|
if (licenseData.tier !== 'premium') {
|
||||||
|
pointintimeContainer.innerHTML = '<div class="panel-empty" style="padding: 24px; text-align: center;">' +
|
||||||
|
'<div style="font-size: 2rem; margin-bottom: 12px;">⭐</div>' +
|
||||||
|
'<div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div>' +
|
||||||
|
'<div style="font-size: 0.85rem; color: var(--muted);">Point-in-time restore requires DashCaddy Premium with auto-backup enabled.</div>' +
|
||||||
|
'<button onclick="showNotification(\'Upgrade to Premium for point-in-time restore!\', \'info\'); scrollToSection(\'license\');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
|
||||||
|
'</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
|
||||||
|
pointintimeContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Fetch services for dropdown
|
||||||
|
var servicesRes = await fetch('/api/v1/services');
|
||||||
|
var servicesData = await servicesRes.json();
|
||||||
|
var services = servicesData.services || [];
|
||||||
|
|
||||||
|
if (services.length === 0) {
|
||||||
|
pointintimeContainer.innerHTML = '<div class="panel-empty"><span class="empty-icon">📦</span> No apps deployed yet</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var html = '<div style="padding: 8px 0 12px;">' +
|
||||||
|
'<div style="display: flex; gap: 8px; align-items: center; margin-bottom: 12px;">' +
|
||||||
|
' <label style="font-size: 0.85rem; color: var(--muted); white-space: nowrap;">App:</label>' +
|
||||||
|
' <select id="pit-app-select" style="flex: 1; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base); max-width: 240px;">';
|
||||||
|
for (var i = 0; i < services.length; i++) {
|
||||||
|
html += '<option value="' + escapeHtml(services[i].id || services[i].name || '') + '">' +
|
||||||
|
escapeHtml(services[i].name || services[i].id || '') + '</option>';
|
||||||
|
}
|
||||||
|
html += '</select>' +
|
||||||
|
' <button id="pit-load-btn" style="padding: 8px 16px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Load Backups</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div id="pit-backups-list" style="max-height: 320px; overflow-y: auto;"></div>' +
|
||||||
|
'</div>';
|
||||||
|
|
||||||
|
pointintimeContainer.innerHTML = html;
|
||||||
|
|
||||||
|
document.getElementById('pit-load-btn')?.addEventListener('click', function() {
|
||||||
|
var appId = document.getElementById('pit-app-select')?.value;
|
||||||
|
if (appId) loadPointInTimeBackups(appId);
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
pointintimeContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed: ' + escapeHtml(e.message) + '</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPointInTimeBackups(appId) {
|
||||||
|
var listEl = document.getElementById('pit-backups-list');
|
||||||
|
if (!listEl) return;
|
||||||
|
|
||||||
|
listEl.innerHTML = '<div style="padding: 20px; text-align: center;"><span class="brand-spinner"></span> Loading backups...</div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
var res = await fetch('/api/v1/backups/files/' + encodeURIComponent(appId));
|
||||||
|
var data = await res.json();
|
||||||
|
|
||||||
|
if (!data.success || !data.files || data.files.length === 0) {
|
||||||
|
listEl.innerHTML = '<div class="panel-empty"><span class="empty-icon">💾</span> No backup files for ' + escapeHtml(appId) + '</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var html = '<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">' + data.files.length + ' backup(s)</div>' +
|
||||||
|
'<div style="display: flex; flex-direction: column; gap: 6px;">';
|
||||||
|
|
||||||
|
for (var i = 0; i < data.files.length; i++) {
|
||||||
|
var f = data.files[i];
|
||||||
|
var dateStr = new Date(f.timestamp).toLocaleString();
|
||||||
|
html += '<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">' +
|
||||||
|
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">' +
|
||||||
|
' <div style="font-weight: 500; font-size: 0.85rem;">' + escapeHtml(f.name) + '</div>' +
|
||||||
|
' <div style="font-size: 0.75rem; color: var(--muted);">' + f.sizeFormatted + '</div>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">' + dateStr + '</div>' +
|
||||||
|
'<div style="display: flex; gap: 6px;">' +
|
||||||
|
' <button class="pit-compare-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 4px 10px; font-size: 0.75rem; background: transparent; border: 1px solid var(--accent); color: var(--accent); border-radius: 5px; cursor: pointer;">Compare</button>' +
|
||||||
|
' <button class="pit-restore-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 4px 10px; font-size: 0.75rem; background: linear-gradient(135deg, var(--ok-fg), #27ae60); border: none; color: white; border-radius: 5px; cursor: pointer; font-weight: 500;">Restore</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
listEl.innerHTML = html;
|
||||||
|
|
||||||
|
// Wire up buttons
|
||||||
|
listEl.querySelectorAll('.pit-compare-btn').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() { compareBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||||
|
});
|
||||||
|
listEl.querySelectorAll('.pit-restore-btn').forEach(function(btn) {
|
||||||
|
btn.addEventListener('click', function() { restoreBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
listEl.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed: ' + escapeHtml(e.message) + '</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function compareBackupFile(appId, filename) {
|
||||||
|
try {
|
||||||
|
var res = await secureFetch('/api/v1/backups/compare/' + encodeURIComponent(filename), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({})
|
||||||
|
});
|
||||||
|
var data = await res.json();
|
||||||
|
if (!data.success) {
|
||||||
|
showNotification('Compare failed: ' + (data.error || 'Unknown'), 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var diff = data.diff;
|
||||||
|
var html = '<div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10000; display: flex; align-items: center; justify-content: center;" id="compare-overlay">' +
|
||||||
|
'<div style="background: var(--base); border-radius: 12px; max-width: 600px; width: 90%; max-height: 80vh; overflow: auto; padding: 20px; border: 1px solid var(--border);">' +
|
||||||
|
'<h4 style="margin: 0 0 16px;">📊 Compare: ' + escapeHtml(filename) + '</h4>' +
|
||||||
|
'<div style="font-size: 0.8rem; color: var(--muted); margin-bottom: 16px;">Size: ' + (diff.sizeFormatted || '?') + ' | Created: ' + new Date(diff.timestamp).toLocaleString() + '</div>';
|
||||||
|
|
||||||
|
if (diff.services) {
|
||||||
|
var svcChanged = diff.services.hasChanges ? '🔴' : '🟢';
|
||||||
|
html += '<div style="margin-bottom: 12px; padding: 10px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border);">' +
|
||||||
|
'<div style="font-weight: 600; font-size: 0.85rem; margin-bottom: 4px;">' + svcChanged + ' Services (backup vs current)</div>' +
|
||||||
|
'<div style="font-size: 0.8rem; color: var(--muted);">Backup: ' + diff.services.backupCount + ' services | Current: ' + diff.services.currentCount + ' services</div>';
|
||||||
|
if (diff.services.hasChanges) {
|
||||||
|
html += '<div style="margin-top: 6px; font-size: 0.8rem; color: #f39c12;">Services differ — restoring will replace current configuration</div>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (diff.config) {
|
||||||
|
var cfgChanged = diff.config.hasChanges ? '🔴' : '🟢';
|
||||||
|
html += '<div style="margin-bottom: 12px; padding: 10px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border);">' +
|
||||||
|
'<div style="font-weight: 600; font-size: 0.85rem; margin-bottom: 4px;">' + cfgChanged + ' Configuration</div>';
|
||||||
|
if (diff.config.hasChanges) {
|
||||||
|
html += '<div style="font-size: 0.8rem; color: #f39c12;">Configuration differs — restoring will replace current settings</div>';
|
||||||
|
} else {
|
||||||
|
html += '<div style="font-size: 0.8rem; color: var(--ok-fg);">No changes</div>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
html += '<button id="compare-close-btn" style="padding: 8px 20px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Close</button>' +
|
||||||
|
'</div></div>';
|
||||||
|
|
||||||
|
document.body.insertAdjacentHTML('beforeend', html);
|
||||||
|
document.getElementById('compare-close-btn')?.addEventListener('click', function() {
|
||||||
|
document.getElementById('compare-overlay')?.remove();
|
||||||
|
});
|
||||||
|
document.getElementById('compare-overlay')?.addEventListener('click', function(e) {
|
||||||
|
if (e.target === this) this.remove();
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
showNotification('Compare error: ' + e.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function restoreBackupFile(appId, filename) {
|
||||||
|
if (!confirm('Restore ' + filename + ' for ' + appId + '?\n\nThis will replace current configuration, credentials, and data. Containers will be restarted.')) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
var res = await secureFetch('/api/v1/apps/' + encodeURIComponent(appId) + '/revert/' + encodeURIComponent(filename), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ restartContainers: true })
|
||||||
|
});
|
||||||
|
var data = await res.json();
|
||||||
|
if (data.success) {
|
||||||
|
showNotification(appId + ' restored to ' + filename, 'success');
|
||||||
|
setTimeout(function() { location.reload(); }, 1500);
|
||||||
|
} else {
|
||||||
|
showNotification('Restore failed: ' + (data.error || 'Unknown'), 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showNotification('Restore error: ' + e.message, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -0,0 +1,455 @@
|
|||||||
|
// ========== BUNDLED WORKFLOWS ==========
|
||||||
|
(function() {
|
||||||
|
const WORKFLOW_DEFINITIONS = {
|
||||||
|
'auto-restart-on-crash': {
|
||||||
|
name: 'Auto-Restart on Crash',
|
||||||
|
icon: '🔄',
|
||||||
|
description: 'Automatically restart a container when it goes down',
|
||||||
|
trigger: 'container-down',
|
||||||
|
actions: 'restart + notify'
|
||||||
|
},
|
||||||
|
'backup-before-update': {
|
||||||
|
name: 'Backup Before Update',
|
||||||
|
icon: '💾',
|
||||||
|
description: 'Create a backup before any app update',
|
||||||
|
trigger: 'pre-update',
|
||||||
|
actions: 'backup + notify'
|
||||||
|
},
|
||||||
|
'health-check-on-interval': {
|
||||||
|
name: 'Periodic Health Check',
|
||||||
|
icon: '🏥',
|
||||||
|
description: 'Run health checks every 15 minutes and alert if degraded',
|
||||||
|
trigger: 'scheduled (15m)',
|
||||||
|
actions: 'health-check + alert'
|
||||||
|
},
|
||||||
|
'disk-space-alert': {
|
||||||
|
name: 'Disk Space Alert',
|
||||||
|
icon: '⚠️',
|
||||||
|
description: 'Alert when disk usage exceeds 80%',
|
||||||
|
trigger: 'resource-alert',
|
||||||
|
actions: 'notify'
|
||||||
|
},
|
||||||
|
'weekly-container-report': {
|
||||||
|
name: 'Weekly Container Report',
|
||||||
|
icon: '📊',
|
||||||
|
description: 'Send a weekly summary of container status and resource usage',
|
||||||
|
trigger: 'scheduled (weekly)',
|
||||||
|
actions: 'collect metrics + report'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let isPremium = false;
|
||||||
|
|
||||||
|
// === CHECK PREMIUM ===
|
||||||
|
async function checkPremium() {
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/api/v1/license/feature/workflows');
|
||||||
|
const data = await resp.json();
|
||||||
|
isPremium = data.available;
|
||||||
|
} catch {
|
||||||
|
isPremium = false;
|
||||||
|
}
|
||||||
|
return isPremium;
|
||||||
|
}
|
||||||
|
|
||||||
|
// === RENDER WORKFLOW CARD ===
|
||||||
|
function renderWorkflowCard(workflow) {
|
||||||
|
const def = WORKFLOW_DEFINITIONS[workflow.id] || {
|
||||||
|
name: workflow.name || workflow.id,
|
||||||
|
icon: '⚡',
|
||||||
|
description: workflow.description || '',
|
||||||
|
trigger: workflow.trigger || 'unknown',
|
||||||
|
actions: workflow.actions ? workflow.actions.map(a => a.type).join(' + ') : ''
|
||||||
|
};
|
||||||
|
|
||||||
|
const locked = !isPremium;
|
||||||
|
const cardClass = locked ? 'workflow-card locked' : 'workflow-card';
|
||||||
|
|
||||||
|
return `<div class="${cardClass}" data-workflow="${workflow.id}">
|
||||||
|
<div class="workflow-header">
|
||||||
|
<span class="workflow-name">${def.icon} ${escapeHtml(def.name)}</span>
|
||||||
|
<label class="toggle-switch">
|
||||||
|
<input type="checkbox" class="workflow-toggle" data-workflow="${workflow.id}" ${workflow.enabled ? 'checked' : ''} ${locked ? 'disabled' : ''} />
|
||||||
|
<span class="slider"></span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p class="workflow-desc">${escapeHtml(def.description)}</p>
|
||||||
|
<div class="workflow-meta">
|
||||||
|
<span class="workflow-trigger">⚡ Trigger: ${escapeHtml(def.trigger)}</span>
|
||||||
|
<span class="workflow-actions">▶ Actions: ${escapeHtml(def.actions)}</span>
|
||||||
|
</div>
|
||||||
|
${locked ? `<div class="workflow-locked-overlay">
|
||||||
|
<span class="lock-icon">🔒</span>
|
||||||
|
<span class="lock-text">Upgrade to Enable</span>
|
||||||
|
</div>` : ''}
|
||||||
|
<button class="btn-run-now" data-workflow="${workflow.id}" ${locked ? 'disabled' : ''}>
|
||||||
|
▶ Run Now
|
||||||
|
</button>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// === LOAD WORKFLOWS TAB ===
|
||||||
|
async function loadWorkflowsTab() {
|
||||||
|
const container = document.getElementById('workflow-list-container');
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
container.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading workflows...</div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/api/v1/workflows');
|
||||||
|
const data = await resp.json();
|
||||||
|
|
||||||
|
if (data.success && data.workflows) {
|
||||||
|
if (data.workflows.length === 0) {
|
||||||
|
container.innerHTML = '<div class="panel-empty"><span class="empty-icon">⚡</span>No workflows configured</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = '';
|
||||||
|
for (const workflow of data.workflows) {
|
||||||
|
html += renderWorkflowCard(workflow);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add non-premium banner
|
||||||
|
if (!isPremium) {
|
||||||
|
html += `<div class="accent-info-box" style="margin-top: 16px; text-align: center;">
|
||||||
|
<span>🔒 Upgrade to unlock automated workflows</span>
|
||||||
|
<button onclick="showNotification('Upgrade to Premium to enable workflows!', 'info'); scrollToSection('license');" style="margin-left: 12px; padding: 6px 16px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
container.innerHTML = `<div class="workflow-list">${html}</div>`;
|
||||||
|
wireWorkflowEvents();
|
||||||
|
} else {
|
||||||
|
container.innerHTML = '<div class="panel-empty"><span class="empty-icon">⚠️</span>Failed to load workflows</div>';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
container.innerHTML = '<div class="panel-empty"><span class="empty-icon">⚠️</span>Error loading workflows: ' + escapeHtml(error.message) + '</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === LOAD HISTORY TAB ===
|
||||||
|
async function loadHistoryTab() {
|
||||||
|
const container = document.getElementById('workflow-history-body');
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
container.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px;"><span class="brand-spinner"></span> Loading history...</td></tr>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/api/v1/workflows/history?limit=100');
|
||||||
|
const data = await resp.json();
|
||||||
|
|
||||||
|
if (data.success && data.history && data.history.length > 0) {
|
||||||
|
let html = '';
|
||||||
|
for (const entry of data.history) {
|
||||||
|
const time = new Date(entry.timestamp).toLocaleString();
|
||||||
|
const duration = entry.duration ? entry.duration + 'ms' : '-';
|
||||||
|
const resultClass = entry.success ? 'result-success' : 'result-failure';
|
||||||
|
const resultText = entry.success ? '✓ Success' : '✗ Failed';
|
||||||
|
|
||||||
|
html += `<tr>
|
||||||
|
<td>${escapeHtml(time)}</td>
|
||||||
|
<td>${escapeHtml(entry.workflowName || entry.workflowId)}</td>
|
||||||
|
<td>${escapeHtml(entry.trigger || 'manual')}</td>
|
||||||
|
<td class="${resultClass}">${resultText}</td>
|
||||||
|
<td>${escapeHtml(duration)}</td>
|
||||||
|
</tr>`;
|
||||||
|
}
|
||||||
|
container.innerHTML = html;
|
||||||
|
} else {
|
||||||
|
container.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px; color: var(--muted);">No workflow history yet</td></tr>';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
container.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px; color: var(--bad-fg);">Error loading history</td></tr>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// === WIRE WORKFLOW EVENTS ===
|
||||||
|
function wireWorkflowEvents() {
|
||||||
|
// Toggle switches
|
||||||
|
document.querySelectorAll('.workflow-toggle').forEach(toggle => {
|
||||||
|
toggle.addEventListener('change', async function() {
|
||||||
|
const workflowId = this.dataset.workflow;
|
||||||
|
const enabled = this.checked;
|
||||||
|
const endpoint = enabled ? 'enable' : 'disable';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`/api/v1/workflows/${workflowId}/${endpoint}`, { method: 'POST' });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (!data.success) {
|
||||||
|
showNotification(`Failed to ${endpoint} workflow`, 'error', 3000);
|
||||||
|
this.checked = !enabled; // revert
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
showNotification(`Error: ${error.message}`, 'error', 3000);
|
||||||
|
this.checked = !enabled; // revert
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Run Now buttons
|
||||||
|
document.querySelectorAll('.btn-run-now').forEach(btn => {
|
||||||
|
btn.addEventListener('click', async function() {
|
||||||
|
const workflowId = this.dataset.workflow;
|
||||||
|
const originalText = this.innerHTML;
|
||||||
|
this.innerHTML = '<span class="brand-spinner"></span>';
|
||||||
|
this.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`/api/v1/workflows/${workflowId}/run`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ trigger: 'manual' })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
showNotification(`Workflow "${WORKFLOW_DEFINITIONS[workflowId]?.name || workflowId}" executed successfully`, 'success', 3000);
|
||||||
|
} else {
|
||||||
|
showNotification(`Workflow failed: ${data.error || 'Unknown error'}`, 'error', 4000);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
showNotification(`Error: ${error.message}`, 'error', 3000);
|
||||||
|
} finally {
|
||||||
|
this.innerHTML = originalText;
|
||||||
|
this.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// === TAB SWITCHING ===
|
||||||
|
function setupTabSwitching() {
|
||||||
|
document.querySelectorAll('.workflows-tab-btn').forEach(btn => {
|
||||||
|
btn.addEventListener('click', function() {
|
||||||
|
const panelId = this.dataset.panel;
|
||||||
|
|
||||||
|
// Update tab buttons
|
||||||
|
document.querySelectorAll('.workflows-tab-btn').forEach(b => b.classList.remove('active'));
|
||||||
|
this.classList.add('active');
|
||||||
|
|
||||||
|
// Update panels
|
||||||
|
document.querySelectorAll('.workflow-panel').forEach(p => p.classList.remove('active'));
|
||||||
|
document.getElementById(panelId)?.classList.add('active');
|
||||||
|
|
||||||
|
// Load data for the active panel
|
||||||
|
if (panelId === 'workflows-list-panel') {
|
||||||
|
loadWorkflowsTab();
|
||||||
|
} else if (panelId === 'workflows-history-panel') {
|
||||||
|
loadHistoryTab();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// === INJECT MODAL HTML ===
|
||||||
|
injectModal('bundled-workflows-modal', `<div id="bundled-workflows-modal" class="weather-modal">
|
||||||
|
<div class="weather-modal-content" style="min-width: 600px; max-width: 750px;">
|
||||||
|
<h3>⚡ Bundled Workflows</h3>
|
||||||
|
<p class="modal-subtitle">
|
||||||
|
Automated workflows to keep your system running smoothly
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<!-- Tab bar -->
|
||||||
|
<div class="panel-tabs">
|
||||||
|
<button class="workflows-tab-btn panel-tab active" data-panel="workflows-list-panel">Workflows</button>
|
||||||
|
<button class="workflows-tab-btn panel-tab" data-panel="workflows-history-panel">History</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: Workflows -->
|
||||||
|
<div id="workflows-list-panel" class="workflow-panel panel-section active">
|
||||||
|
<div id="workflow-list-container">
|
||||||
|
<div class="panel-empty">
|
||||||
|
<span class="brand-spinner"></span> Loading workflows...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tab: History -->
|
||||||
|
<div id="workflows-history-panel" class="workflow-panel panel-section">
|
||||||
|
<div class="workflow-history">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Time</th>
|
||||||
|
<th>Workflow</th>
|
||||||
|
<th>Trigger</th>
|
||||||
|
<th>Result</th>
|
||||||
|
<th>Duration</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="workflow-history-body">
|
||||||
|
<!-- populated from API -->
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Close Button -->
|
||||||
|
<div class="weather-modal-buttons modal-footer-bar">
|
||||||
|
<button id="workflows-cancel">Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>`);
|
||||||
|
|
||||||
|
const modal = document.getElementById('bundled-workflows-modal');
|
||||||
|
const openBtn = document.getElementById('bundled-workflows-btn');
|
||||||
|
const cancelBtn = document.getElementById('workflows-cancel');
|
||||||
|
|
||||||
|
// === STYLES ===
|
||||||
|
const style = document.createElement('style');
|
||||||
|
style.textContent = `
|
||||||
|
.workflow-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-card {
|
||||||
|
position: relative;
|
||||||
|
padding: 16px;
|
||||||
|
background: var(--card-base);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-card:hover {
|
||||||
|
border-color: var(--accent);
|
||||||
|
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-card.locked {
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-name {
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-desc {
|
||||||
|
font-size: 0.82rem;
|
||||||
|
color: var(--muted);
|
||||||
|
margin: 0 0 10px 0;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--muted);
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-meta span {
|
||||||
|
padding: 2px 8px;
|
||||||
|
background: var(--base);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-locked-overlay {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0,0,0,0.5);
|
||||||
|
border-radius: 10px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lock-icon {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lock-text {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #f39c12;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-history {
|
||||||
|
max-height: 400px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-history table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-history th {
|
||||||
|
text-align: left;
|
||||||
|
padding: 8px 10px;
|
||||||
|
background: var(--base);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
font-weight: 600;
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-history td {
|
||||||
|
padding: 8px 10px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-success {
|
||||||
|
color: var(--ok-fg);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-failure {
|
||||||
|
color: var(--bad-fg);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-panel {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-panel.active {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.accent-info-box {
|
||||||
|
padding: 12px 16px;
|
||||||
|
background: color-mix(in srgb, var(--accent) 10%, transparent);
|
||||||
|
border: 1px solid var(--accent);
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
document.head.appendChild(style);
|
||||||
|
|
||||||
|
// === MODAL EVENTS ===
|
||||||
|
openBtn?.addEventListener('click', async function() {
|
||||||
|
modal.classList.add('show');
|
||||||
|
await checkPremium();
|
||||||
|
loadWorkflowsTab();
|
||||||
|
});
|
||||||
|
|
||||||
|
setupTabSwitching();
|
||||||
|
|
||||||
|
// Close on cancel
|
||||||
|
cancelBtn?.addEventListener('click', function() {
|
||||||
|
modal.classList.remove('show');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wire modal escape key / click outside
|
||||||
|
wireModal(modal, cancelBtn);
|
||||||
|
})();
|
||||||
@@ -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>
|
||||||
|
|||||||
@@ -95,6 +95,36 @@
|
|||||||
'Prometheus metrics'
|
'Prometheus metrics'
|
||||||
],
|
],
|
||||||
recommended: false
|
recommended: false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cloudflare',
|
||||||
|
name: 'Cloudflare DNS',
|
||||||
|
description: 'Managed DNS with API access — no self-hosting needed',
|
||||||
|
icon: '🔶',
|
||||||
|
difficulty: 'Easy',
|
||||||
|
features: [
|
||||||
|
'Fully managed, no server needed',
|
||||||
|
'API for automated record management',
|
||||||
|
'Global anycast network',
|
||||||
|
'Free tier available'
|
||||||
|
],
|
||||||
|
recommended: false,
|
||||||
|
providerId: 'cloudflare'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'external',
|
||||||
|
name: 'External / Manual DNS',
|
||||||
|
description: 'Use your own DNS provider (cPanel, Route53, etc.)',
|
||||||
|
icon: '🔗',
|
||||||
|
difficulty: 'Easy',
|
||||||
|
features: [
|
||||||
|
'Works with any DNS provider',
|
||||||
|
'DashCaddy shows you what records to create',
|
||||||
|
'Propagation checking still works',
|
||||||
|
'No API credentials needed'
|
||||||
|
],
|
||||||
|
recommended: false,
|
||||||
|
providerId: 'manual'
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|
||||||
|
})();
|
||||||
@@ -168,6 +168,9 @@
|
|||||||
<label class="checkbox-label-sm">
|
<label class="checkbox-label-sm">
|
||||||
<input type="checkbox" id="event-deploy-failed" checked /> Deployment Failed
|
<input type="checkbox" id="event-deploy-failed" checked /> Deployment Failed
|
||||||
</label>
|
</label>
|
||||||
|
<label class="checkbox-label-sm" style="grid-column: 1 / -1;">
|
||||||
|
<input type="checkbox" id="event-resource-alert" checked /> Resource Alerts
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- History -->
|
<!-- History -->
|
||||||
@@ -175,9 +178,11 @@
|
|||||||
<div id="notification-history" style="max-height: 150px; overflow-y: auto; padding: 8px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); font-size: 0.8rem;">
|
<div id="notification-history" style="max-height: 150px; overflow-y: auto; padding: 8px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); font-size: 0.8rem;">
|
||||||
<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>
|
<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="last-notification-sent" style="font-size: 0.75rem; color: var(--muted); text-align: center; margin-top: 6px;"></div>
|
||||||
|
|
||||||
<!-- Buttons -->
|
<!-- Buttons -->
|
||||||
<div class="weather-modal-buttons modal-footer-bar">
|
<div class="weather-modal-buttons modal-footer-bar">
|
||||||
|
<button id="notifications-send-test" class="btn-secondary" style="margin-right: auto;">Send Test</button>
|
||||||
<button id="notifications-cancel">Cancel</button>
|
<button id="notifications-cancel">Cancel</button>
|
||||||
<button id="notifications-save" class="btn-accent">Save Settings</button>
|
<button id="notifications-save" class="btn-accent">Save Settings</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -254,6 +259,7 @@
|
|||||||
document.getElementById('event-container-up').checked = config.events?.containerUp !== false;
|
document.getElementById('event-container-up').checked = config.events?.containerUp !== false;
|
||||||
document.getElementById('event-deploy-success').checked = config.events?.deploymentSuccess !== false;
|
document.getElementById('event-deploy-success').checked = config.events?.deploymentSuccess !== false;
|
||||||
document.getElementById('event-deploy-failed').checked = config.events?.deploymentFailed !== false;
|
document.getElementById('event-deploy-failed').checked = config.events?.deploymentFailed !== false;
|
||||||
|
document.getElementById('event-resource-alert').checked = config.events?.resourceAlert !== false;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errorHandler.logError('[Notifications] Load Config', error, { function: 'loadConfig' });
|
errorHandler.logError('[Notifications] Load Config', error, { function: 'loadConfig' });
|
||||||
@@ -329,7 +335,8 @@
|
|||||||
containerDown: document.getElementById('event-container-down').checked,
|
containerDown: document.getElementById('event-container-down').checked,
|
||||||
containerUp: document.getElementById('event-container-up').checked,
|
containerUp: document.getElementById('event-container-up').checked,
|
||||||
deploymentSuccess: document.getElementById('event-deploy-success').checked,
|
deploymentSuccess: document.getElementById('event-deploy-success').checked,
|
||||||
deploymentFailed: document.getElementById('event-deploy-failed').checked
|
deploymentFailed: document.getElementById('event-deploy-failed').checked,
|
||||||
|
resourceAlert: document.getElementById('event-resource-alert').checked
|
||||||
},
|
},
|
||||||
healthCheck: {
|
healthCheck: {
|
||||||
enabled: document.getElementById('health-check-enabled').checked,
|
enabled: document.getElementById('health-check-enabled').checked,
|
||||||
@@ -404,5 +411,56 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
saveBtn?.addEventListener('click', saveNotificationConfig);
|
saveBtn?.addEventListener('click', saveNotificationConfig);
|
||||||
|
|
||||||
|
// Send Test button - sends test notification to all enabled providers
|
||||||
|
document.getElementById('notifications-send-test')?.addEventListener('click', async () => {
|
||||||
|
const btn = document.getElementById('notifications-send-test');
|
||||||
|
const originalText = btn.textContent;
|
||||||
|
btn.textContent = 'Sending...';
|
||||||
|
btn.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await secureFetch('/api/v1/notifications/send', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
event: 'test',
|
||||||
|
data: { message: 'This is a test notification from DashCaddy.' },
|
||||||
|
type: 'info'
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
if (data.success) {
|
||||||
|
showNotification('Test notification sent!', 'success', 3000);
|
||||||
|
// Update last sent timestamp
|
||||||
|
loadNotificationStatus();
|
||||||
|
} else {
|
||||||
|
showNotification(`Test failed: ${data.results?.map(r => `${r.provider}: ${r.error || 'ok'}`).join(', ')}`, 'error', 5000);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
showNotification(`Error: ${error.message}`, 'error', 3000);
|
||||||
|
} finally {
|
||||||
|
btn.textContent = originalText;
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Load notification status (last sent timestamp)
|
||||||
|
async function loadNotificationStatus() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/v1/notifications/status');
|
||||||
|
const data = await response.json();
|
||||||
|
if (data.success && data.lastSent) {
|
||||||
|
const lastSentEl = document.getElementById('last-notification-sent');
|
||||||
|
if (lastSentEl) {
|
||||||
|
lastSentEl.textContent = `Last sent: ${new Date(data.lastSent).toLocaleString()}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - status is not critical
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
wireModal(modal, cancelBtn);
|
wireModal(modal, cancelBtn);
|
||||||
})();
|
})();
|
||||||
|
|||||||
+165
-50
@@ -236,70 +236,185 @@
|
|||||||
async function loadAlerts() {
|
async function loadAlerts() {
|
||||||
if (!alertsContainer) return;
|
if (!alertsContainer) return;
|
||||||
alertsContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';
|
alertsContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';
|
||||||
|
|
||||||
const data = cachedMonitoringData;
|
const data = cachedMonitoringData;
|
||||||
if (!data || Object.keys(data).length === 0) {
|
if (!data || Object.keys(data).length === 0) {
|
||||||
alertsContainer.innerHTML = '<div class="panel-empty"><span class="empty-icon">🔔</span>No containers found. Open the Live Stats tab first.</div>';
|
alertsContainer.innerHTML = '<div class="panel-empty"><span class="empty-icon">🔔</span>No containers found. Open the Live Stats tab first.</div>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let html = '<div style="display: flex; flex-direction: column; gap: 12px;">';
|
|
||||||
for (const [id, info] of Object.entries(data)) {
|
|
||||||
const alertCfg = info.alertConfig || {};
|
|
||||||
html += `<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
|
|
||||||
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px;">
|
|
||||||
<span style="font-weight: 600; flex: 1;">${info.name || id}</span>
|
|
||||||
<label style="display: flex; align-items: center; gap: 6px; font-size: 0.8rem; cursor: pointer;">
|
|
||||||
<input type="checkbox" class="alert-enabled" data-container="${id}" ${alertCfg.enabled ? 'checked' : ''} /> Enabled
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
|
|
||||||
<div>
|
|
||||||
<label style="font-size: 0.75rem; color: var(--muted);">CPU Threshold %</label>
|
|
||||||
<input type="number" class="alert-cpu" data-container="${id}" value="${alertCfg.cpuThreshold || 80}" min="1" max="100" style="width: 100%; font-size: 0.85rem;" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label style="font-size: 0.75rem; color: var(--muted);">Memory Threshold %</label>
|
|
||||||
<input type="number" class="alert-mem" data-container="${id}" value="${alertCfg.memoryThreshold || 85}" min="1" max="100" style="width: 100%; font-size: 0.85rem;" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label style="font-size: 0.75rem; color: var(--muted);">Cooldown (min)</label>
|
|
||||||
<input type="number" class="alert-cooldown" data-container="${id}" value="${alertCfg.cooldownMinutes || 15}" min="1" max="1440" style="width: 100%; font-size: 0.85rem;" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div style="display: flex; gap: 8px; margin-top: 8px; align-items: center;">
|
|
||||||
<label style="display: flex; align-items: center; gap: 6px; font-size: 0.8rem; cursor: pointer;">
|
|
||||||
<input type="checkbox" class="alert-autorestart" data-container="${id}" ${alertCfg.autoRestart ? 'checked' : ''} /> Auto-restart on breach
|
|
||||||
</label>
|
|
||||||
<span style="flex: 1;"></span>
|
|
||||||
<button class="alert-save-btn" data-container="${id}" style="padding: 4px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 4px; cursor: pointer;">Save</button>
|
|
||||||
</div>
|
|
||||||
</div>`;
|
|
||||||
}
|
|
||||||
html += '</div>';
|
|
||||||
alertsContainer.innerHTML = html;
|
|
||||||
|
|
||||||
// Wire up save buttons
|
// Check premium status for config section visibility
|
||||||
alertsContainer.querySelectorAll('.alert-save-btn').forEach(btn => {
|
let isPremium = false;
|
||||||
btn.addEventListener('click', async () => {
|
|
||||||
const cId = btn.dataset.container;
|
|
||||||
const enabled = alertsContainer.querySelector(`.alert-enabled[data-container="${cId}"]`)?.checked || false;
|
|
||||||
const cpuThreshold = parseInt(alertsContainer.querySelector(`.alert-cpu[data-container="${cId}"]`)?.value) || 80;
|
|
||||||
const memoryThreshold = parseInt(alertsContainer.querySelector(`.alert-mem[data-container="${cId}"]`)?.value) || 85;
|
|
||||||
const cooldownMinutes = parseInt(alertsContainer.querySelector(`.alert-cooldown[data-container="${cId}"]`)?.value) || 15;
|
|
||||||
const autoRestart = alertsContainer.querySelector(`.alert-autorestart[data-container="${cId}"]`)?.checked || false;
|
|
||||||
try {
|
try {
|
||||||
const res = await secureFetch(`/api/v1/monitoring/alerts/${cId}`, {
|
const resp = await fetch('/api/v1/license/feature/resource-alerts');
|
||||||
|
const ld = await resp.json();
|
||||||
|
isPremium = ld.available;
|
||||||
|
} catch (_) { isPremium = false; }
|
||||||
|
|
||||||
|
// Fetch alert history
|
||||||
|
let alertHistory = [];
|
||||||
|
try {
|
||||||
|
const hr = await fetch('/api/v1/monitoring/alerts?limit=50');
|
||||||
|
const hd = await hr.json();
|
||||||
|
if (hd.success) alertHistory = hd.history || [];
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
// Fetch all alert configs
|
||||||
|
let allConfigs = {};
|
||||||
|
try {
|
||||||
|
const cr = await fetch('/api/v1/monitoring/alerts/config');
|
||||||
|
const cd = await cr.json();
|
||||||
|
if (cd.success) allConfigs = cd.configs || {};
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
const containers = Object.entries(data);
|
||||||
|
const containerRows = containers.map(([id, info]) => {
|
||||||
|
const cfg = allConfigs[id] || { cpuThreshold: 80, memoryThreshold: 90, diskIOThreshold: 50, autoRestart: false, enabled: false };
|
||||||
|
return `
|
||||||
|
<tr data-container="${id}">
|
||||||
|
<td style="font-weight: 600; padding: 8px;">${info.name || id}</td>
|
||||||
|
<td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${cfg.cpuThreshold ?? 80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${isPremium ? '' : 'disabled'} /></td>
|
||||||
|
<td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${cfg.memoryThreshold ?? 90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${isPremium ? '' : 'disabled'} /></td>
|
||||||
|
<td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${cfg.diskIOThreshold ?? 50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${isPremium ? '' : 'disabled'} /></td>
|
||||||
|
<td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${cfg.autoRestart ? 'checked' : ''} ${isPremium ? '' : 'disabled'} /></td>
|
||||||
|
<td style="padding: 4px 8px;">
|
||||||
|
<button class="alert-test-btn btn-xs" data-container="${id}" data-name="${info.name || id}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
|
||||||
|
const historyRows = alertHistory.map(entry => {
|
||||||
|
const time = new Date(entry.timestamp).toLocaleString();
|
||||||
|
const notifiedMark = entry.notified ? '✓' : '—';
|
||||||
|
return `
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${time}</td>
|
||||||
|
<td style="padding: 6px 8px; font-weight: 500;">${entry.containerName || entry.containerId}</td>
|
||||||
|
<td style="padding: 6px 8px; text-transform: capitalize;">${entry.metric || entry.type}</td>
|
||||||
|
<td style="padding: 6px 8px;">${typeof entry.value === 'number' ? entry.value.toFixed(1) : entry.value}${entry.metric === 'disk' ? ' MB/s' : '%'}</td>
|
||||||
|
<td style="padding: 6px 8px; text-align: center;">${notifiedMark}</td>
|
||||||
|
<td style="padding: 6px 8px; font-size: 0.75rem; color: ${entry.autoRestartTriggered ? '#f39c12' : 'var(--muted)'};">${entry.autoRestartTriggered ? '↻' : ''}</td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
|
||||||
|
const configSection = isPremium ? `
|
||||||
|
<div style="margin-bottom: 20px;">
|
||||||
|
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
|
||||||
|
<h4 style="margin: 0; font-size: 0.9rem;">⚙️ Alert Configuration</h4>
|
||||||
|
<a href="#" id="go-to-notifications" style="font-size: 0.8rem; color: var(--accent); text-decoration: none;">Configure notifications →</a>
|
||||||
|
</div>
|
||||||
|
<div style="overflow-x: auto;">
|
||||||
|
<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">
|
||||||
|
<thead>
|
||||||
|
<tr style="border-bottom: 1px solid var(--border);">
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Container</th>
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">CPU %</th>
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Mem %</th>
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Disk I/O MB/s</th>
|
||||||
|
<th style="text-align: center; padding: 6px 8px; color: var(--muted);">Auto-Restart</th>
|
||||||
|
<th style="padding: 6px 8px;"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>${containerRows}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top: 12px; display: flex; justify-content: flex-end;">
|
||||||
|
<button id="save-all-alerts" style="padding: 6px 16px; font-size: 0.85rem; background: var(--accent); color: var(--base); border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Save All</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
` : `
|
||||||
|
<div style="margin-bottom: 20px; padding: 12px; background: rgba(241,196,15,0.1); border: 1px solid rgba(241,196,15,0.3); border-radius: 8px; text-align: center;">
|
||||||
|
<span style="color: #f1c40f; font-weight: 600; font-size: 0.85rem;">⭐ Premium Feature</span>
|
||||||
|
<p style="margin: 6px 0 0; font-size: 0.75rem; color: var(--muted);">Upgrade to configure resource alert thresholds per container.</p>
|
||||||
|
<button id="upgrade-for-alerts" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; background: #f1c40f; color: #000; border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Upgrade Now</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
alertsContainer.innerHTML = `
|
||||||
|
${configSection}
|
||||||
|
<div>
|
||||||
|
<h4 style="margin: 0 0 10px; font-size: 0.9rem;">📋 Recent Alerts</h4>
|
||||||
|
${historyRows ? `
|
||||||
|
<div style="overflow-x: auto;">
|
||||||
|
<table style="width: 100%; border-collapse: collapse; font-size: 0.8rem;">
|
||||||
|
<thead>
|
||||||
|
<tr style="border-bottom: 1px solid var(--border);">
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Time</th>
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Container</th>
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Metric</th>
|
||||||
|
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Value</th>
|
||||||
|
<th style="text-align: center; padding: 6px 8px; color: var(--muted);">✓?</th>
|
||||||
|
<th style="padding: 6px 8px;"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>${historyRows}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
` : '<div style="color: var(--muted); text-align: center; padding: 20px;">No alerts recorded yet.</div>'}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Wire up save-all button
|
||||||
|
document.getElementById('save-all-alerts')?.addEventListener('click', async () => {
|
||||||
|
const configs = {};
|
||||||
|
document.querySelectorAll('#stats-alerts-container tr[data-container]').forEach(row => {
|
||||||
|
const cId = row.dataset.container;
|
||||||
|
configs[cId] = {
|
||||||
|
cpuThreshold: parseInt(row.querySelector('.alert-cpu')?.value) || 80,
|
||||||
|
memoryThreshold: parseInt(row.querySelector('.alert-mem')?.value) || 90,
|
||||||
|
diskIOThreshold: parseInt(row.querySelector('.alert-disk')?.value) || 50,
|
||||||
|
autoRestart: !!row.querySelector('.alert-autorestart')?.checked,
|
||||||
|
enabled: true
|
||||||
|
};
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const res = await secureFetch('/api/v1/monitoring/alerts/config', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ enabled, cpuThreshold, memoryThreshold, cooldownMinutes, autoRestart })
|
body: JSON.stringify({ configs })
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const d = await res.json();
|
||||||
btn.textContent = data.success ? '✅ Saved' : '⚠️ Failed';
|
const btn = document.getElementById('save-all-alerts');
|
||||||
setTimeout(() => { btn.textContent = 'Save'; }, 2000);
|
btn.textContent = d.success ? '✅ Saved' : '❌ Failed';
|
||||||
|
setTimeout(() => { btn.textContent = 'Save All'; }, 2000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
const btn = document.getElementById('save-all-alerts');
|
||||||
btn.textContent = '❌ Error';
|
btn.textContent = '❌ Error';
|
||||||
setTimeout(() => { btn.textContent = 'Save'; }, 2000);
|
setTimeout(() => { btn.textContent = 'Save All'; }, 2000);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Wire up notification settings link
|
||||||
|
document.getElementById('go-to-notifications')?.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
modal.classList.remove('show');
|
||||||
|
stopAutoRefresh();
|
||||||
|
document.getElementById('manage-notifications')?.click();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wire up test buttons
|
||||||
|
document.querySelectorAll('.alert-test-btn').forEach(btn => {
|
||||||
|
btn.addEventListener('click', async () => {
|
||||||
|
const orig = btn.textContent;
|
||||||
|
btn.textContent = '...';
|
||||||
|
try {
|
||||||
|
await secureFetch(`/api/v1/monitoring/alerts/${btn.dataset.container}/test`, { method: 'POST' });
|
||||||
|
btn.textContent = '✅';
|
||||||
|
showNotification('Test alert sent for ' + btn.dataset.name, 'success', 3000);
|
||||||
|
} catch (e) {
|
||||||
|
btn.textContent = '❌';
|
||||||
|
}
|
||||||
|
setTimeout(() => { btn.textContent = orig; }, 2000);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wire up upgrade button
|
||||||
|
document.getElementById('upgrade-for-alerts')?.addEventListener('click', () => {
|
||||||
|
modal.classList.remove('show');
|
||||||
|
stopAutoRefresh();
|
||||||
|
if (typeof openLicenseModal === 'function') openLicenseModal();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -174,8 +174,9 @@ window.populateTimezoneSelect = function(selectEl, selectedTz) {
|
|||||||
if (currentConfigType === 'homelab') {
|
if (currentConfigType === 'homelab') {
|
||||||
config.tld = document.getElementById('setup-tld')?.value?.trim() || '.home';
|
config.tld = document.getElementById('setup-tld')?.value?.trim() || '.home';
|
||||||
config.caName = document.getElementById('setup-ca-name')?.value?.trim() || '';
|
config.caName = document.getElementById('setup-ca-name')?.value?.trim() || '';
|
||||||
|
const selectedProvider = document.getElementById('setup-dns-provider')?.value || 'technitium';
|
||||||
config.dns = {
|
config.dns = {
|
||||||
provider: 'technitium',
|
provider: selectedProvider,
|
||||||
ip: document.getElementById('setup-dns-ip')?.value?.trim() || '',
|
ip: document.getElementById('setup-dns-ip')?.value?.trim() || '',
|
||||||
port: document.getElementById('setup-dns-port')?.value?.trim() || DC.DEFAULTS.DNS_PORT,
|
port: document.getElementById('setup-dns-port')?.value?.trim() || DC.DEFAULTS.DNS_PORT,
|
||||||
token: document.getElementById('setup-dns-token')?.value?.trim() || ''
|
token: document.getElementById('setup-dns-token')?.value?.trim() || ''
|
||||||
|
|||||||
@@ -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