SPB Git

Repository Public

ops.ts 21.3 KB 395 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : studio/server/ops.ts9 * Module           : studio10 * Repository       : https://git.spboucher.ai/ka-maps-engine11 * Created          : 2026-12-0112 * Last Modified    : 2026-12-0113 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@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// Exploitation : santé des services, séries de mesures (scrutation des /metrics), sondes de tuiles,43// données et journaux d'import, déclenchement du pipeline, statistiques d'usage agrégées.44import { execFile } from 'node:child_process';45import { readdir, open, stat, statfs } from 'node:fs/promises';46import { join } from 'node:path';47import { promisify } from 'node:util';48import { type Actor, audit, type Db, HttpError } from './db.ts';4950const run = promisify(execFile);5152export type OpsConfig = {53  services: { name: string; label: string; health: string; metrics: string | null; unit: string }[];54  tiler: string;55  logDir: string;56  dataDir: string;57  pipelineUnit: string;58  pipelineTrigger: boolean;59  collect: boolean;60};6162export function opsConfigFromEnv(env = process.env): OpsConfig {63  const e = (k: string, d: string) => env[k] ?? d;64  return {65    services: [66      { name: 'km-tiler', label: 'Tuiles vectorielles', health: e('KM_HEALTH_TILER', 'http://127.0.0.1:8901/healthz'), metrics: e('KM_METRICS_TILER', 'http://127.0.0.1:8911/metrics'), unit: 'km-tiler.service' },67      { name: 'km-geo', label: 'API géographique', health: e('KM_HEALTH_GEO', 'http://127.0.0.1:8902/healthz'), metrics: e('KM_METRICS_GEO', 'http://127.0.0.1:8902/metrics'), unit: 'km-geo.service' },68      { name: 'km-terrain', label: 'Relief', health: e('KM_HEALTH_TERRAIN', 'http://127.0.0.1:8903/healthz'), metrics: e('KM_METRICS_TERRAIN', 'http://127.0.0.1:8903/metrics'), unit: 'km-terrain.service' },69      { name: 'km-maps', label: 'Manifeste public', health: e('KM_HEALTH_MAPS', 'http://127.0.0.1:8904/healthz'), metrics: e('KM_METRICS_MAPS', 'http://127.0.0.1:8914/metrics'), unit: 'km-maps.service' },70    ],71    tiler: e('KM_TILER_LOCAL', 'http://127.0.0.1:8901'),72    logDir: e('KM_LOG_DIR', '/var/log/kamaps'),73    dataDir: e('KM_DATA_DIR', '/var/lib/kamaps'),74    pipelineUnit: e('STUDIO_PIPELINE_UNIT', 'kamaps-osm-refresh.service'),75    pipelineTrigger: e('STUDIO_PIPELINE_TRIGGER', '0') === '1',76    collect: e('STUDIO_COLLECT', '1') === '1',77  };78}7980// ---------- format Prometheus8182export type Sample = { name: string; labels: Record<string, string>; value: number };8384export function parseProm(text: string): Sample[] {85  const out: Sample[] = [];86  for (const line of text.split('\n')) {87    if (!line || line[0] === '#') continue;88    const m = /^([a-zA-Z_:][a-zA-Z0-9_:]*)(?:\{([^}]*)\})?\s+(\S+)/.exec(line);89    if (!m) continue;90    const labels: Record<string, string> = {};91    if (m[2]) for (const l of m[2].matchAll(/([a-zA-Z_][a-zA-Z0-9_]*)="((?:[^"\\]|\\.)*)"/g)) labels[l[1]] = l[2];92    const value = Number(m[3]);93    if (Number.isFinite(value)) out.push({ name: m[1], labels, value });94  }95  return out;96}9798/** Totaux utiles d'un service à partir de ses compteurs bruts. `buckets` : histogramme cumulé des99 *  durées, bornes en millisecondes. */100export function summarize(service: string, samples: Sample[]) {101  const sum = (pred: (s: Sample) => boolean) => samples.filter(pred).reduce((a, s) => a + s.value, 0);102  const buckets = new Map<number, number>();103  const addBuckets = (name: string, scale: number) => {104    for (const s of samples) if (s.name === name) {105      const le = s.labels.le === '+Inf' ? Infinity : Number(s.labels.le) * scale;106      buckets.set(le, (buckets.get(le) ?? 0) + s.value);107    }108  };109  const t: Record<string, number> = {};110  if (service === 'km-tiler') {111    t.req = sum((s) => s.name === 'km_tile_requests_total');112    t.err = sum((s) => s.name === 'km_generation_errors_total' || s.name === 'km_overloaded_total');113    t.hit = sum((s) => s.name === 'km_cache_hits_total');114    t.miss = sum((s) => s.name === 'km_cache_misses_total');115    t.limited = sum((s) => s.name === 'km_rate_limited_total');116    t.bytes = sum((s) => s.name === 'km_bytes_sent_total');117    addBuckets('km_generation_seconds_bucket', 1000);118  } else {119    const p = service === 'km-geo' ? 'km_geo' : service === 'km-terrain' ? 'km_terrain' : 'km_maps';120    t.req = sum((s) => s.name === `${p}_requests_total`);121    t.err = sum((s) => s.name === `${p}_requests_total` && s.labels.status === '5xx');122    t.limited = sum((s) => s.name === `${p}_requests_total` && s.labels.route === 'limited') + sum((s) => s.name === `${p}_rate_limited_total`);123    if (service === 'km-maps') {124      t.hit = sum((s) => s.name === 'km_maps_static_total' && s.labels.result === 'hit');125      t.miss = sum((s) => s.name === 'km_maps_static_total' && s.labels.result === 'rendered');126    }127    addBuckets(`${p}_duration_ms_bucket`, 1);128  }129  return { totals: t, buckets: [...buckets.entries()].sort((a, b) => a[0] - b[0]) };130}131132/** Quantile d'un histogramme cumulé (interpolation linéaire dans la tranche). */133export function quantile(buckets: [number, number][], q: number): number | null {134  const total = buckets.length ? buckets[buckets.length - 1][1] : 0;135  if (total <= 0) return null;136  const rank = q * total;137  let prevLe = 0;138  let prevCount = 0;139  for (const [le, count] of buckets) {140    if (count >= rank) {141      if (le === Infinity) return prevLe;142      const span = count - prevCount;143      return span <= 0 ? le : prevLe + ((rank - prevCount) / span) * (le - prevLe);144    }145    prevLe = le === Infinity ? prevLe : le;146    prevCount = count;147  }148  return prevLe;149}150151/** Variation entre deux relevés ; un compteur qui recule (redémarrage du service) repart de zéro. */152export function delta(cur: number, prev: number | undefined): number {153  if (prev === undefined) return 0;154  return cur >= prev ? cur - prev : cur;155}156157export class Collector {158  private prev = new Map<string, ReturnType<typeof summarize>>();159  private timers: NodeJS.Timeout[] = [];160  private db: Db;161  private cfg: OpsConfig;162  constructor(db: Db, cfg: OpsConfig) {163    this.db = db;164    this.cfg = cfg;165  }166167  start() {168    if (!this.cfg.collect) return;169    this.timers.push(setInterval(() => this.metrics().catch(() => {}), 60_000), setInterval(() => this.health().catch(() => {}), 30_000), setInterval(() => this.prune().catch(() => {}), 3600_000));170    for (const t of this.timers) t.unref();171    this.metrics().catch(() => {});172    this.health().catch(() => {});173  }174  stop() {175    for (const t of this.timers) clearInterval(t);176  }177178  async health() {179    const rows = await Promise.all(this.cfg.services.map((s) => probe(s.health).then((r) => ({ service: s.name, ...r }))));180    for (const r of rows) await this.db.pool.query(`INSERT INTO ${this.db.schema}.health_sample (service, ts, ok, ms, detail) VALUES ($1, now(), $2, $3, $4) ON CONFLICT DO NOTHING`, [r.service, r.ok, r.ms, r.detail]);181    return rows;182  }183184  async metrics() {185    const ts = new Date(Math.floor(Date.now() / 60_000) * 60_000);186    for (const s of this.cfg.services) {187      if (!s.metrics) continue;188      let cur;189      try {190        const r = await fetch(s.metrics, { signal: AbortSignal.timeout(4000) });191        if (!r.ok) continue;192        cur = summarize(s.name, parseProm(await r.text()));193      } catch {194        continue;195      }196      const prev = this.prev.get(s.name);197      this.prev.set(s.name, cur);198      if (!prev) continue;199      const points: [string, number][] = [];200      for (const [k, v] of Object.entries(cur.totals)) points.push([k, delta(v, prev.totals[k])]);201      const prevB = new Map(prev.buckets);202      const reset = cur.buckets.some(([le, c]) => c < (prevB.get(le) ?? 0));203      const db: [number, number][] = cur.buckets.map(([le, c]) => [le, reset ? c : c - (prevB.get(le) ?? 0)]);204      for (const [k, q] of [['p50', 0.5], ['p95', 0.95], ['p99', 0.99]] as const) {205        const v = quantile(db, q);206        if (v !== null) points.push([k, Math.round(v * 100) / 100]);207      }208      for (const [k, v] of points) await this.db.pool.query(`INSERT INTO ${this.db.schema}.metric_point (service, key, ts, value) VALUES ($1, $2, $3, $4) ON CONFLICT (service, key, ts) DO UPDATE SET value = EXCLUDED.value`, [s.name, k, ts, v]);209    }210  }211212  async prune() {213    await this.db.pool.query(`DELETE FROM ${this.db.schema}.metric_point WHERE ts < now() - interval '30 days'`);214    await this.db.pool.query(`DELETE FROM ${this.db.schema}.health_sample WHERE ts < now() - interval '14 days'`);215  }216}217218async function probe(url: string): Promise<{ ok: boolean; ms: number | null; detail: string | null }> {219  const t0 = performance.now();220  try {221    const r = await fetch(url, { signal: AbortSignal.timeout(3000) });222    const text = (await r.text()).slice(0, 300);223    return { ok: r.ok, ms: Math.round((performance.now() - t0) * 10) / 10, detail: r.ok ? text.trim() : `HTTP ${r.status}` };224  } catch (e: any) {225    return { ok: false, ms: null, detail: String(e?.cause?.code ?? e?.name ?? 'erreur') };226  }227}228229export async function healthBoard(db: Db, cfg: OpsConfig) {230  const s = db.schema;231  const live = await Promise.all(cfg.services.map((x) => probe(x.health)));232  const units = await Promise.all(cfg.services.map((x) => run('systemctl', ['show', '-p', 'ActiveState,SubState,ActiveEnterTimestamp,NRestarts,MemoryCurrent', x.unit], { timeout: 4000 }).then((r) => Object.fromEntries(r.stdout.trim().split('\n').map((l) => l.split(/=(.*)/s).slice(0, 2))), () => null)));233  const up = await db.pool.query(`SELECT service, count(*)::int AS n, count(*) FILTER (WHERE ok)::int AS ok, avg(ms) FILTER (WHERE ok) AS ms FROM ${s}.health_sample WHERE ts > now() - interval '24 hours' GROUP BY service`);234  const last = await db.pool.query(`SELECT service, max(ts) AS ts FROM ${s}.health_sample WHERE NOT ok AND ts > now() - interval '14 days' GROUP BY service`);235  const dbInfo = await db.pool.query(`SELECT pg_database_size(current_database()) AS bytes, (SELECT count(*)::int FROM pg_stat_activity WHERE datname = current_database()) AS connections, version() AS version`);236  const disk = await statfs(cfg.dataDir).then((f) => ({ total: f.blocks * f.bsize, free: f.bavail * f.bsize }), () => null);237  return {238    at: new Date().toISOString(),239    services: cfg.services.map((x, i) => {240      const u = up.rows.find((r) => r.service === x.name);241      return { name: x.name, label: x.label, ...live[i], unit: units[i], uptime24h: u && u.n ? u.ok / u.n : null, samples24h: u?.n ?? 0, avgMs24h: u?.ms ?? null, lastFailure: last.rows.find((r) => r.service === x.name)?.ts ?? null };242    }),243    database: { ok: true, bytes: dbInfo.rows[0].bytes, connections: dbInfo.rows[0].connections, version: String(dbInfo.rows[0].version).split(' on ')[0] },244    disk,245  };246}247248export async function metricSeries(db: Db, service: string, hours: number) {249  const h = Math.min(Math.max(1, Math.round(hours)), 24 * 30);250  // Pas d'agrégation : 1 min jusqu'à 6 h, puis 5 min, 30 min, 2 h.251  const step = h <= 6 ? 60 : h <= 48 ? 300 : h <= 24 * 7 ? 1800 : 7200;252  const r = await db.pool.query(253    `SELECT key, to_timestamp(floor(extract(epoch FROM ts) / $3) * $3) AS t,254            CASE WHEN key IN ('p50', 'p95', 'p99') THEN max(value) ELSE sum(value) END AS v255     FROM ${db.schema}.metric_point WHERE service = $1 AND ts > now() - make_interval(hours => $2) GROUP BY key, t ORDER BY t`,256    [service, h, step],257  );258  const series: Record<string, [number, number][]> = {};259  for (const row of r.rows) (series[row.key] ??= []).push([new Date(row.t).getTime(), Number(row.v)]);260  return { service, hours: h, step, series };261}262263export async function usage(db: Db, days: number) {264  const d = Math.min(Math.max(1, Math.round(days)), 90);265  const s = db.schema;266  const app = await db.pool.query(`SELECT to_char(day, 'YYYY-MM-DD') AS day, app, platform, kind, count FROM ${s}.usage_daily WHERE day > current_date - $1::int ORDER BY day, app, platform, kind`, [d]);267  const svc = await db.pool.query(`SELECT to_char(date_trunc('day', ts), 'YYYY-MM-DD') AS day, service, sum(value) AS requests FROM ${s}.metric_point WHERE key = 'req' AND ts > current_date - $1::int GROUP BY 1, 2 ORDER BY 1, 2`, [d]);268  return { days: d, manifest: app.rows, services: svc.rows.map((r) => ({ ...r, requests: Number(r.requests) })) };269}270271// ---------- sondes de tuiles272273export const PROBE_PLACES: { id: string; label: string; lon: number; lat: number }[] = [274  { id: 'montreal', label: 'Montréal, centre-ville', lon: -73.5674, lat: 45.5019 },275  { id: 'plateau', label: 'Montréal, Plateau', lon: -73.5805, lat: 45.5232 },276  { id: 'laval', label: 'Laval', lon: -73.7124, lat: 45.5699 },277  { id: 'quebec', label: 'Québec, Vieux-Québec', lon: -71.2075, lat: 46.8123 },278  { id: 'gatineau', label: 'Gatineau', lon: -75.7013, lat: 45.4765 },279  { id: 'sherbrooke', label: 'Sherbrooke', lon: -71.8929, lat: 45.4042 },280  { id: 'saguenay', label: 'Saguenay', lon: -71.0657, lat: 48.4284 },281  { id: 'lac-saint-jean', label: 'Lac-Saint-Jean (rural)', lon: -72.2354, lat: 48.5522 },282  { id: 'gaspe', label: 'Gaspé', lon: -64.4781, lat: 48.8316 },283  { id: 'rouyn', label: 'Rouyn-Noranda', lon: -79.0183, lat: 48.2366 },284];285export const PROBE_ZOOMS = [3, 6, 8, 10, 12, 13, 14];286287export function tileOf(lon: number, lat: number, z: number): { z: number; x: number; y: number } {288  const n = 2 ** z;289  const x = Math.floor(((lon + 180) / 360) * n);290  const r = (lat * Math.PI) / 180;291  const y = Math.floor(((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2) * n);292  return { z, x: Math.min(n - 1, Math.max(0, x)), y: Math.min(n - 1, Math.max(0, y)) };293}294295export async function runTileProbe(db: Db, cfg: OpsConfig, actor: Actor) {296  const jobs = PROBE_PLACES.flatMap((p) => PROBE_ZOOMS.map((z) => ({ place: p.id, label: p.label, ...tileOf(p.lon, p.lat, z) })));297  const seen = new Set<string>();298  const unique = jobs.filter((j) => (seen.has(`${j.z}/${j.x}/${j.y}`) ? false : (seen.add(`${j.z}/${j.x}/${j.y}`), true)));299  const results: any[] = [];300  let i = 0;301  await Promise.all(302    Array.from({ length: 4 }, async () => {303      while (i < unique.length) {304        const j = unique[i++];305        const t0 = performance.now();306        try {307          const r = await fetch(`${cfg.tiler}/v1/base/${j.z}/${j.x}/${j.y}.mvt`, { headers: { 'Accept-Encoding': 'gzip' }, signal: AbortSignal.timeout(15_000) });308          const bytes = Number(r.headers.get('content-length') ?? 0) || (await r.clone().arrayBuffer()).byteLength;309          await r.arrayBuffer().catch(() => {});310          const ms = Math.round((performance.now() - t0) * 10) / 10;311          const ok = r.status === 200 || (r.status === 204 && j.z < 8);312          results.push({ ...j, status: r.status, ms, bytes, ok, note: r.status === 204 ? 'vide' : ms > 1000 ? 'lente' : bytes > 500_000 ? 'lourde' : null });313        } catch (e: any) {314          results.push({ ...j, status: 0, ms: Math.round(performance.now() - t0), bytes: 0, ok: false, note: String(e?.name ?? 'erreur') });315        }316      }317    }),318  );319  results.sort((a, b) => a.place.localeCompare(b.place) || a.z - b.z);320  const lat = results.filter((r) => r.status === 200).map((r) => r.ms).sort((a, b) => a - b);321  const pick = (q: number) => (lat.length ? lat[Math.min(lat.length - 1, Math.floor(q * lat.length))] : null);322  const summary = { tiles: results.length, failures: results.filter((r) => !r.ok).length, slow: results.filter((r) => r.ms > 1000).length, p50: pick(0.5), p95: pick(0.95), max: lat.length ? lat[lat.length - 1] : null };323  const ins = await db.pool.query(`INSERT INTO ${db.schema}.tile_probe (author_name, summary, results) VALUES ($1, $2, $3) RETURNING id, at`, [actor.name, JSON.stringify(summary), JSON.stringify(results)]);324  await audit(db.pool, db.schema, actor, 'ops.tile-probe', null, summary);325  return { id: ins.rows[0].id, at: ins.rows[0].at, summary, results };326}327328export async function tileProbes(db: Db) {329  const list = await db.pool.query(`SELECT id, at, author_name, summary FROM ${db.schema}.tile_probe ORDER BY id DESC LIMIT 30`);330  const last = await db.pool.query(`SELECT id, at, author_name, summary, results FROM ${db.schema}.tile_probe ORDER BY id DESC LIMIT 1`);331  return { history: list.rows, last: last.rows[0] ?? null };332}333334// ---------- données, journaux, pipeline335336export async function dataStatus(db: Db, cfg: OpsConfig) {337  const safe = async (sql: string) => db.pool.query(sql).then((r) => r.rows, () => null);338  const datasets = await safe(`SELECT id, title, provider, url, licence, attribution, source_date, imported_at, layers, features, status, notes FROM meta.dataset ORDER BY provider, title`);339  const versions = await safe(`SELECT version, status, osm_timestamp, created_at, activated_at, counts, validation->'ok' AS validation_ok, validation->'errors' AS validation_errors, validation->'warnings' AS validation_warnings, notes FROM meta.version ORDER BY created_at DESC LIMIT 20`);340  const logs: { name: string; bytes: number; mtime: string }[] = [];341  for (const f of await readdir(cfg.logDir).catch(() => [] as string[])) {342    if (!/^[A-Za-z0-9._-]{1,120}$/.test(f)) continue;343    const st = await stat(join(cfg.logDir, f)).catch(() => null);344    if (st?.isFile()) logs.push({ name: f, bytes: st.size, mtime: st.mtime.toISOString() });345  }346  logs.sort((a, b) => b.mtime.localeCompare(a.mtime));347  return { datasets, versions, logs: logs.slice(0, 100), pipeline: await pipelineStatus(db, cfg) };348}349350export async function logTail(cfg: OpsConfig, name: string, maxBytes = 64 * 1024) {351  if (!/^[A-Za-z0-9._-]{1,120}$/.test(name) || name.startsWith('.')) throw new HttpError(400, 'nom de journal invalide');352  const path = join(cfg.logDir, name);353  const st = await stat(path).catch(() => null);354  if (!st?.isFile()) throw new HttpError(404, 'journal inconnu');355  const fh = await open(path, 'r');356  try {357    const len = Math.min(st.size, maxBytes);358    const buf = Buffer.alloc(len);359    await fh.read(buf, 0, len, st.size - len);360    let text = buf.toString('utf8');361    if (st.size > len) text = text.slice(text.indexOf('\n') + 1);362    return { name, bytes: st.size, truncated: st.size > len, mtime: st.mtime.toISOString(), text };363  } finally {364    await fh.close();365  }366}367368export async function pipelineStatus(db: Db, cfg: OpsConfig) {369  const show = await run('systemctl', ['show', '-p', 'LoadState,ActiveState,SubState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp', cfg.pipelineUnit], { timeout: 4000 }).then((r) => Object.fromEntries(r.stdout.trim().split('\n').map((l) => l.split(/=(.*)/s).slice(0, 2))), () => null);370  const timer = await run('systemctl', ['show', '-p', 'NextElapseUSecRealtime,LastTriggerUSec', cfg.pipelineUnit.replace(/\.service$/, '.timer')], { timeout: 4000 }).then((r) => Object.fromEntries(r.stdout.trim().split('\n').map((l) => l.split(/=(.*)/s).slice(0, 2))), () => null);371  const runs = await db.pool.query(`SELECT id, at, author_name, unit, outcome FROM ${db.schema}.pipeline_run ORDER BY id DESC LIMIT 20`);372  return { unit: cfg.pipelineUnit, triggerEnabled: cfg.pipelineTrigger, state: show, timer, runs: runs.rows, confirmWord: PIPELINE_CONFIRM };373}374375export const PIPELINE_CONFIRM = 'RAFRAICHIR';376377/** Lance l'unité systemd du rafraîchissement (la même que la minuterie hebdomadaire). Jamais de378 *  commande libre : seule cette unité, et seulement si le déclenchement est activé sur le serveur. */379export async function pipelineRun(db: Db, cfg: OpsConfig, actor: Actor, body: any) {380  if (!cfg.pipelineTrigger) throw new HttpError(403, 'déclenchement désactivé sur ce serveur (lecture seule)');381  if (body?.confirm !== PIPELINE_CONFIRM) throw new HttpError(400, `confirmation requise : saisir ${PIPELINE_CONFIRM}`);382  const st = await pipelineStatus(db, cfg);383  if (st.state?.ActiveState === 'active' || st.state?.ActiveState === 'activating') throw new HttpError(409, 'un rafraîchissement est déjà en cours');384  let outcome = 'lancé';385  try {386    await run('systemctl', ['start', '--no-block', cfg.pipelineUnit], { timeout: 10_000 });387  } catch (e: any) {388    outcome = `refusé : ${String(e?.stderr ?? e?.message ?? e).trim().slice(0, 200)}`;389  }390  await db.pool.query(`INSERT INTO ${db.schema}.pipeline_run (author_name, unit, outcome) VALUES ($1, $2, $3)`, [actor.name, cfg.pipelineUnit, outcome]);391  await audit(db.pool, db.schema, actor, 'ops.pipeline.run', cfg.pipelineUnit, { outcome });392  if (outcome !== 'lancé') throw new HttpError(502, outcome);393  return { outcome };394}395
Files main
Menu

Theme