로컬(개발)용과 운영용 설정분리

This commit is contained in:
2025-12-28 13:45:41 +09:00
parent a871ec8008
commit 716f4f8791
15 changed files with 661 additions and 368 deletions

View File

@@ -1,4 +1,4 @@
import { getDb } from './db'
import { query, queryOne, execute, getPool } from './db'
interface ServerTarget {
target_id: number
@@ -60,20 +60,19 @@ async function detectApiVersion(baseUrl: string, serverName: string): Promise<st
// 이상감지 실행
async function detectAnomalies(targetId: number, serverName: string) {
const db = getDb()
const now = timestamp()
try {
// === 단기 변화율 감지 ===
const SHORT_TERM_THRESHOLD = 30
const snapshots = db.prepare(`
const snapshots = await query<any>(`
SELECT cpu_percent, memory_percent
FROM server_snapshots
WHERE target_id = ? AND is_online = 1
WHERE target_id = $1 AND is_online = 1
ORDER BY collected_at DESC
LIMIT 20
`).all(targetId) as any[]
`, [targetId])
if (snapshots.length >= 4) {
const half = Math.floor(snapshots.length / 2)
@@ -88,39 +87,46 @@ async function detectAnomalies(targetId: number, serverName: string) {
const cpuChange = prevCpuAvg > 1 ? ((currCpuAvg - prevCpuAvg) / prevCpuAvg) * 100 : currCpuAvg - prevCpuAvg
const memChange = prevMemAvg > 1 ? ((currMemAvg - prevMemAvg) / prevMemAvg) * 100 : currMemAvg - prevMemAvg
// 중복 체크용
const recentLogExists = db.prepare(`
SELECT 1 FROM anomaly_logs
WHERE target_id = ? AND detect_type = ? AND metric = ?
AND detected_at > datetime('now', '-1 minute', 'localtime')
LIMIT 1
`)
const insertLog = db.prepare(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`)
// CPU 단기 변화율 체크
if (Math.abs(cpuChange) >= SHORT_TERM_THRESHOLD) {
const level = Math.abs(cpuChange) >= 100 ? 'danger' : 'warning'
const direction = cpuChange >= 0 ? '증가' : '감소'
const message = `CPU ${direction} 감지 (${prevCpuAvg.toFixed(1)}% → ${currCpuAvg.toFixed(1)}%)`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'short-term' AND metric = 'CPU'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!recentLogExists.get(targetId, 'short-term', 'CPU')) {
insertLog.run(targetId, serverName, 'short-term', 'CPU', level, currCpuAvg, cpuChange, message)
if (!recentExists) {
const level = Math.abs(cpuChange) >= 100 ? 'danger' : 'warning'
const direction = cpuChange >= 0 ? '증가' : '감소'
const message = `CPU ${direction} 감지 (${prevCpuAvg.toFixed(1)}% → ${currCpuAvg.toFixed(1)}%)`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'short-term', 'CPU', $3, $4, $5, $6)
`, [targetId, serverName, level, currCpuAvg, cpuChange, message])
console.log(`[${now}] 🚨 [${serverName}] 단기변화율 이상감지: CPU ${cpuChange.toFixed(1)}% (${level})`)
}
}
// Memory 단기 변화율 체크
if (Math.abs(memChange) >= SHORT_TERM_THRESHOLD) {
const level = Math.abs(memChange) >= 100 ? 'danger' : 'warning'
const direction = memChange >= 0 ? '증가' : '감소'
const message = `Memory ${direction} 감지 (${prevMemAvg.toFixed(1)}% → ${currMemAvg.toFixed(1)}%)`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'short-term' AND metric = 'Memory'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!recentLogExists.get(targetId, 'short-term', 'Memory')) {
insertLog.run(targetId, serverName, 'short-term', 'Memory', level, currMemAvg, memChange, message)
if (!recentExists) {
const level = Math.abs(memChange) >= 100 ? 'danger' : 'warning'
const direction = memChange >= 0 ? '증가' : '감소'
const message = `Memory ${direction} 감지 (${prevMemAvg.toFixed(1)}% → ${currMemAvg.toFixed(1)}%)`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'short-term', 'Memory', $3, $4, $5, $6)
`, [targetId, serverName, level, currMemAvg, memChange, message])
console.log(`[${now}] 🚨 [${serverName}] 단기변화율 이상감지: Memory ${memChange.toFixed(1)}% (${level})`)
}
}
@@ -130,13 +136,13 @@ async function detectAnomalies(targetId: number, serverName: string) {
const WARNING_Z = 2.0
const DANGER_Z = 3.0
const hourSnapshots = db.prepare(`
const hourSnapshots = await query<any>(`
SELECT cpu_percent, memory_percent
FROM server_snapshots
WHERE target_id = ? AND is_online = 1
AND collected_at >= datetime('now', '-1 hour', 'localtime')
WHERE target_id = $1 AND is_online = 1
AND collected_at >= NOW() - INTERVAL '1 hour'
ORDER BY collected_at DESC
`).all(targetId) as any[]
`, [targetId])
if (hourSnapshots.length >= 10) {
const current = hourSnapshots[0]
@@ -157,43 +163,51 @@ async function detectAnomalies(targetId: number, serverName: string) {
const cpuZscore = cpuStd > 0.1 ? (currCpu - cpuAvg) / cpuStd : 0
const memZscore = memStd > 0.1 ? (currMem - memAvg) / memStd : 0
const recentLogExists = db.prepare(`
SELECT 1 FROM anomaly_logs
WHERE target_id = ? AND detect_type = 'zscore' AND metric = ?
AND detected_at > datetime('now', '-1 minute', 'localtime')
LIMIT 1
`)
const insertLog = db.prepare(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES (?, ?, 'zscore', ?, ?, ?, ?, ?)
`)
// CPU Z-Score 체크
if (Math.abs(cpuZscore) >= WARNING_Z) {
const level = Math.abs(cpuZscore) >= DANGER_Z ? 'danger' : 'warning'
const direction = cpuZscore >= 0 ? '높음' : '낮음'
const message = `CPU 평균 대비 ${Math.abs(cpuZscore).toFixed(1)}σ ${direction} (평균: ${cpuAvg.toFixed(1)}%, 현재: ${currCpu.toFixed(1)}%)`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'zscore' AND metric = 'CPU'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!recentLogExists.get(targetId, 'CPU')) {
insertLog.run(targetId, serverName, 'CPU', level, currCpu, cpuZscore, message)
if (!recentExists) {
const level = Math.abs(cpuZscore) >= DANGER_Z ? 'danger' : 'warning'
const direction = cpuZscore >= 0 ? '높음' : '낮음'
const message = `CPU 평균 대비 ${Math.abs(cpuZscore).toFixed(1)}σ ${direction} (평균: ${cpuAvg.toFixed(1)}%, 현재: ${currCpu.toFixed(1)}%)`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'zscore', 'CPU', $3, $4, $5, $6)
`, [targetId, serverName, level, currCpu, cpuZscore, message])
console.log(`[${now}] 🚨 [${serverName}] Z-Score 이상감지: CPU Z=${cpuZscore.toFixed(2)} (${level})`)
}
}
// Memory Z-Score 체크
if (Math.abs(memZscore) >= WARNING_Z) {
const level = Math.abs(memZscore) >= DANGER_Z ? 'danger' : 'warning'
const direction = memZscore >= 0 ? '높음' : '낮음'
const message = `Memory 평균 대비 ${Math.abs(memZscore).toFixed(1)}σ ${direction} (평균: ${memAvg.toFixed(1)}%, 현재: ${currMem.toFixed(1)}%)`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'zscore' AND metric = 'Memory'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!recentLogExists.get(targetId, 'Memory')) {
insertLog.run(targetId, serverName, 'Memory', level, currMem, memZscore, message)
if (!recentExists) {
const level = Math.abs(memZscore) >= DANGER_Z ? 'danger' : 'warning'
const direction = memZscore >= 0 ? '높음' : '낮음'
const message = `Memory 평균 대비 ${Math.abs(memZscore).toFixed(1)}σ ${direction} (평균: ${memAvg.toFixed(1)}%, 현재: ${currMem.toFixed(1)}%)`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'zscore', 'Memory', $3, $4, $5, $6)
`, [targetId, serverName, level, currMem, memZscore, message])
console.log(`[${now}] 🚨 [${serverName}] Z-Score 이상감지: Memory Z=${memZscore.toFixed(2)} (${level})`)
}
}
}
// === 시간대별 베이스라인 감지 ===
const DEVIATION_THRESHOLD = 2.0
const currentHour = new Date().getHours()
@@ -201,25 +215,25 @@ async function detectAnomalies(targetId: number, serverName: string) {
const isWeekend = currentDayOfWeek === 0 || currentDayOfWeek === 6
const dayType = isWeekend ? 'weekend' : 'weekday'
const baselineData = db.prepare(`
const baselineData = await query<any>(`
SELECT cpu_percent, memory_percent
FROM server_snapshots
WHERE target_id = ? AND is_online = 1
AND collected_at >= datetime('now', '-14 days', 'localtime')
AND strftime('%H', collected_at) = ?
WHERE target_id = $1 AND is_online = 1
AND collected_at >= NOW() - INTERVAL '14 days'
AND EXTRACT(HOUR FROM collected_at) = $2
AND (
(? = 'weekend' AND strftime('%w', collected_at) IN ('0', '6'))
($3 = 'weekend' AND EXTRACT(DOW FROM collected_at) IN (0, 6))
OR
(? = 'weekday' AND strftime('%w', collected_at) NOT IN ('0', '6'))
($3 = 'weekday' AND EXTRACT(DOW FROM collected_at) NOT IN (0, 6))
)
`).all(targetId, currentHour.toString().padStart(2, '0'), dayType, dayType) as any[]
`, [targetId, currentHour, dayType])
const currentSnapshot = db.prepare(`
const currentSnapshot = await queryOne<any>(`
SELECT cpu_percent, memory_percent
FROM server_snapshots
WHERE target_id = ? AND is_online = 1
WHERE target_id = $1 AND is_online = 1
ORDER BY collected_at DESC LIMIT 1
`).get(targetId) as any
`, [targetId])
if (baselineData.length >= 5 && currentSnapshot) {
const currCpu = currentSnapshot.cpu_percent ?? 0
@@ -239,38 +253,46 @@ async function detectAnomalies(targetId: number, serverName: string) {
const cpuDeviation = cpuStd > 0.1 ? (currCpu - cpuAvg) / cpuStd : 0
const memDeviation = memStd > 0.1 ? (currMem - memAvg) / memStd : 0
const baselineLogExists = db.prepare(`
SELECT 1 FROM anomaly_logs
WHERE target_id = ? AND detect_type = 'baseline' AND metric = ?
AND detected_at > datetime('now', '-1 minute', 'localtime')
LIMIT 1
`)
const baselineInsertLog = db.prepare(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES (?, ?, 'baseline', ?, ?, ?, ?, ?)
`)
if (Math.abs(cpuDeviation) >= DEVIATION_THRESHOLD) {
const level = Math.abs(cpuDeviation) >= 3.0 ? 'danger' : 'warning'
const direction = cpuDeviation >= 0 ? '높음' : '낮음'
const dayLabel = isWeekend ? '주말' : '평일'
const message = `CPU ${dayLabel} ${currentHour}시 베이스라인 대비 ${Math.abs(cpuDeviation).toFixed(1)}σ ${direction}`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'baseline' AND metric = 'CPU'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!baselineLogExists.get(targetId, 'CPU')) {
baselineInsertLog.run(targetId, serverName, 'CPU', level, currCpu, cpuDeviation, message)
if (!recentExists) {
const level = Math.abs(cpuDeviation) >= 3.0 ? 'danger' : 'warning'
const direction = cpuDeviation >= 0 ? '높음' : '낮음'
const dayLabel = isWeekend ? '주말' : '평일'
const message = `CPU ${dayLabel} ${currentHour}시 베이스라인 대비 ${Math.abs(cpuDeviation).toFixed(1)}σ ${direction}`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'baseline', 'CPU', $3, $4, $5, $6)
`, [targetId, serverName, level, currCpu, cpuDeviation, message])
console.log(`[${now}] 🚨 [${serverName}] 베이스라인 이상감지: CPU σ=${cpuDeviation.toFixed(2)} (${level})`)
}
}
if (Math.abs(memDeviation) >= DEVIATION_THRESHOLD) {
const level = Math.abs(memDeviation) >= 3.0 ? 'danger' : 'warning'
const direction = memDeviation >= 0 ? '높음' : '낮음'
const dayLabel = isWeekend ? '주말' : '평일'
const message = `Memory ${dayLabel} ${currentHour}시 베이스라인 대비 ${Math.abs(memDeviation).toFixed(1)}σ ${direction}`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'baseline' AND metric = 'Memory'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!baselineLogExists.get(targetId, 'Memory')) {
baselineInsertLog.run(targetId, serverName, 'Memory', level, currMem, memDeviation, message)
if (!recentExists) {
const level = Math.abs(memDeviation) >= 3.0 ? 'danger' : 'warning'
const direction = memDeviation >= 0 ? '높음' : '낮음'
const dayLabel = isWeekend ? '주말' : '평일'
const message = `Memory ${dayLabel} ${currentHour}시 베이스라인 대비 ${Math.abs(memDeviation).toFixed(1)}σ ${direction}`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'baseline', 'Memory', $3, $4, $5, $6)
`, [targetId, serverName, level, currMem, memDeviation, message])
console.log(`[${now}] 🚨 [${serverName}] 베이스라인 이상감지: Memory σ=${memDeviation.toFixed(2)} (${level})`)
}
}
@@ -280,13 +302,13 @@ async function detectAnomalies(targetId: number, serverName: string) {
const SLOPE_THRESHOLD = 0.5
const WINDOW_MINUTES = 30
const trendSnapshots = db.prepare(`
const trendSnapshots = await query<any>(`
SELECT cpu_percent, memory_percent
FROM server_snapshots
WHERE target_id = ? AND is_online = 1
AND collected_at >= datetime('now', '-${WINDOW_MINUTES} minutes', 'localtime')
WHERE target_id = $1 AND is_online = 1
AND collected_at >= NOW() - INTERVAL '${WINDOW_MINUTES} minutes'
ORDER BY collected_at ASC
`).all(targetId) as any[]
`, [targetId])
if (trendSnapshots.length >= 10) {
const n = trendSnapshots.length
@@ -315,34 +337,42 @@ async function detectAnomalies(targetId: number, serverName: string) {
const cpuResult = calcSlope(trendSnapshots.map(s => s.cpu_percent ?? 0))
const memResult = calcSlope(trendSnapshots.map(s => s.memory_percent ?? 0))
const trendLogExists = db.prepare(`
SELECT 1 FROM anomaly_logs
WHERE target_id = ? AND detect_type = 'trend' AND metric = ?
AND detected_at > datetime('now', '-1 minute', 'localtime')
LIMIT 1
`)
const trendInsertLog = db.prepare(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES (?, ?, 'trend', ?, ?, ?, ?, ?)
`)
if (cpuResult.slope >= SLOPE_THRESHOLD && cpuResult.r2 >= 0.3) {
const level = cpuResult.slope >= 1.0 ? 'danger' : 'warning'
const message = `CPU 지속 상승 중 (분당 +${cpuResult.slope.toFixed(2)}%, R²=${cpuResult.r2.toFixed(2)})`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'trend' AND metric = 'CPU'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!trendLogExists.get(targetId, 'CPU')) {
trendInsertLog.run(targetId, serverName, 'CPU', level, currCpu, cpuResult.slope, message)
if (!recentExists) {
const level = cpuResult.slope >= 1.0 ? 'danger' : 'warning'
const message = `CPU 지속 상승 중 (분당 +${cpuResult.slope.toFixed(2)}%, R²=${cpuResult.r2.toFixed(2)})`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'trend', 'CPU', $3, $4, $5, $6)
`, [targetId, serverName, level, currCpu, cpuResult.slope, message])
console.log(`[${now}] 🚨 [${serverName}] 추세 이상감지: CPU +${cpuResult.slope.toFixed(2)}/분 (${level})`)
}
}
if (memResult.slope >= SLOPE_THRESHOLD && memResult.r2 >= 0.3) {
const level = memResult.slope >= 1.0 ? 'danger' : 'warning'
const message = `Memory 지속 상승 중 (분당 +${memResult.slope.toFixed(2)}%, R²=${memResult.r2.toFixed(2)})`
const recentExists = await queryOne(`
SELECT 1 FROM anomaly_logs
WHERE target_id = $1 AND detect_type = 'trend' AND metric = 'Memory'
AND detected_at > NOW() - INTERVAL '1 minute'
LIMIT 1
`, [targetId])
if (!trendLogExists.get(targetId, 'Memory')) {
trendInsertLog.run(targetId, serverName, 'Memory', level, currMem, memResult.slope, message)
if (!recentExists) {
const level = memResult.slope >= 1.0 ? 'danger' : 'warning'
const message = `Memory 지속 상승 중 (분당 +${memResult.slope.toFixed(2)}%, R²=${memResult.r2.toFixed(2)})`
await execute(`
INSERT INTO anomaly_logs (target_id, server_name, detect_type, metric, level, current_value, threshold_value, message)
VALUES ($1, $2, 'trend', 'Memory', $3, $4, $5, $6)
`, [targetId, serverName, level, currMem, memResult.slope, message])
console.log(`[${now}] 🚨 [${serverName}] 추세 이상감지: Memory +${memResult.slope.toFixed(2)}/분 (${level})`)
}
}
@@ -353,9 +383,9 @@ async function detectAnomalies(targetId: number, serverName: string) {
}
}
// 서버 데이터 수집
async function collectServerData(target: ServerTarget) {
const db = getDb()
const now = timestamp()
console.log(`[${now}] 📡 [${target.server_name}] 수집 시작... (${target.glances_url})`)
@@ -373,10 +403,10 @@ async function collectServerData(target: ServerTarget) {
if (!apiVersion) {
console.log(`[${now}] ❌ [${target.server_name}] 연결 실패 - Offline 기록`)
db.prepare(`
await execute(`
INSERT INTO server_snapshots (target_id, is_online, collected_at)
VALUES (?, 0, ?)
`).run(target.target_id, now)
VALUES ($1, 0, $2)
`, [target.target_id, now])
return
}
@@ -403,10 +433,10 @@ async function collectServerData(target: ServerTarget) {
// 캐시 클리어 후 재시도 위해
apiVersionCache.delete(target.target_id)
console.log(`[${now}] ❌ [${target.server_name}] 연결 실패 - Offline 기록`)
db.prepare(`
await execute(`
INSERT INTO server_snapshots (target_id, is_online, collected_at)
VALUES (?, 0, ?)
`).run(target.target_id, now)
VALUES ($1, 0, $2)
`, [target.target_id, now])
return
}
@@ -423,16 +453,17 @@ async function collectServerData(target: ServerTarget) {
cpuTemp = tempSensor?.value ?? null
}
// server_snapshots INSERT (api_version 포함)
// server_snapshots INSERT
console.log(`[${now}] 💾 [${target.server_name}] snapshot 저장 (API v${apiVersion}, CPU: ${cpu?.total?.toFixed(1) || 0}%, MEM: ${mem?.percent?.toFixed(1) || 0}%, TEMP: ${cpuTemp ?? 'N/A'}°C, LOAD: ${quicklook?.load?.toFixed(1) ?? 'N/A'}%)`)
db.prepare(`
await execute(`
INSERT INTO server_snapshots (
target_id, os_name, os_version, host_name, uptime_seconds, uptime_str, ip_address,
cpu_name, cpu_count, cpu_percent, memory_total, memory_used, memory_percent,
swap_total, swap_used, swap_percent, is_online, api_version, cpu_temp,
load_1, load_5, load_15, load_percent, collected_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)
`, [
target.target_id,
system?.os_name || system?.linux_distro || null,
system?.os_version || null,
@@ -457,19 +488,18 @@ async function collectServerData(target: ServerTarget) {
load?.min15 ?? null,
quicklook?.load ?? null,
now
)
])
// server_disks INSERT (배열)
if (Array.isArray(fs) && fs.length > 0) {
console.log(`[${now}] 💾 [${target.server_name}] disk 저장 (${fs.length}개 파티션)`)
const diskStmt = db.prepare(`
INSERT INTO server_disks (
target_id, device_name, mount_point, fs_type,
disk_total, disk_used, disk_percent, collected_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`)
for (const disk of fs) {
diskStmt.run(
await execute(`
INSERT INTO server_disks (
target_id, device_name, mount_point, fs_type,
disk_total, disk_used, disk_percent, collected_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
`, [
target.target_id,
disk.device_name || null,
disk.mnt_point || null,
@@ -478,22 +508,21 @@ async function collectServerData(target: ServerTarget) {
disk.used || null,
disk.percent || null,
now
)
])
}
}
// server_containers INSERT (배열)
if (Array.isArray(docker) && docker.length > 0) {
console.log(`[${now}] 🐳 [${target.server_name}] container 저장 (${docker.length}개 컨테이너)`)
const containerStmt = db.prepare(`
INSERT INTO server_containers (
target_id, docker_id, container_name, container_image,
container_status, cpu_percent, memory_usage, memory_limit,
memory_percent, uptime, network_rx, network_tx, collected_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
for (const container of docker) {
containerStmt.run(
await execute(`
INSERT INTO server_containers (
target_id, docker_id, container_name, container_image,
container_status, cpu_percent, memory_usage, memory_limit,
memory_percent, uptime, network_rx, network_tx, collected_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
`, [
target.target_id,
container.id || null,
container.name || null,
@@ -509,22 +538,21 @@ async function collectServerData(target: ServerTarget) {
container.network?.rx ?? container.network_rx ?? null,
container.network?.tx ?? container.network_tx ?? null,
now
)
])
}
}
// server_networks INSERT (배열)
if (Array.isArray(network) && network.length > 0) {
console.log(`[${now}] 🌐 [${target.server_name}] network 저장 (${network.length}개 인터페이스)`)
const netStmt = db.prepare(`
INSERT INTO server_networks (
target_id, interface_name, bytes_recv, bytes_sent,
packets_recv, packets_sent, speed_recv, speed_sent,
is_up, collected_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
for (const iface of network) {
netStmt.run(
await execute(`
INSERT INTO server_networks (
target_id, interface_name, bytes_recv, bytes_sent,
packets_recv, packets_sent, speed_recv, speed_sent,
is_up, collected_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
`, [
target.target_id,
iface.interface_name || null,
iface.bytes_recv || iface.cumulative_rx || null,
@@ -535,7 +563,7 @@ async function collectServerData(target: ServerTarget) {
iface.bytes_sent_rate_per_sec || iface.tx || iface.bytes_sent_rate || null,
iface.is_up ? 1 : 0,
now
)
])
}
}
@@ -551,13 +579,14 @@ async function collectServerData(target: ServerTarget) {
apiVersionCache.delete(target.target_id)
// 오프라인 기록
db.prepare(`
await execute(`
INSERT INTO server_snapshots (target_id, is_online, collected_at)
VALUES (?, 0, ?)
`).run(target.target_id, now)
VALUES ($1, 0, $2)
`, [target.target_id, now])
}
}
// 서버별 타이머 시작
function startServerTimer(target: ServerTarget) {
const now = timestamp()
@@ -591,7 +620,7 @@ function stopServerTimer(targetId: number) {
}
// 스케줄러 시작 (모든 활성 서버)
export function startServerScheduler() {
export async function startServerScheduler() {
const now = timestamp()
if (isRunning) {
@@ -601,10 +630,9 @@ export function startServerScheduler() {
console.log(`[${now}] 🚀 [Server Scheduler] ========== 스케줄러 시작 ==========`)
const db = getDb()
const targets = db.prepare(`
const targets = await query<ServerTarget>(`
SELECT * FROM server_targets WHERE is_active = 1
`).all() as ServerTarget[]
`)
console.log(`[${now}] 📋 [Server Scheduler] 활성 서버: ${targets.length}`)
@@ -632,12 +660,11 @@ export function stopServerScheduler() {
}
// 스케줄러 상태
export function getServerSchedulerStatus() {
const db = getDb()
export async function getServerSchedulerStatus() {
const activeServers = serverTimers.size
const targets = db.prepare(`
const targets = await query<ServerTarget>(`
SELECT * FROM server_targets WHERE is_active = 1
`).all() as ServerTarget[]
`)
return {
is_running: isRunning,
@@ -655,12 +682,11 @@ export function getServerSchedulerStatus() {
}
// 특정 서버 타이머 갱신 (설정 변경 시)
export function refreshServerTimer(targetId: number) {
export async function refreshServerTimer(targetId: number) {
const now = timestamp()
const db = getDb()
const target = db.prepare(`
SELECT * FROM server_targets WHERE target_id = ? AND is_active = 1
`).get(targetId) as ServerTarget | undefined
const target = await queryOne<ServerTarget>(`
SELECT * FROM server_targets WHERE target_id = $1 AND is_active = 1
`, [targetId])
if (target && isRunning) {
console.log(`[${now}] 🔄 [${target.server_name}] 타이머 갱신`)