Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | /** * Routes Uptime — Monitoring de disponibilité des URLs. * * Endpoints : * GET /uptime/monitors — Lister les monitors * POST /uptime/monitors — Ajouter un monitor * PATCH /uptime/monitors/:id — Modifier un monitor * DELETE /uptime/monitors/:id — Supprimer un monitor * GET /uptime/monitors/:id/history — Historique (uptime %, latence) * POST /uptime/scan/:serverId — Scanner les URLs depuis Traefik * * @module routes/uptime */ const express = require('express'); const { pool: db } = require('../db'); const { requireAuth } = require('../middleware/auth'); const { checkQuota, checkPlanValue } = require('../middleware/planLimits'); const { validatePublicUrl } = require('../utils/networkValidator'); const { exec } = require('../services/ssh'); const { makeDeleteHandler } = require('../helpers/routeHelpers'); const { requireGroupContext, requireGroupPermission } = require('../middleware/groupContext'); const { applyGroupScope } = require('../helpers/groupScope'); const router = express.Router(); router.use(requireAuth); router.use(requireGroupContext()); // ─── GET /uptime/monitors ─────────────────────────────────────────────────── router.get('/monitors', requireGroupPermission('uptime', 'read'), async (req, res, next) => { try { const effectiveUserId = req.access?.ownerUserId || req.user.id; // Récupérer les monitors avec le dernier statut et l'uptime 24h const baseQuery = ` SELECT m.id, m.url, m.label, m.interval_s, m.enabled, m.created_at, m.docker_service, (SELECT status FROM uptime_history WHERE monitor_id = m.id ORDER BY created_at DESC LIMIT 1) AS last_status, (SELECT latency_ms FROM uptime_history WHERE monitor_id = m.id ORDER BY created_at DESC LIMIT 1) AS last_latency, (SELECT ROUND( COUNT(*) FILTER (WHERE status BETWEEN 200 AND 399) * 100.0 / GREATEST(COUNT(*), 1), 1 ) FROM uptime_history WHERE monitor_id = m.id AND created_at > NOW() - INTERVAL '24 hours') AS uptime_24h, (SELECT ROUND( COUNT(*) FILTER (WHERE status BETWEEN 200 AND 399) * 100.0 / GREATEST(COUNT(*), 1), 1 ) FROM uptime_history WHERE monitor_id = m.id AND created_at > NOW() - INTERVAL '30 days') AS uptime_30d FROM uptime_monitors m WHERE m.user_id = $1`; const { rows } = await db.query(baseQuery + ` ORDER BY m.created_at`, [effectiveUserId]); // En mode groupe, filtrer par docker_service matchant les docker_targets if (req.access && req.access.serverIds?.length > 0) { const { loadGroupTargets, matchesTargets } = require('../helpers/dockerTargets'); const allTargets = []; for (const sid of req.access.serverIds) { allTargets.push(...await loadGroupTargets(req.access.groupId, sid)); } if (allTargets.length === 0) return res.json([]); const filtered = rows.filter((m) => m.docker_service && matchesTargets(m.docker_service, allTargets)); return res.json(filtered); } res.json(rows); } catch (err) { next(err); } }); // ─── POST /uptime/monitors ────────────────────────────────────────────────── router.post('/monitors', requireGroupPermission('uptime', 'read'), checkQuota('uptime_monitors', 'uptime_monitors'), checkPlanValue('uptime_interval_seconds'), async (req, res, next) => { try { const effectiveUserId = req.access?.ownerUserId || req.user.id; const { url, label, interval_s = 300, docker_service } = req.body; if (!url || !label) { return res.status(400).json({ error: 'url et label sont requis.' }); } if (!/^https?:\/\/.+/.test(url)) { return res.status(400).json({ error: 'URL invalide (doit commencer par http:// ou https://).' }); } // Protection SSRF : bloquer les IPs privees const urlCheck = await validatePublicUrl(url); if (!urlCheck.valid) { return res.status(400).json({ error: urlCheck.reason }); } const minInterval = req.planLimit?.uptime_interval_seconds || 300; const interval = Math.max(minInterval, Math.min(Number.parseInt(interval_s) || 300, 3600)); const { rows } = await db.query( `INSERT INTO uptime_monitors (user_id, url, label, interval_s, docker_service) VALUES ($1, $2, $3, $4, $5) RETURNING id, url, label, interval_s, enabled, created_at, docker_service`, [effectiveUserId, url, label, interval, docker_service || null], ); res.status(201).json(rows[0]); } catch (err) { next(err); } }); // ─── PATCH /uptime/monitors/:id ───────────────────────────────────────────── router.patch('/monitors/:id', requireGroupPermission('uptime', 'read'), checkPlanValue('uptime_interval_seconds'), async (req, res, next) => { try { const effectiveUserId = req.access?.ownerUserId || req.user.id; const { url, label, interval_s, enabled } = req.body; const existing = await db.query( 'SELECT * FROM uptime_monitors WHERE id = $1 AND user_id = $2', [req.params.id, effectiveUserId], ); if (existing.rows.length === 0) { return res.status(404).json({ error: 'Monitor introuvable.' }); } const minInterval = req.planLimit?.uptime_interval_seconds || 300; const m = existing.rows[0]; const { rows } = await db.query( `UPDATE uptime_monitors SET url=$1, label=$2, interval_s=$3, enabled=$4 WHERE id=$5 AND user_id=$6 RETURNING id, url, label, interval_s, enabled, created_at`, [ url ?? m.url, label ?? m.label, interval_s == null ? m.interval_s : Math.max(minInterval, Math.min(Number.parseInt(interval_s), 3600)), enabled == null ? m.enabled : Boolean(enabled), req.params.id, effectiveUserId, ], ); res.json(rows[0]); } catch (err) { next(err); } }); // ─── DELETE /uptime/monitors/:id ──────────────────────────────────────────── router.delete('/monitors/:id', requireGroupPermission('uptime', 'read'), makeDeleteHandler('uptime_monitors', 'Monitor introuvable.', { message: 'Monitor supprimé.' })); // ─── GET /uptime/monitors/:id/history ─────────────────────────────────────── router.get('/monitors/:id/history', requireGroupPermission('uptime', 'read'), async (req, res, next) => { try { const range = req.query.range || '24h'; const intervals = { '1h': '1 hour', '6h': '6 hours', '24h': '24 hours', '7d': '7 days', '30d': '30 days' }; const interval = intervals[range] || '24 hours'; const { rows } = await db.query( `SELECT status, latency_ms, created_at FROM uptime_history WHERE monitor_id = $1 AND created_at > NOW() - INTERVAL '${interval}' ORDER BY created_at`, [req.params.id], ); // Calculer l'uptime % const total = rows.length; const up = rows.filter((r) => r.status >= 200 && r.status < 400).length; const uptimePercent = total > 0 ? Math.round((up / total) * 1000) / 10 : null; const avgLatency = total > 0 ? Math.round(rows.reduce((s, r) => s + (r.latency_ms || 0), 0) / total) : null; res.json({ checks: rows, uptime_percent: uptimePercent, avg_latency: avgLatency, count: total }); } catch (err) { next(err); } }); // ─── POST /uptime/scan/:serverId — auto-detect URLs depuis Traefik ────────── router.post('/scan/:serverId', requireGroupPermission('uptime', 'read'), async (req, res, next) => { try { const effectiveUserId = req.access?.ownerUserId || req.user.id; const { serverId } = req.params; // Vérifier propriété du serveur const srvCheck = await db.query('SELECT id FROM servers WHERE id = $1 AND user_id = $2', [serverId, effectiveUserId]); if (srvCheck.rows.length === 0) { return res.status(403).json({ error: 'Accès refusé.' }); } // Scanner les labels Traefik avec le nom du service pour le mapping service→host // Format : service_name|||{labels_json} const { stdout: swarmOut } = await exec(effectiveUserId, serverId, "docker service inspect $(docker service ls -q 2>/dev/null) --format '{{.Spec.Name}}|||{{json .Spec.Labels}}' 2>/dev/null", ); const serviceHosts = []; for (const line of (swarmOut || '').trim().split('\n').filter(Boolean)) { const sepIdx = line.indexOf('|||'); if (sepIdx === -1) continue; const serviceName = line.substring(0, sepIdx); const labelsJson = line.substring(sepIdx + 3); // Extraire les Host(`...`) des labels Traefik via matchAll for (const m of labelsJson.matchAll(/Host\(\x60([^\x60]+)\x60\)/g)) { serviceHosts.push({ service: serviceName, host: m[1] }); } } // Fallback : labels sur les containers (docker-compose classique) if (serviceHosts.length === 0) { const { stdout: composeOut } = await exec(effectiveUserId, serverId, "docker inspect $(docker ps -q 2>/dev/null) --format '{{.Name}}|||{{json .Config.Labels}}' 2>/dev/null", ); for (const line of (composeOut || '').trim().split('\n').filter(Boolean)) { const sepIdx = line.indexOf('|||'); if (sepIdx === -1) continue; const containerName = line.substring(0, sepIdx).replace(/^\//, ''); const labelsJson = line.substring(sepIdx + 3); for (const m of labelsJson.matchAll(/Host\(\x60([^\x60]+)\x60\)/g)) { serviceHosts.push({ service: containerName, host: m[1] }); } } } // En mode groupe, filtrer par docker_targets let filtered = serviceHosts; if (req.access) { const { loadGroupTargets, matchesTargets } = require('../helpers/dockerTargets'); const targets = await loadGroupTargets(req.access.groupId, serverId); if (targets.length === 0) return res.json({ urls: [] }); filtered = serviceHosts.filter((sh) => matchesTargets(sh.service, targets)); } // Deduplication par host const seen = new Set(); const urls = []; for (const { host, service } of filtered) { if (seen.has(host)) continue; seen.add(host); urls.push({ url: `https://${host}`, label: host, service }); } // Auto-remplir docker_service sur les monitors existants qui matchent une URL detectee const hostToService = new Map(serviceHosts.map((sh) => [sh.host, sh.service])); const { rows: existingMonitors } = await db.query( 'SELECT id, url FROM uptime_monitors WHERE user_id = $1 AND docker_service IS NULL', [effectiveUserId], ); for (const m of existingMonitors) { try { const host = new URL(m.url).hostname; const svc = hostToService.get(host); /* v8 ignore next */ if (svc) { await db.query('UPDATE uptime_monitors SET docker_service = $1 WHERE id = $2', [svc, m.id]); } } catch {} } res.json({ urls }); } catch (err) { next(err); } }); module.exports = router; |