Repository Public
1#!/bin/bash2# =============================================================================3# SP BOUCHER | INFRASTRUCTURE & AUTOMATION4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project : KA Maps Engine8# File : server/km-geo/tests/loadtest.sh9# Module : server10# 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# Technical Contact: dev@spboucher.ai23# Security/Admin : admin@spboucher.ai24#25# Copyright (c) 202626# Simon-Pierre Boucher27# All rights reserved where applicable. This file is governed by the28# applicable project license, copyright notices and relevant law.29# Existing third-party rights and notices remain unaffected.30#31# License : None specified (no license file in this repository)32#33# Do not embed credentials, private keys, access tokens,34# certificates or confidential personal information.35#36# =============================================================================37# END OF SP BOUCHER SOURCE HEADER38# =============================================================================3940# Tir de charge local de km-geo (wrk, boucle locale — non soumise à la limite par IP).41# loadtest.sh [connexions=200] [durée=120s] [mélange=api|routing]42# api : recherche 60 %, inverse 15 %, proximité 10 %, limites 8 %, altitude 5 %, mesure 2 %43# routing : le même mélange + 3 % d'isochrones à pied (15 min) et 0,3 % en auto (30 min)44# Sortie : JSON (débit, centiles, statuts, CPU moyen de km-geo et de PostgreSQL en cœurs, mémoire résidente maximale).45set -euo pipefail46CONN=${1:-200}; DUR=${2:-120s}; MIX=${3:-api}47HERE=$(cd "$(dirname "$0")" && pwd)48BASE=${KM_GEO_URL:-http://127.0.0.1:8902}49W=$(mktemp -d)50python3 -I - "$HERE" "$MIX" > "$W/urls.lua" <<'PY'51import json, random, sys, urllib.parse52here, mix = sys.argv[1], sys.argv[2]53random.seed(20261201)54rows = [l.rstrip("\n").split("\t") for l in open(here + "/geocode_sample.tsv", encoding="utf-8") if not l.startswith("#")]55manual = json.load(open(here + "/cases_manual.json", encoding="utf-8"))56q = lambda path, **kw: path + "?" + urllib.parse.urlencode(kw)57urls = []58def add(n, f):59 for _ in range(n):60 urls.append(f())61def addr():62 r = random.choice(rows); s = f"{r[2]} {r[3]}, {r[4]}"63 k = random.choice([4, 7, 10, 14, 18, len(s), len(s), len(s)]) # frappe en cours et adresse complète64 return q("/v1/search", q=s[:k])65def pt():66 r = random.choice(rows)67 return float(r[6]) + random.uniform(-0.01, 0.01), float(r[7]) + random.uniform(-0.007, 0.007)68add(900, addr)69add(300, lambda: q("/v1/search", q=random.choice(manual)["q"]))70add(300, lambda: (lambda p: q("/v1/reverse", lon=round(p[0], 6), lat=round(p[1], 6)))(pt()))71add(200, lambda: (lambda p: q("/v1/nearby", lon=round(p[0], 6), lat=round(p[1], 6), radius=random.choice([500, 1000, 2000])))(pt()))72add(100, lambda: (lambda p: q("/v1/boundaries", lon=round(p[0], 6), lat=round(p[1], 6)))(pt()))73add(60, lambda: q("/v1/boundaries/search", q=random.choice(["plateau", "limoilou", "saint", "mont", "verdun", "sherb", "gatineau"])))74add(100, lambda: (lambda p: q("/v1/elevation", lon=round(p[0], 6), lat=round(p[1], 6)))(pt()))75add(40, lambda: (lambda p: q("/v1/measure", points=f"{p[0]:.5f},{p[1]:.5f};{p[0]+0.01:.5f},{p[1]:.5f};{p[0]+0.01:.5f},{p[1]+0.01:.5f}", close="true"))(pt()))76if mix == "routing":77 add(62, lambda: (lambda p: q("/v1/isochrone", lon=round(p[0], 5), lat=round(p[1], 5), profile="walking", minutes=15, max_vertices=180))(pt()))78 add(6, lambda: (lambda p: q("/v1/isochrone", lon=round(p[0], 5), lat=round(p[1], 5), profile="driving", minutes=30, max_vertices=180))(pt()))79random.shuffle(urls)80print("urls = {")81for u in urls:82 print(' "' + u.replace('"', "%22") + '",')83print("}")84PY85cat >> "$W/urls.lua" <<'LUA'86local threads = {}87function setup(thread) table.insert(threads, thread) end88function init(args) i = math.random(#urls); codes = {} end89function request() i = i % #urls + 1; return wrk.format("GET", urls[i]) end90function response(status) codes[status] = (codes[status] or 0) + 1 end91function done(summary, latency, requests)92 local tot = {}93 for _, t in ipairs(threads) do94 local c = t:get("codes")95 for k, v in pairs(c) do tot[k] = (tot[k] or 0) + v end96 end97 local parts = {}98 for k, v in pairs(tot) do table.insert(parts, string.format('"%d": %d', k, v)) end99 io.write(string.format('WRKJSON {"requests": %d, "seconds": %.1f, "rps": %.0f, "p50_ms": %.2f, "p90_ms": %.2f, "p95_ms": %.2f, "p99_ms": %.2f, "p999_ms": %.2f, "max_ms": %.2f, "socket_errors": %d, "timeouts": %d, "status": {%s}}\n',100 summary.requests, summary.duration / 1e6, summary.requests / (summary.duration / 1e6),101 latency:percentile(50) / 1000, latency:percentile(90) / 1000, latency:percentile(95) / 1000, latency:percentile(99) / 1000,102 latency:percentile(99.9) / 1000, latency.max / 1000,103 summary.errors.connect + summary.errors.read + summary.errors.write, summary.errors.timeout, table.concat(parts, ", ")))104end105LUA106cpu() { ps -o cputimes= -C km-geo 2>/dev/null | awk '{s+=$1} END {print s+0}'; }107# CPU de PostgreSQL : seulement les connexions du service (rôle km_geo_ro), suivies par PID du début à la fin108pgpids=$(ps -o pid=,args= -u postgres | awk '/km_geo_ro/ {print $1}' | tr '\n' ',' | sed 's/,$//')109pgcpu() { [ -n "$pgpids" ] && ps -o cputimes= -p "$pgpids" 2>/dev/null | awk '{s+=$1} END {print s+0}' || echo 0; }110g0=$(cpu); p0=$(pgcpu); t0=$(date +%s.%N)111touch "$W/running"; echo 0 > "$W/rss"112( maxrss=0; while [ -e "$W/running" ]; do r=$(ps -o rss= -C km-geo | awk '{s+=$1} END {print s+0}'); [ "$r" -gt "$maxrss" ] && maxrss=$r; echo "$maxrss" > "$W/rss"; sleep 2; done ) &113( cd "$W" && wrk -t 8 -c "$CONN" -d "$DUR" --timeout 10s -s urls.lua "$BASE" ) > "$W/wrk.out" 2>&1 || true114rm -f "$W/running"; wait115g1=$(cpu); p1=$(pgcpu); t1=$(date +%s.%N)116python3 -I - "$W/wrk.out" "$g0" "$g1" "$p0" "$p1" "$t0" "$t1" "$(cat "$W/rss" 2>/dev/null || echo 0)" "$CONN" "$MIX" <<'PY'117import json, sys118out, g0, g1, p0, p1, t0, t1, rss, conn, mix = sys.argv[1:]119line = [l for l in open(out) if l.startswith("WRKJSON ")]120if not line:121 print(open(out).read()); sys.exit(1)122r = json.loads(line[0][8:])123dt = float(t1) - float(t0)124r.update(connections=int(conn), mix=mix, km_geo_cpu_cores=round((float(g1) - float(g0)) / dt, 2),125 postgres_cpu_cores=round((float(p1) - float(p0)) / dt, 2), km_geo_rss_max_mb=round(int(rss) / 1024))126tot = sum(r["status"].values()) or 1127r["non_2xx_pct"] = round(100 * sum(v for k, v in r["status"].items() if not k.startswith("2")) / tot, 3)128print(json.dumps(r, ensure_ascii=False))129PY130rm -rf "$W"131