feat(lan): 오류 카운터 기준값 초기화 API + 절전/기상 때 링크 끊김을 이상으로 세지 않음

- POST /api/lan-status/reset: 커널 카운터는 0으로 못 돌려서 기준값을 저장하고 증가분만 표시, 이벤트 로그는 백업 파일로 보관
- 점검 공백(>90초)을 절전/기상으로 감지해 깨어난 직후 90초 동안 링크·핑 이벤트를 억제하고 resume 이벤트로 기록
- 끊김 횟수를 link_flap 이벤트만 세도록 해 down/flap 이중 계산 수정

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-11-21 10:44:07 +09:00
1 parent 4c61af093f
commit efcf1631f6
3 files changed
+53 -14

No files matched your search

+50 -12
View File
@@ -14,6 +14,8 @@ const SAMPLE_MS = 30_000;
const KEEP_SAMPLES = 2880; // 30초 × 2880 = 24시간
const KEEP_EVENTS = 100;
const WAN_TARGET = '1.1.1.1';
const RESUME_GAP_MS = 90_000; // 점검 사이가 이보다 벌어지면 절전에서 깨어난 것으로 본다
const QUIET_AFTER_RESUME_MS = 90_000; // 깨어난 직후 이 시간 동안은 링크 끊김·핑 손실을 이상으로 세지 않는다
export interface NicState {
name: string;
@@ -36,6 +38,14 @@ const events: LanEvent[] = [];
let logPath = '';
let timer: NodeJS.Timeout | null = null;
let busy = false;
let quietUntil = 0;
// 오류 카운터는 커널이 0으로 되돌릴 수 없어서(드라이버 재적재 필요), "기준값"을 저장해 두고 그 이후 증가분만 보여 준다.
type Base = Pick<NicState, 'rx_errors' | 'rx_dropped' | 'rx_crc_errors' | 'tx_errors' | 'tx_dropped' | 'carrier_changes'>;
let baseline: Record<string, Base> = {};
let baselineTs = 0;
let baselinePath = '';
let eventsLogDir = '';
function readNum(p: string): number | null {
try { const n = Number(fs.readFileSync(p, 'utf8').trim()); return Number.isFinite(n) ? n : null; } catch { return null; }
@@ -108,22 +118,29 @@ async function sampleOnce() {
const [gateway, wan] = await Promise.all([gw ? ping(gw) : Promise.resolve(null), ping(WAN_TARGET)]);
const cur: LanSample = { ts: Date.now(), nics, gateway, wan };
const prev = samples[samples.length - 1];
// 절전/기상 감지: 점검은 30초마다 도는데 공백이 크게 벌어지면 서버가 잠들었다 깨어난 것이다.
// 깨어난 직후 1분 동안은 랜 링크가 100→1000M으로 다시 협상하며 몇 초 끊기는 게 정상이라 이상으로 세지 않는다.
if (prev && cur.ts - prev.ts > RESUME_GAP_MS) {
quietUntil = cur.ts + QUIET_AFTER_RESUME_MS;
addEvent('resume', `절전/기상 (점검 공백 ${Math.round((cur.ts - prev.ts) / 60000)}분)`);
}
const quiet = cur.ts < quietUntil;
if (prev) {
for (const n of nics) {
const p = prev.nics.find(x => x.name === n.name);
if (!p) continue;
if (n.carrier_changes > p.carrier_changes) addEvent('link_flap', `${n.name} 링크 끊김/복구 ${n.carrier_changes - p.carrier_changes}회`);
if (p.up && !n.up) addEvent('link_down', `${n.name} 링크 내려감`);
if (!p.up && n.up) addEvent('link_up', `${n.name} 링크 올라옴`);
if (p.speed_mbps && n.speed_mbps && n.speed_mbps < p.speed_mbps) addEvent('speed_drop', `${n.name} 속도 ${p.speed_mbps}→${n.speed_mbps}Mbps`);
if (!quiet && n.carrier_changes > p.carrier_changes) addEvent('link_flap', `${n.name} 링크 끊김/복구 ${n.carrier_changes - p.carrier_changes}회`);
if (!quiet && p.up && !n.up) addEvent('link_down', `${n.name} 링크 내려감`);
if (!quiet && !p.up && n.up) addEvent('link_up', `${n.name} 링크 올라옴`);
if (!quiet && p.speed_mbps && n.speed_mbps && n.speed_mbps < p.speed_mbps) addEvent('speed_drop', `${n.name} 속도 ${p.speed_mbps}→${n.speed_mbps}Mbps`);
if (n.rx_crc_errors > p.rx_crc_errors) addEvent('crc_errors', `${n.name} CRC 오류 +${n.rx_crc_errors - p.rx_crc_errors}`);
}
const lanBad = !!gateway && gateway.loss_pct > 0, lanBadPrev = !!prev.gateway && prev.gateway.loss_pct > 0;
if (lanBad && !lanBadPrev) addEvent('lan_loss', `공유기 핑 손실 ${gateway!.loss_pct}%`);
if (!lanBad && lanBadPrev) addEvent('lan_ok', '공유기 핑 복구');
if (!quiet && lanBad && !lanBadPrev) addEvent('lan_loss', `공유기 핑 손실 ${gateway!.loss_pct}%`);
if (!quiet && !lanBad && lanBadPrev) addEvent('lan_ok', '공유기 핑 복구');
const wanBad = !!wan && wan.loss_pct >= 50, wanBadPrev = !!prev.wan && prev.wan.loss_pct >= 50;
if (wanBad && !wanBadPrev) addEvent('wan_down', `인터넷 핑 손실 ${wan!.loss_pct}%`);
if (!wanBad && wanBadPrev) addEvent('wan_ok', '인터넷 핑 복구');
if (!quiet && wanBad && !wanBadPrev) addEvent('wan_down', `인터넷 핑 손실 ${wan!.loss_pct}%`);
if (!quiet && !wanBad && wanBadPrev) addEvent('wan_ok', '인터넷 핑 복구');
}
samples.push(cur);
if (samples.length > KEEP_SAMPLES) samples.shift();
@@ -133,23 +150,41 @@ async function sampleOnce() {
export function startNetHealth(logDir: string) {
if (timer) return;
try { fs.mkdirSync(logDir, { recursive: true }); logPath = path.join(logDir, 'lan-events.jsonl'); } catch { logPath = ''; }
eventsLogDir = logDir;
baselinePath = path.join(logDir, 'lan-baseline.json');
try { const b = JSON.parse(fs.readFileSync(baselinePath, 'utf8')); baseline = b.nics || {}; baselineTs = Number(b.ts) || 0; } catch { /* 기준값 없음 */ }
void sampleOnce();
timer = setInterval(() => void sampleOnce(), SAMPLE_MS);
timer.unref();
}
/** 오류 기록을 지우고 지금부터 다시 센다: 이벤트·24시간 요약을 비우고 현재 카운터를 기준값으로 저장한다. */
export function resetLanCounters() {
const nics = listNics().map(readNic);
baseline = {};
for (const n of nics) baseline[n.name] = { rx_errors: n.rx_errors, rx_dropped: n.rx_dropped, rx_crc_errors: n.rx_crc_errors, tx_errors: n.tx_errors, tx_dropped: n.tx_dropped, carrier_changes: n.carrier_changes };
baselineTs = Date.now();
events.length = 0;
try {
if (logPath && fs.existsSync(logPath)) fs.renameSync(logPath, path.join(eventsLogDir, `lan-events.${new Date().toISOString().replace(/[:.]/g, '-')}.bak.jsonl`));
} catch { /* 보관 실패는 무시 */ }
try { if (baselinePath) fs.writeFileSync(baselinePath, JSON.stringify({ ts: baselineTs, nics: baseline })); } catch { /* 저장 실패는 무시 */ }
return { reset_at: baselineTs, nics: nics.map(n => n.name) };
}
/** 화면용 요약. status: ok(정상) / warn(최근 24시간 이상 있음) / bad(지금 문제) / unknown */
export function getLanStatus() {
const last = samples[samples.length - 1];
if (!last) return { status: 'unknown', label: '확인 중', nics: [], gateway: null, wan: null, events: [], summary: null };
const dayAgo = Date.now() - 24 * 3600_000;
const dayAgo = Math.max(Date.now() - 24 * 3600_000, baselineTs);
const recent = samples.filter(s => s.ts >= dayAgo);
const ev24 = events.filter(e => e.ts >= dayAgo);
const primary = last.nics.filter(n => n.up).sort((a, b) => (b.speed_mbps ?? 0) - (a.speed_mbps ?? 0))[0];
const speed = primary?.speed_mbps ?? null;
const lossSamples = recent.filter(s => s.gateway && s.gateway.loss_pct > 0).length;
const wanSamples = recent.filter(s => s.wan && s.wan.loss_pct >= 50).length;
const flaps = ev24.filter(e => e.kind === 'link_flap' || e.kind === 'link_down').length;
const flaps = ev24.filter(e => e.kind === 'link_flap').length;
const resumes = ev24.filter(e => e.kind === 'resume').length;
const speedDrops = ev24.filter(e => e.kind === 'speed_drop').length;
const nowBad = !primary || (last.gateway?.loss_pct ?? 0) >= 50 || (last.wan?.loss_pct ?? 100) >= 50;
const warn = flaps > 0 || speedDrops > 0 || lossSamples > 0 || wanSamples > 0 || (speed != null && speed < 1000);
@@ -157,10 +192,13 @@ export function getLanStatus() {
const label = primary ? `${speed != null ? speed + 'M' : '링크'}${flaps ? ` · 끊김 ${flaps}` : ''}` : '연결 끊김';
return {
status, label,
nics: last.nics,
nics: last.nics.map(n => {
const b = baseline[n.name];
return b ? { ...n, rx_errors: Math.max(0, n.rx_errors - b.rx_errors), rx_dropped: Math.max(0, n.rx_dropped - b.rx_dropped), rx_crc_errors: Math.max(0, n.rx_crc_errors - b.rx_crc_errors), tx_errors: Math.max(0, n.tx_errors - b.tx_errors), tx_dropped: Math.max(0, n.tx_dropped - b.tx_dropped), carrier_changes: Math.max(0, n.carrier_changes - b.carrier_changes) } : n;
}),
gateway: last.gateway,
wan: last.wan,
summary: { window_hours: 24, samples: recent.length, flaps, speed_drops: speedDrops, lan_loss_samples: lossSamples, wan_down_samples: wanSamples },
summary: { since: dayAgo, resumes, window_hours: 24, samples: recent.length, flaps, speed_drops: speedDrops, lan_loss_samples: lossSamples, wan_down_samples: wanSamples },
events: ev24.slice(-10).reverse(),
updated: last.ts,
};
+2 -1
View File
@@ -61,7 +61,7 @@ import { registerSkillsRoutes } from './routes/routes-skills';
import { registerCodeRoutes } from './routes/routes-code';
import { registerClaudeFsRoutes } from './routes/routes-claude-fs';
import { getBuildInfo, buildLabel } from './build-info';
import { startNetHealth, getLanStatus } from './net-health';
import { startNetHealth, getLanStatus, resetLanCounters } from './net-health';
import { skillContextBudget } from './chat/skill-context-budget';
import { ptyStore, ptyAppend, ptyAttach, ptyDetach, cleanPtyKey, cleanPtyMode, listPtySessions } from './pty-store';
import { ptyAccessDecision, resolveWorkshopCwd, resolvePcbCwd, allowedAutorun } from './pty-guard';
@@ -3872,6 +3872,7 @@ updateNetSpeed();
setInterval(updateNetSpeed, 2000);
startNetHealth(path.join(CONFIG_DIR_PATH, 'logs'));
app.get('/api/lan-status', (_req, res) => { res.json(getLanStatus()); });
app.post('/api/lan-status/reset', (_req, res) => { res.json(resetLanCounters()); });
// ──────────────────────────────────────────────────────────────────────────
app.get('/api/system-stats', async (req, res) => {
+1 -1
View File
@@ -1162,7 +1162,7 @@ function renderLanStatus(lan) {
const nics = (lan.nics || []).map(n => `${n.name}: ${n.up ? (n.speed_mbps ? n.speed_mbps + 'Mbps ' + n.duplex : '링크 올라옴') : '끊김'} (오류 ${n.rx_errors + n.tx_errors}, CRC ${n.rx_crc_errors}, 링크전환 ${n.carrier_changes})`);
const gw = lan.gateway ? `공유기 ${lan.gateway.avg_ms ?? '-'}ms 손실 ${lan.gateway.loss_pct}%` : '공유기 없음';
const wan = lan.wan ? `인터넷 ${lan.wan.avg_ms ?? '-'}ms 손실 ${lan.wan.loss_pct}%` : '';
const sm = lan.summary ? `최근 24시간: 링크 끊김 ${lan.summary.flaps} · 속도 하락 ${lan.summary.speed_drops} · 공유기 손실 ${lan.summary.lan_loss_samples}회 · 인터넷 끊김 ${lan.summary.wan_down_samples}회` : '';
const sm = lan.summary ? `${new Date(lan.summary.since).toLocaleString()} 이후: 링크 끊김 ${lan.summary.flaps} · 절전/기상 ${lan.summary.resumes || 0} · 속도 하락 ${lan.summary.speed_drops} · 공유기 손실 ${lan.summary.lan_loss_samples}회 · 인터넷 끊김 ${lan.summary.wan_down_samples}회` : '';
const evs = (lan.events || []).slice(0, 5).map(e => `${new Date(e.ts).toLocaleTimeString()} ${e.detail}`);
row.title = [...nics, gw, wan, sm, ...(evs.length ? ['— 최근 이벤트 —', ...evs] : [])].filter(Boolean).join('\n');
}