Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/monitor.ts9 * Module : server10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Supervision : joignabilité des caméras (TCP RTSP), redécouverte par adresse MAC, métriques système.43import os from 'node:os';44import type { Camera } from './cameras.ts';45import type { Config } from './config.ts';46import { addEvent, type DB } from './db.ts';47import { logger } from './log.ts';48import { run } from './media.ts';49import { lanReachable } from './relay.ts';50import { archiveBytes } from './retention.ts';51import { diskStats } from './storage.ts';5253const log = logger('monitor');5455export const tcpCheck = (host: string, port: number, timeoutMs = 3000) => lanReachable(host, port, Math.max(1, Math.round(timeoutMs / 1000)));5657const failures = new Map<string, number>();58const lastDiscovery = new Map<string, number>();5960/** Retourne les caméras dont l'adresse a changé (à charge de l'appelant de régénérer la passerelle). */61export async function checkCameras(db: DB, cams: Camera[]): Promise<string[]> {62 const changed: string[] = [];63 await Promise.all(64 cams.map(async (cam) => {65 const ok = await tcpCheck(cam.effectiveHost, cam.rtspPort);66 const now = Date.now();67 const st = db.prepare('SELECT reachable, reachable_since_ms FROM camera_state WHERE camera_id = ?').get(cam.id) as { reachable: number; reachable_since_ms: number | null } | undefined;68 const fails = ok ? 0 : (failures.get(cam.id) || 0) + 1;69 failures.set(cam.id, fails);70 if (ok && !st?.reachable) {71 const down = st?.reachable_since_ms ? now - st.reachable_since_ms : null;72 db.prepare('UPDATE camera_state SET reachable = 1, reachable_since_ms = ?, last_check_ms = ? WHERE camera_id = ?').run(now, now, cam.id);73 if (st?.reachable_since_ms) addEvent(db, { cameraId: cam.id, type: 'camera_online', message: `Caméra de nouveau joignable${down ? ` après ${Math.round(down / 1000)} s` : ''}`, data: { downMs: down } });74 } else if (!ok && fails === 2 && st?.reachable) {75 db.prepare('UPDATE camera_state SET reachable = 0, reachable_since_ms = ?, last_check_ms = ? WHERE camera_id = ?').run(now, now, cam.id);76 addEvent(db, { cameraId: cam.id, type: 'camera_offline', severity: 'warning', message: 'Caméra injoignable sur le réseau local' });77 } else {78 db.prepare('UPDATE camera_state SET last_check_ms = ? WHERE camera_id = ?').run(now, cam.id);79 if (!ok && !st?.reachable && !st?.reachable_since_ms) db.prepare('UPDATE camera_state SET reachable_since_ms = ? WHERE camera_id = ?').run(now, cam.id);80 }81 if (!ok && fails >= 4 && cam.mac && now - (lastDiscovery.get(cam.id) || 0) > 5 * 60000) {82 lastDiscovery.set(cam.id, now);83 const ip = await findByMac(cam);84 if (ip && ip !== cam.effectiveHost) {85 db.prepare('UPDATE cameras SET host_override = ?, updated_ms = ? WHERE id = ?').run(ip, now, cam.id);86 addEvent(db, { cameraId: cam.id, type: 'camera_address_changed', severity: 'warning', message: `Adresse de la caméra retrouvée par son adresse MAC : ${ip}`, data: { ip } });87 log.warn('adresse caméra mise à jour', { cam: cam.id, ip });88 changed.push(cam.id);89 }90 }91 }),92 );93 return changed;94}9596const normMac = (m: string) => m.toLowerCase().split(/[:-]/).map((o) => parseInt(o, 16).toString(16)).join(':');9798/** Balayage borné du /24 de la caméra (connexion TCP au port RTSP), puis lecture de la table ARP. */99async function findByMac(cam: Camera): Promise<string | null> {100 const m = /^(\d+\.\d+\.\d+)\.\d+$/.exec(cam.host);101 if (!m || !cam.mac) return null;102 const hosts = Array.from({ length: 254 }, (_, i) => `${m[1]}.${i + 1}`);103 for (let i = 0; i < hosts.length; i += 64) await Promise.all(hosts.slice(i, i + 64).map((h) => tcpCheck(h, cam.rtspPort, 1000)));104 const arp = await run('/usr/sbin/arp', ['-an'], { timeoutMs: 8000 });105 const want = normMac(cam.mac);106 for (const line of arp.stdout.split('\n')) {107 const a = /\((\d+\.\d+\.\d+\.\d+)\) at ([0-9a-f:]+)/i.exec(line);108 if (a && normMac(a[2]) === want && a[1].startsWith(m[1] + '.')) return a[1];109 }110 return null;111}112113let lastCpu: { idle: number; total: number } | null = null;114function cpuPercent(): number | null {115 let idle = 0;116 let total = 0;117 for (const c of os.cpus()) {118 idle += c.times.idle;119 total += c.times.idle + c.times.user + c.times.sys + c.times.nice + c.times.irq;120 }121 const prev = lastCpu;122 lastCpu = { idle, total };123 if (!prev || total === prev.total) return null;124 return (1 - (idle - prev.idle) / (total - prev.total)) * 100;125}126127/** RSS et CPU cumulés de l'arbre de processus de MacLustr Vision (cœur, go2rtc, FFmpeg, API). */128async function processTree(rootPids: number[]): Promise<{ rssMb: number; cpuPct: number; count: number }> {129 const r = await run('/bin/ps', ['-axo', 'pid=,ppid=,rss=,pcpu='], { timeoutMs: 8000 });130 const rows = r.stdout131 .split('\n')132 .map((l) => l.trim().split(/\s+/))133 .filter((p) => p.length >= 4)134 .map((p) => ({ pid: +p[0], ppid: +p[1], rss: +p[2], cpu: parseFloat(p[3].replace(',', '.')) || 0 }));135 const want = new Set(rootPids);136 let grew = true;137 while (grew) {138 grew = false;139 for (const row of rows) if (want.has(row.ppid) && !want.has(row.pid)) {140 want.add(row.pid);141 grew = true;142 }143 }144 let rss = 0;145 let cpu = 0;146 let count = 0;147 for (const row of rows) if (want.has(row.pid)) {148 rss += row.rss;149 cpu += row.cpu;150 count++;151 }152 return { rssMb: rss / 1024, cpuPct: cpu, count };153}154155export async function sampleMetrics(cfg: Config, db: DB, extraPids: number[]): Promise<void> {156 const now = Date.now();157 const ins = db.prepare('INSERT INTO metrics (ts_ms, key, value) VALUES (?, ?, ?)');158 const put = (k: string, v: number | null) => {159 if (v !== null && Number.isFinite(v)) ins.run(now, k, v);160 };161 put('load1', os.loadavg()[0]);162 put('cpu_pct', cpuPercent());163 const tree = await processTree([process.pid, ...extraPids]);164 put('vision_rss_mb', tree.rssMb);165 put('vision_cpu_pct', tree.cpuPct);166 put('vision_procs', tree.count);167 try {168 put('disk_free_gb', diskStats(cfg.dataDir).freeBytes / 1024 ** 3);169 } catch {170 /* rien */171 }172 put('archive_gb', archiveBytes(db) / 1024 ** 3);173 const rows = db.prepare('SELECT camera_id, last_bitrate_bps FROM camera_state').all() as { camera_id: string; last_bitrate_bps: number | null }[];174 let sum = 0;175 for (const r of rows) {176 if (r.last_bitrate_bps) {177 put(`bitrate_bps:${r.camera_id}`, r.last_bitrate_bps);178 sum += r.last_bitrate_bps;179 }180 }181 put('bitrate_bps', sum);182}183