|
| 1 | +import { Context } from "./dependencies.ts"; |
| 2 | +import { |
| 3 | + getContainerHistory, |
| 4 | + getHealthSummary, |
| 5 | + isUnhealthy, |
| 6 | + type TimeStep, |
| 7 | + type TimeRange, |
| 8 | +} from "./utils/container-health.ts"; |
| 9 | +import { restartContainer, getRestartCount } from "./utils/auto-restart.ts"; |
| 10 | +import { getMonitorStatus, triggerHealthCheck } from "./health-monitor.ts"; |
| 11 | +import { checkJWT } from "./utils/jwt.ts"; |
| 12 | + |
| 13 | +const TIME_RANGE_PRESETS: Record<TimeStep, TimeRange> = { |
| 14 | + '1s': { step: '1s', duration: '5m' }, |
| 15 | + '15s': { step: '15s', duration: '15m' }, |
| 16 | + '1m': { step: '1m', duration: '1h' }, |
| 17 | + '5m': { step: '5m', duration: '6h' }, |
| 18 | + '1h': { step: '1h', duration: '24h' }, |
| 19 | + '1d': { step: '1d', duration: '7d' }, |
| 20 | +}; |
| 21 | + |
| 22 | + |
| 23 | +export async function getContainerHealth(ctx: Context): Promise<void> { |
| 24 | + const author = ctx.request.url.searchParams.get("user"); |
| 25 | + const token = ctx.request.url.searchParams.get("token"); |
| 26 | + const provider = ctx.request.url.searchParams.get("provider"); |
| 27 | + |
| 28 | + if (author !== await checkJWT(provider!, token!)) { |
| 29 | + ctx.throw(401); |
| 30 | + } |
| 31 | + |
| 32 | + const summary = await getHealthSummary(); |
| 33 | + |
| 34 | + ctx.response.headers.set("Access-Control-Allow-Origin", "*"); |
| 35 | + ctx.response.body = { |
| 36 | + total: summary.total, |
| 37 | + healthy: summary.healthy, |
| 38 | + unhealthy: summary.unhealthy, |
| 39 | + containers: summary.containers.map(c => ({ |
| 40 | + name: c.name, |
| 41 | + subdomain: c.subdomain, |
| 42 | + status: c.status, |
| 43 | + cpuPercent: Math.round(c.cpuPercent * 100) / 100, |
| 44 | + memoryPercent: Math.round(c.memoryPercent * 100) / 100, |
| 45 | + memoryUsageMB: Math.round(c.memoryUsage / (1024 * 1024)), |
| 46 | + restartCount: getRestartCount(c.name), |
| 47 | + isHealthy: !isUnhealthy(c), |
| 48 | + lastUpdated: c.lastUpdated.toISOString(), |
| 49 | + })), |
| 50 | + }; |
| 51 | +} |
| 52 | + |
| 53 | + |
| 54 | +export async function getContainerMetrics(ctx: Context): Promise<void> { |
| 55 | + const subdomain = ctx.params.subdomain; |
| 56 | + const stepParam = ctx.request.url.searchParams.get("step") || '1m'; |
| 57 | + const author = ctx.request.url.searchParams.get("user"); |
| 58 | + const token = ctx.request.url.searchParams.get("token"); |
| 59 | + const provider = ctx.request.url.searchParams.get("provider"); |
| 60 | + |
| 61 | + if (author !== await checkJWT(provider!, token!)) { |
| 62 | + ctx.throw(401); |
| 63 | + } |
| 64 | + |
| 65 | + const step = stepParam as TimeStep; |
| 66 | + const range = TIME_RANGE_PRESETS[step] || TIME_RANGE_PRESETS['1m']; |
| 67 | + |
| 68 | + const history = await getContainerHistory(subdomain, range); |
| 69 | + |
| 70 | + ctx.response.headers.set("Access-Control-Allow-Origin", "*"); |
| 71 | + ctx.response.body = { |
| 72 | + subdomain, |
| 73 | + step: range.step, |
| 74 | + duration: range.duration, |
| 75 | + dataPoints: history.cpu.length, |
| 76 | + cpu: history.cpu.map(([ts, val]) => ({ |
| 77 | + timestamp: new Date(ts).toISOString(), |
| 78 | + value: Math.round(val * 100) / 100, |
| 79 | + })), |
| 80 | + memory: history.memory.map(([ts, val]) => ({ |
| 81 | + timestamp: new Date(ts).toISOString(), |
| 82 | + valueMB: Math.round(val / (1024 * 1024)), |
| 83 | + })), |
| 84 | + }; |
| 85 | +} |
| 86 | + |
| 87 | + |
| 88 | +export async function getHealthDashboard(ctx: Context): Promise<void> { |
| 89 | + const author = ctx.request.url.searchParams.get("user"); |
| 90 | + const token = ctx.request.url.searchParams.get("token"); |
| 91 | + const provider = ctx.request.url.searchParams.get("provider"); |
| 92 | + |
| 93 | + if (author !== await checkJWT(provider!, token!)) { |
| 94 | + ctx.throw(401); |
| 95 | + } |
| 96 | + |
| 97 | + const summary = await getHealthSummary(); |
| 98 | + const monitorStatus = getMonitorStatus(); |
| 99 | + |
| 100 | + ctx.response.headers.set("Access-Control-Allow-Origin", "*"); |
| 101 | + ctx.response.body = { |
| 102 | + overview: { |
| 103 | + total: summary.total, |
| 104 | + healthy: summary.healthy, |
| 105 | + unhealthy: summary.unhealthy, |
| 106 | + healthPercent: summary.total > 0 |
| 107 | + ? Math.round((summary.healthy / summary.total) * 100) |
| 108 | + : 100, |
| 109 | + }, |
| 110 | + monitor: { |
| 111 | + running: monitorStatus.running, |
| 112 | + checkIntervalMs: monitorStatus.interval, |
| 113 | + thresholds: monitorStatus.thresholds, |
| 114 | + }, |
| 115 | + unhealthyContainers: summary.containers |
| 116 | + .filter(c => isUnhealthy(c)) |
| 117 | + .map(c => ({ |
| 118 | + name: c.name, |
| 119 | + subdomain: c.subdomain, |
| 120 | + reason: getUnhealthyReason(c), |
| 121 | + restartAttempts: monitorStatus.restartAttempts[c.name]?.count || 0, |
| 122 | + })), |
| 123 | + }; |
| 124 | +} |
| 125 | + |
| 126 | + |
| 127 | +export async function restartContainerHandler(ctx: Context): Promise<void> { |
| 128 | + const subdomain = ctx.params.subdomain; |
| 129 | + |
| 130 | + const body = await ctx.request.body().value; |
| 131 | + let document; |
| 132 | + try { |
| 133 | + document = typeof body === 'string' ? JSON.parse(body) : body; |
| 134 | + } catch { |
| 135 | + document = body; |
| 136 | + } |
| 137 | + |
| 138 | + const author = document?.author; |
| 139 | + const token = document?.token; |
| 140 | + const provider = document?.provider; |
| 141 | + |
| 142 | + if (author !== await checkJWT(provider, token)) { |
| 143 | + ctx.throw(401); |
| 144 | + } |
| 145 | + |
| 146 | + try { |
| 147 | + await restartContainer(subdomain); |
| 148 | + |
| 149 | + ctx.response.headers.set("Access-Control-Allow-Origin", "*"); |
| 150 | + ctx.response.body = { |
| 151 | + status: "success", |
| 152 | + message: `Container ${subdomain} restart initiated`, |
| 153 | + }; |
| 154 | + } catch (error) { |
| 155 | + ctx.response.status = 500; |
| 156 | + ctx.response.body = { |
| 157 | + status: "error", |
| 158 | + message: `Failed to restart ${subdomain}: ${error}`, |
| 159 | + }; |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | + |
| 164 | +export async function triggerHealthCheckHandler(ctx: Context): Promise<void> { |
| 165 | + const body = await ctx.request.body().value; |
| 166 | + let document; |
| 167 | + try { |
| 168 | + document = typeof body === 'string' ? JSON.parse(body) : body; |
| 169 | + } catch { |
| 170 | + document = body; |
| 171 | + } |
| 172 | + |
| 173 | + const ADMIN_LIST = Deno.env.get("ADMIN_LIST")?.split("|") || []; |
| 174 | + const author = document?.author; |
| 175 | + const token = document?.token; |
| 176 | + const provider = document?.provider; |
| 177 | + |
| 178 | + if (author !== await checkJWT(provider, token) || !ADMIN_LIST.includes(author)) { |
| 179 | + ctx.throw(401); |
| 180 | + } |
| 181 | + |
| 182 | + await triggerHealthCheck(); |
| 183 | + |
| 184 | + ctx.response.headers.set("Access-Control-Allow-Origin", "*"); |
| 185 | + ctx.response.body = { |
| 186 | + status: "success", |
| 187 | + message: "Health check triggered", |
| 188 | + }; |
| 189 | +} |
| 190 | + |
| 191 | + |
| 192 | +function getUnhealthyReason(c: { cpuPercent: number; memoryPercent: number; restartCount: number; status: string }): string { |
| 193 | + const reasons: string[] = []; |
| 194 | + |
| 195 | + if (c.cpuPercent > 90) reasons.push(`High CPU (${c.cpuPercent.toFixed(1)}%)`); |
| 196 | + if (c.memoryPercent > 85) reasons.push(`High Memory (${c.memoryPercent.toFixed(1)}%)`); |
| 197 | + if (c.restartCount > 5) reasons.push(`Many restarts (${c.restartCount})`); |
| 198 | + if (c.status === 'exited') reasons.push('Container exited'); |
| 199 | + if (c.status === 'unhealthy') reasons.push('Health check failed'); |
| 200 | + |
| 201 | + return reasons.join(', ') || 'Unknown'; |
| 202 | +} |
0 commit comments