From 4c61af093fcd713b87e96b0354d2a885a6250fdd Mon Sep 17 00:00:00 2001 From: kim Date: Fri, 20 Nov 2026 22:57:27 +0900 Subject: [PATCH] =?UTF-8?q?feat(lan):=20=EC=9C=A0=EC=84=A0=20NIC=20?= =?UTF-8?q?=EC=83=81=ED=83=9C=20=EC=A3=BC=EA=B8=B0=20=EC=A0=90=EA=B2=80=20?= =?UTF-8?q?+=20=EC=82=AC=EC=9D=B4=EB=93=9C=EB=B0=94=20LAN=20=ED=96=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 링크 속도·끊김 횟수·CRC/오류 카운터와 공유기(LAN)/인터넷(WAN) 핑 손실을 30초마다 점검하고, 이벤트(링크 끊김·속도 하락·핑 손실)를 logs/lan-events.jsonl 에 남긴다. /api/system-stats 의 lan 필드와 /api/lan-status 로 내보내고 사이드바에 속도·상태 점을 표시한다. Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/net-health.ts | 167 ++++++++++++++++++++++++++++++++++++++ src/gateway/server.ts | 4 + web-ui/html/index.html | 5 ++ web-ui/js/app/app.js | 21 +++++ 4 files changed, 197 insertions(+) create mode 100644 src/gateway/net-health.ts diff --git a/src/gateway/net-health.ts b/src/gateway/net-health.ts new file mode 100644 index 0000000..b10f9de --- /dev/null +++ b/src/gateway/net-health.ts @@ -0,0 +1,167 @@ +/** + * 랜(유선 NIC) 상태 주기 점검 — 링크 속도·끊김 횟수·오류 카운터·공유기/인터넷 핑 손실을 30초마다 기록한다. + * + * 간헐적으로 끊기는 랜 케이블/소켓 접촉 불량을 잡으려는 용도: + * - 링크 속도가 1000→100으로 떨어지거나, carrier_changes(링크 끊김 횟수)가 늘면 이벤트로 남긴다. + * - 공유기(LAN)와 인터넷(WAN)을 따로 핑해서 "허브/케이블 쪽"인지 "회선 쪽"인지 가린다. + * 상태는 /api/system-stats 의 lan 필드와 /api/lan-status 로 내보내고, 이벤트는 logs/lan-events.jsonl 에 남긴다. + */ +import fs from 'fs'; +import path from 'path'; +import { execFile } from 'child_process'; + +const SAMPLE_MS = 30_000; +const KEEP_SAMPLES = 2880; // 30초 × 2880 = 24시간 +const KEEP_EVENTS = 100; +const WAN_TARGET = '1.1.1.1'; + +export interface NicState { + name: string; + up: boolean; + speed_mbps: number | null; + duplex: string; + carrier_changes: number; + rx_errors: number; + rx_dropped: number; + rx_crc_errors: number; + tx_errors: number; + tx_dropped: number; +} +export interface PingResult { target: string; loss_pct: number; avg_ms: number | null } +export interface LanSample { ts: number; nics: NicState[]; gateway: PingResult | null; wan: PingResult | null } +export interface LanEvent { ts: number; kind: string; detail: string } + +const samples: LanSample[] = []; +const events: LanEvent[] = []; +let logPath = ''; +let timer: NodeJS.Timeout | null = null; +let busy = false; + +function readNum(p: string): number | null { + try { const n = Number(fs.readFileSync(p, 'utf8').trim()); return Number.isFinite(n) ? n : null; } catch { return null; } +} +function readStr(p: string): string { + try { return fs.readFileSync(p, 'utf8').trim(); } catch { return ''; } +} + +/** 실제 유선 NIC만(가상·도커·터널 제외): /sys/class/net/X/device 가 있고 이름이 e* 로 시작 */ +function listNics(): string[] { + try { + return fs.readdirSync('/sys/class/net') + .filter(n => /^(en|eth)/.test(n) && fs.existsSync(`/sys/class/net/${n}/device`)); + } catch { return []; } +} + +function readNic(name: string): NicState { + const b = `/sys/class/net/${name}`; + const st = (f: string) => readNum(`${b}/statistics/${f}`) ?? 0; + const speed = readNum(`${b}/speed`); + return { + name, + up: readStr(`${b}/operstate`) === 'up', + speed_mbps: speed != null && speed > 0 ? speed : null, + duplex: readStr(`${b}/duplex`) || 'unknown', + carrier_changes: readNum(`${b}/carrier_changes`) ?? 0, + rx_errors: st('rx_errors'), + rx_dropped: st('rx_dropped'), + rx_crc_errors: st('rx_crc_errors'), + tx_errors: st('tx_errors'), + tx_dropped: st('tx_dropped'), + }; +} + +function defaultGateway(): Promise { + return new Promise(resolve => { + execFile('ip', ['route', 'show', 'default'], { timeout: 3000 }, (err, out) => { + if (err) return resolve(null); + const m = String(out).match(/default via (\d+\.\d+\.\d+\.\d+)/); + resolve(m ? m[1] : null); + }); + }); +} + +function ping(target: string): Promise { + return new Promise(resolve => { + execFile('ping', ['-c', '4', '-i', '0.25', '-W', '1', target], { timeout: 8000 }, (_err, out) => { + // ping은 손실이 있으면 종료코드가 1이라 err가 있어도 출력은 파싱한다 + const s = String(out || ''); + const loss = s.match(/(\d+(?:\.\d+)?)% packet loss/); + const rtt = s.match(/= [\d.]+\/([\d.]+)\//); + resolve({ target, loss_pct: loss ? Number(loss[1]) : 100, avg_ms: rtt ? Number(rtt[1]) : null }); + }); + }); +} + +function addEvent(kind: string, detail: string) { + const ev: LanEvent = { ts: Date.now(), kind, detail }; + events.push(ev); + if (events.length > KEEP_EVENTS) events.shift(); + if (logPath) { try { fs.appendFileSync(logPath, JSON.stringify(ev) + '\n'); } catch { /* 로그 실패는 무시 */ } } +} + +async function sampleOnce() { + if (busy) return; + busy = true; + try { + const nics = listNics().map(readNic); + const gw = await defaultGateway(); + 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]; + 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 (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', '공유기 핑 복구'); + 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', '인터넷 핑 복구'); + } + samples.push(cur); + if (samples.length > KEEP_SAMPLES) samples.shift(); + } catch { /* 점검 실패는 다음 주기에 다시 */ } finally { busy = false; } +} + +export function startNetHealth(logDir: string) { + if (timer) return; + try { fs.mkdirSync(logDir, { recursive: true }); logPath = path.join(logDir, 'lan-events.jsonl'); } catch { logPath = ''; } + void sampleOnce(); + timer = setInterval(() => void sampleOnce(), SAMPLE_MS); + timer.unref(); +} + +/** 화면용 요약. 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 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 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); + const status = nowBad ? 'bad' : warn ? 'warn' : 'ok'; + const label = primary ? `${speed != null ? speed + 'M' : '링크'}${flaps ? ` · 끊김 ${flaps}` : ''}` : '연결 끊김'; + return { + status, label, + nics: last.nics, + 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 }, + events: ev24.slice(-10).reverse(), + updated: last.ts, + }; +} diff --git a/src/gateway/server.ts b/src/gateway/server.ts index 4b941f4..aff8a83 100644 --- a/src/gateway/server.ts +++ b/src/gateway/server.ts @@ -61,6 +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 { 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'; @@ -3869,6 +3870,8 @@ function updateNetSpeed() { } updateNetSpeed(); setInterval(updateNetSpeed, 2000); +startNetHealth(path.join(CONFIG_DIR_PATH, 'logs')); +app.get('/api/lan-status', (_req, res) => { res.json(getLanStatus()); }); // ────────────────────────────────────────────────────────────────────────── app.get('/api/system-stats', async (req, res) => { @@ -3968,6 +3971,7 @@ app.get('/api/system-stats', async (req, res) => { }, gpu: gpuStats, network: _netSpeed, + lan: getLanStatus(), ollama_process: { running: ollamaRunning, process_count: ollamaCount, total_memory_mb: ollamaMemMb }, gateway_process: { rss_mb: rss / (1024 * 1024) }, active_provider: (getConfig().getConfig() as any).llm?.provider || 'ollama', diff --git a/web-ui/html/index.html b/web-ui/html/index.html index c92985f..d4aa43b 100644 --- a/web-ui/html/index.html +++ b/web-ui/html/index.html @@ -208,6 +208,11 @@
--% +
+ LAN + + -- +
diff --git a/web-ui/js/app/app.js b/web-ui/js/app/app.js index 410d473..40dc4ce 100644 --- a/web-ui/js/app/app.js +++ b/web-ui/js/app/app.js @@ -1148,6 +1148,25 @@ function netBarPct(bps) { return Math.min(100, (bps / _netPeak) * 100); } +// 사이드바 LAN 행: 링크 속도 + 최근 24시간 끊김 횟수, 점(초록/노랑/빨강), 마우스를 올리면 상세 +function renderLanStatus(lan) { + const dot = document.getElementById('sb-lan-dot'); + const txt = document.getElementById('sb-lan-text'); + const row = document.getElementById('sb-lan-row'); + if (!dot || !txt || !row) return; + if (!lan || lan.status === 'unknown') { txt.textContent = '확인 중'; dot.style.background = 'var(--muted)'; return; } + const color = { ok: 'var(--ok)', warn: '#e0a400', bad: '#d64545' }[lan.status] || 'var(--muted)'; + dot.style.background = color; + const ms = lan.gateway && lan.gateway.avg_ms != null ? ` · ${lan.gateway.avg_ms.toFixed(1)}ms` : ''; + txt.textContent = `${lan.label}${ms}`; + 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 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'); +} + let systemStatsFetchInFlight = false; async function loadSystemStats() { if (systemStatsFetchInFlight) return; @@ -1196,6 +1215,8 @@ async function loadSystemStats() { setMeter('sb-sys-rx-meter', netBarPct(rxBps)); setMeter('sb-sys-tx-meter', netBarPct(txBps)); + renderLanStatus(stats?.lan); + const ollamaRunning = !!stats?.ollama_process?.running; const ollamaCount = Number(stats?.ollama_process?.process_count || 0); const ollamaMemMb = Number(stats?.ollama_process?.total_memory_mb || 0);