fix:lasttest
This commit is contained in:
1 parent
c7d622f4e3
commit
4cb6cd8cf9
3 files changed
+65
-20
No files matched your search
@@ -6,5 +6,7 @@ __pycache__/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.venv/
|
||||
|
||||
# Berichte der Abnahme (scripts/zap-baseline.sh)
|
||||
zap-report.html
|
||||
zap-report.md
|
||||
+6
-1
@@ -64,7 +64,12 @@ produktive Instanz.
|
||||
3. **Lasttest** (nur lesend):
|
||||
`python3 scripts/loadtest.py https://test.umfrage.example.de --path / --path /login --path /f/<token> --users 20 --requests 100`.
|
||||
Ziel: 95. Perzentil unter 200 ms. Für Seiten hinter der Anmeldung
|
||||
`--cookie "__Host-surveybox_session=…"` angeben.
|
||||
`--cookie "__Host-surveybox_session=…"` angeben. Das Skript hält die
|
||||
Verbindungen offen wie ein Browser und verfolgt keine Weiterleitungen.
|
||||
Die Spalte „einzeln“ ist die Antwortzeit ohne gleichzeitige Last; liegt
|
||||
sie weit unter dem 95. Perzentil, warten die Anfragen auf freie
|
||||
Web-Prozesse – dann `SURVEYBOX_WEB_WORKERS` (Standard 2) auf die Zahl der
|
||||
CPU-Kerne des Servers erhöhen und erneut messen.
|
||||
4. **Update-Test mit Daten**: vor dem Update der Testinstanz das laufende Image
|
||||
markieren (`docker tag surveybox:local surveybox:vorher`), dann
|
||||
`OLD_IMAGE=surveybox:vorher scripts/upgrade-test.sh`. Danach die
|
||||
|
||||
+57
-19
@@ -20,26 +20,56 @@ Bitte nur gegen eigene Testinstanzen laufen lassen.
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import http.client
|
||||
import ssl
|
||||
import statistics
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
_local = threading.local()
|
||||
|
||||
def fetch(url: str, cookie: str | None) -> tuple[float, int]:
|
||||
request = urllib.request.Request(url, headers={ # noqa: S310 (Adresse vom Aufrufer)
|
||||
"User-Agent": "surveybox-loadtest", "Accept-Language": "de",
|
||||
**({"Cookie": cookie} if cookie else {})})
|
||||
|
||||
def _connection(base: urllib.parse.SplitResult) -> http.client.HTTPConnection:
|
||||
"""Eine Verbindung je Thread, wie ein Browser sie offen hält (Keep-Alive)."""
|
||||
conn: http.client.HTTPConnection | None = getattr(_local, "conn", None)
|
||||
if conn is None:
|
||||
if base.scheme == "https":
|
||||
conn = http.client.HTTPSConnection(base.hostname or "", base.port,
|
||||
context=ssl.create_default_context(),
|
||||
timeout=30)
|
||||
else:
|
||||
conn = http.client.HTTPConnection(base.hostname or "", base.port, timeout=30)
|
||||
_local.conn = conn
|
||||
return conn
|
||||
|
||||
|
||||
def fetch(base: urllib.parse.SplitResult, path: str, cookie: str | None) -> tuple[float, int]:
|
||||
"""Eine Anfrage; Weiterleitungen werden nicht verfolgt (zählen als Antwort)."""
|
||||
headers = {"User-Agent": "surveybox-loadtest", "Accept-Language": "de",
|
||||
**({"Cookie": cookie} if cookie else {})}
|
||||
for attempt in (1, 2):
|
||||
conn = _connection(base)
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as resp: # noqa: S310
|
||||
conn.request("GET", path, headers=headers)
|
||||
resp = conn.getresponse()
|
||||
resp.read()
|
||||
status = resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = exc.code
|
||||
return (time.perf_counter() - start) * 1000, status
|
||||
return (time.perf_counter() - start) * 1000, resp.status
|
||||
except (http.client.HTTPException, OSError):
|
||||
conn.close()
|
||||
_local.conn = None
|
||||
if attempt == 2:
|
||||
return (time.perf_counter() - start) * 1000, 599
|
||||
return 0.0, 599 # nicht erreichbar
|
||||
|
||||
|
||||
def warm_up(base: urllib.parse.SplitResult, path: str, cookie: str | None, users: int) -> None:
|
||||
"""Verbindungen aufbauen (TLS-Handschlag), bevor gemessen wird."""
|
||||
with ThreadPoolExecutor(max_workers=users) as pool:
|
||||
list(pool.map(lambda _: fetch(base, path, cookie), range(users * 2)))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -55,23 +85,31 @@ def main() -> int:
|
||||
parser.add_argument("--cookie", default=None, help="Cookie-Kopf für angemeldete Seiten")
|
||||
args = parser.parse_args()
|
||||
paths = args.path or ["/", "/login"]
|
||||
base = args.base.rstrip("/")
|
||||
base = urllib.parse.urlsplit(args.base.rstrip("/"))
|
||||
failed = False
|
||||
print(f"{'Seite':40} {'Median':>8} {'95 %':>8} {'Max':>8} Fehler")
|
||||
print(f"{'Seite':34} {'einzeln':>8} {'Median':>8} {'95 %':>8} {'Max':>8} {'Abr./s':>7}"
|
||||
" Fehler")
|
||||
for path in paths:
|
||||
url = base + path
|
||||
fetch(url, args.cookie) # aufwärmen
|
||||
# einzeln: eine Anfrage nach der anderen = reine Antwortzeit ohne Warteschlange
|
||||
warm_up(base, path, args.cookie, 1)
|
||||
single = statistics.median(fetch(base, path, args.cookie)[0] for _ in range(10))
|
||||
warm_up(base, path, args.cookie, args.users)
|
||||
began = time.perf_counter()
|
||||
with ThreadPoolExecutor(max_workers=args.users) as pool:
|
||||
results = list(pool.map(fetch, [url] * args.requests, [args.cookie] * args.requests))
|
||||
n = args.requests
|
||||
results = list(pool.map(fetch, [base] * n, [path] * n, [args.cookie] * n))
|
||||
rate = len(results) / (time.perf_counter() - began)
|
||||
times = sorted(t for t, _ in results)
|
||||
errors = sum(1 for _, status in results if status >= 400)
|
||||
p95 = times[max(int(len(times) * 0.95) - 1, 0)]
|
||||
too_slow = p95 > args.limit_ms
|
||||
failed = failed or too_slow or errors > 0
|
||||
mark = " ZU LANGSAM" if too_slow else ""
|
||||
print(f"{path[:40]:40} {statistics.median(times):7.0f} {p95:7.0f} {times[-1]:7.0f}"
|
||||
f" {errors}{mark}")
|
||||
print(f"\nGrenze 95. Perzentil: {args.limit_ms:.0f} ms bei {args.users} gleichzeitigen Abrufen")
|
||||
print(f"{path[:34]:34} {single:7.0f} {statistics.median(times):7.0f} {p95:7.0f}"
|
||||
f" {times[-1]:7.0f} {rate:6.0f} {errors}{mark}")
|
||||
print(f"\nZeiten in ms. einzeln = Median ohne gleichzeitige Last; danach {args.users}"
|
||||
f" gleichzeitige Abrufe.\nGrenze 95. Perzentil: {args.limit_ms:.0f} ms."
|
||||
" Verbindungen bleiben offen (Keep-Alive), Weiterleitungen werden nicht verfolgt.")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user