Add phased stress testing with router resource monitoring
This commit is contained in:
9 files changed
+775
-5
No files matched your search
@@ -27,3 +27,7 @@ dist/
|
||||
/routershelf
|
||||
/deploy/padavan/supervisor.private.sh
|
||||
**/config.sh
|
||||
|
||||
# Python development artifacts
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -21,6 +21,7 @@ Read the relevant guide before changing a component:
|
||||
- `internal/theme/assets.go`: embeds assets under `internal/theme/nais/`.
|
||||
- `deploy/padavan/`: environment-driven supervisor and host firewall lifecycle.
|
||||
- `scripts/nat-plan.sh`: prints gateway configuration guidance; it does not modify the gateway.
|
||||
- `scripts/stress_test.py` and `scripts/tests/`: bounded load runner and localhost-only runner tests. Read `docs/stress-testing.md`; writing/editing the tool does not imply permission to load a live target.
|
||||
- `.env.example`: tracked configuration template; `.env` is private and ignored.
|
||||
- `examples/status-dashboard/`: independent historical BusyBox/Netcat example, with its guide in `docs/examples/`. Do not expose it using the public server's NAT rules.
|
||||
- `docs/`, `.github/`, `Makefile`, `project.json`: documentation, CI, local commands and metadata.
|
||||
@@ -55,7 +56,8 @@ Preserve these unless the user explicitly requests a change:
|
||||
Run from the repository root using Go 1.26 or a newer toolchain verified against the target kernel:
|
||||
|
||||
```sh
|
||||
make test # shell syntax, example config validation, Go tests
|
||||
make test # shell syntax, config validation, Python runner tests, Go tests
|
||||
make test-stress-tool # Python localhost-only tests; no live-router requests
|
||||
make check-shell # syntax only; does not execute deployment
|
||||
make check-config # side-effect-free validation using .env.example
|
||||
make build-mipsle # dist/routershelf-linux-mipsle, static Linux/MIPS LE soft-float
|
||||
@@ -63,7 +65,7 @@ make build-mipsle # dist/routershelf-linux-mipsle, static Linux/MIPS LE soft-f
|
||||
|
||||
For a private configuration check, use `ROUTERSHELF_ENV_FILE=/absolute/path/to/.env sh deploy/padavan/supervisor.example.sh --check-config`. The env file is sourced shell code: do not load an untrusted one. `make nat-plan` reads private `.env` and prints deployment addresses; do not run it just to produce public diagnostics.
|
||||
|
||||
There is no frontend build. Format Go with `gofmt`; use `.editorconfig` for other text. Keep deployment scripts compatible with the observed `/bin/sh` and BusyBox features.
|
||||
Python 3.10+ is required for runner tests on the development computer, not the router. There is no frontend build. Format Go with `gofmt`; use `.editorconfig` for other text. Keep deployment scripts compatible with the observed `/bin/sh` and BusyBox features.
|
||||
|
||||
Use `testing` and `net/http/httptest` for meaningful behavior checks. For handler changes cover the affected filesystem boundaries, methods, headers, index precedence, inline MIME/disposition, fallback listing and byte ranges. For config changes cover env/flag precedence and validation. For shell-only changes run syntax and dry config checks; never start NTP or alter a live firewall merely to check formatting. Documentation-only edits normally need link/accuracy checks, not a cross-build or deployment.
|
||||
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Stress testing
|
||||
|
||||
- Added a bounded read-only Python runner with phased concurrency, rate caps, optional router telemetry and stop thresholds.
|
||||
- Added keep-alive/fresh-TLS modes, static page/range/redirect preflight checks and private JSON/CSV/Markdown reports.
|
||||
- Verified the runner locally; no live-router stress load has been run.
|
||||
|
||||
### Static pages
|
||||
|
||||
- Render directory `index.html` and direct HTML requests from the existing shared root.
|
||||
|
||||
+3
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
## Development
|
||||
|
||||
Use Go 1.26 or a newer toolchain verified against the target kernel. From the repository root, run `make test` and `make build-mipsle`. Keep changes focused and describe user-visible behavior and validation. A desktop cross-build proves compilation, not target-kernel compatibility or successful boot persistence.
|
||||
Use Go 1.26 or a newer toolchain verified against the target kernel, and Python 3.10+ for the stress-runner tests. From the repository root, run `make test` and `make build-mipsle`. Keep changes focused and describe user-visible behavior and validation. A desktop cross-build proves compilation, not target-kernel compatibility or successful boot persistence.
|
||||
|
||||
Application changes belong in `cmd/routershelf`. Theme changes belong in `internal/theme/nais`; retain the upstream license and document local adaptations. Padavan-specific lifecycle rules belong in `deploy/padavan`. Keep the legacy status dashboard independent under `examples/status-dashboard`.
|
||||
|
||||
@@ -19,3 +19,5 @@ Record which checks actually ran. Do not claim a reboot or certificate renewal p
|
||||
Never attach private keys, certificate caches, full router exports, USB files, usernames/passwords, public-IP deployment values, or unredacted logs/screenshots. Use the example subnet, documentation IP range, and `files.example.com` in public issues. A sanitized minimal configuration is more useful than a full device dump.
|
||||
|
||||
Before the first publication, review staged files and metadata, configure the actual Git remote, and replace publication placeholders where needed. There is no automatic deploy or publish action in this project.
|
||||
|
||||
Stress-runner changes should be tested with `make test-stress-tool` against localhost and synthetic telemetry, not by loading the live deployment. Only run a live workload when requested, with the target and bounds clear. See [stress testing](docs/stress-testing.md).
|
||||
@@ -1,9 +1,10 @@
|
||||
GO ?= go
|
||||
PYTHON ?= python3
|
||||
BINARY := dist/routershelf-linux-mipsle
|
||||
|
||||
.PHONY: test build-mipsle check-shell check-config nat-plan
|
||||
.PHONY: test build-mipsle check-shell check-config nat-plan test-stress-tool
|
||||
|
||||
test: check-shell check-config
|
||||
test: check-shell check-config test-stress-tool
|
||||
$(GO) test ./...
|
||||
|
||||
check-shell:
|
||||
@@ -21,3 +22,6 @@ check-config:
|
||||
|
||||
nat-plan:
|
||||
sh scripts/nat-plan.sh
|
||||
|
||||
test-stress-tool:
|
||||
$(PYTHON) -B -m unittest discover -s scripts/tests -p 'test_*.py' -v
|
||||
@@ -43,6 +43,8 @@ Read [environment configuration](docs/configuration.md) for available values, pr
|
||||
|
||||
See [static-page behavior](docs/static-pages.md) for index precedence and supported assets.
|
||||
|
||||
Use the [stress-test guide](docs/stress-testing.md) for bounded load phases, router telemetry and private reports. The runner uses Python 3.10+ with no third-party packages.
|
||||
|
||||
## Repository layout
|
||||
|
||||
```text
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# Stress testing RouterShelf
|
||||
|
||||
The standard-library Python runner lives at `scripts/stress_test.py`. It exercises read-only HTTP/HTTPS requests from your computer; it is not installed on the router. Use Python 3.10+ and, optionally, an OpenSSH client with authorized key login. Test only an endpoint you administer.
|
||||
|
||||
The runner was validated against a temporary localhost server and synthetic telemetry. **No live-router stress workload has been run yet.** A build or runner test does not establish router capacity.
|
||||
|
||||
## What it covers
|
||||
|
||||
- Preflight and postflight root GET/HEAD, NAIS assets, hidden-path/traversal rejection, and HTTP-to-HTTPS redirect for HTTPS targets.
|
||||
- Optional directory index and direct HTML requests, checking HTML MIME type and absence of attachment disposition.
|
||||
- Optional additional asset paths, which are requested explicitly rather than discovered by crawling.
|
||||
- Optional byte-range downloads; preflight checks for HTTP 206 and Content-Range. Pseudorandom ranges can spread reads across a larger file.
|
||||
- Incremental concurrency, cooldown periods, optional sustained load, and keep-alive versus fresh connections/TLS handshakes.
|
||||
- Request counts, status/error counts, completed-response p50/p95/p99 latency, request rate and application-byte throughput.
|
||||
- Optional SSH samples of service PID/RSS/thread count, total system CPU, process share of total device CPU capacity, load average and estimated free/reclaimable memory.
|
||||
|
||||
All workload requests use GET/HEAD. The runner does not upload/delete files, alter firewall/configuration, clear caches, reboot, or modify the service. It does not execute browser JavaScript, simulate a full browser, test reboot/renewal, or replace a disk-health check. HTTPS uses normal certificate validation; there is no insecure TLS switch.
|
||||
|
||||
## Start with an offline plan
|
||||
|
||||
Run from the repository root. The base domain/public port come from private `.env` or exported `RS_*` values; `--url` overrides the target. The reader accepts literal assignments and shell quoting, but **does not source or execute** the env file. Derived shell expressions must be replaced by literal values for this tool.
|
||||
|
||||
```sh
|
||||
python3 scripts/stress_test.py --dry-run
|
||||
```
|
||||
|
||||
A dry run creates no connections or reports. Check the target, request paths and limits before starting. `--ssh router` uses an example SSH alias; substitute your own alias. SSH must address the same router whose service is receiving the load.
|
||||
|
||||
## Stage 1: small baseline
|
||||
|
||||
```sh
|
||||
python3 scripts/stress_test.py \
|
||||
--ssh router \
|
||||
--levels 1,2,4,8 --seconds 15 --cooldown 5 --max-rps 20
|
||||
```
|
||||
|
||||
This is the default four-stage workload, approximately 80 seconds plus pre/post checks and in-flight timeout handling. `--max-rps` is a **global** ceiling shared by all workers, not a per-worker rate. It includes load-stage requests, but not the small pre/post check set. Concurrency increases alone may not increase throughput if this ceiling is already reached.
|
||||
|
||||
Without `--ssh`, the HTTP test works but CPU/RSS/memory/PID safeguards cannot operate. Keep other home-network traffic stable so comparisons are meaningful. Telemetry SSH connections add some CPU overhead, particularly when measuring a small router; the system CPU figures include that overhead and other services.
|
||||
|
||||
## Stage 2: static pages and real file reads
|
||||
|
||||
Use paths that already exist. Do not copy the illustrative names unchanged unless those files are present. The runner will stop at preflight if a requested resource is missing or a check fails.
|
||||
|
||||
```sh
|
||||
python3 scripts/stress_test.py \
|
||||
--ssh router --levels 1,2,4,8 --seconds 20 --max-rps 30 \
|
||||
--html-path /demo/ --html-path /brochure.html \
|
||||
--asset-path /demo/style.css --asset-path /demo/app.js \
|
||||
--download-path /sample.bin --random-ranges --range-bytes 1048576
|
||||
```
|
||||
|
||||
`--html-path` and `--asset-path` can repeat. Use URL-encoded paths for spaces/non-ASCII names as needed. Only same-origin absolute request paths are accepted; absolute external URLs are rejected. No links from the requested HTML are automatically fetched.
|
||||
|
||||
A file larger than RAM with pseudorandom ranges is more representative of storage reads than repeatedly reading one tiny cached file, but operating-system and USB caches still affect results. The script does not clear them or claim a pure USB benchmark. Choose an existing nonempty public test file; the script will not create one.
|
||||
|
||||
## Stage 3: higher concurrency and soak
|
||||
|
||||
After baseline results are satisfactory:
|
||||
|
||||
```sh
|
||||
python3 scripts/stress_test.py \
|
||||
--ssh router --levels 1,2,4,8,16,32 \
|
||||
--seconds 30 --cooldown 10 --max-rps 100 --soak 180
|
||||
```
|
||||
|
||||
This is approximately seven minutes plus checks and in-flight handling. Optional file/page arguments can be added. It tests the configured workload; it does not prove the maximum number of Internet users. Do not interpret the rate ceiling as a measured service limit.
|
||||
|
||||
The runner limits concurrency to 32, stage duration to 300 seconds, soak to 600 seconds, global rate to 500 requests/second, request timeout to 15 seconds and response cap to 16 MiB. Defaults are lower. These are tool bounds, not a promise that the router can sustain their maximums.
|
||||
|
||||
## Stage 4: separate TLS handshake pressure
|
||||
|
||||
```sh
|
||||
python3 scripts/stress_test.py \
|
||||
--ssh router --levels 1,2,4,8 --seconds 15 --max-rps 20 \
|
||||
--fresh-connections
|
||||
```
|
||||
|
||||
The default mode reuses one HTTP/1.1 connection per worker within each stage. This mode closes after each request, forcing new connections and HTTPS handshakes. It can be substantially more CPU-intensive. Compare the two runs; do not assume all browser traffic behaves like either extreme.
|
||||
|
||||
## Stop conditions and recovery
|
||||
|
||||
Ctrl+C requests a controlled stop and still writes a partial report. Already-running requests finish or time out. Cooldown stages issue no load requests; SSH sampling can continue.
|
||||
|
||||
Automatic stop defaults:
|
||||
|
||||
| Condition | Default |
|
||||
| --- | --- |
|
||||
| Failed preflight | No load stages start |
|
||||
| Errors in last 20 completed load requests | More than 20% |
|
||||
| Service RSS, with SSH | Above 48 MiB |
|
||||
| Free + buffers + cache estimate, with SSH | Below 8 MiB |
|
||||
| Total system CPU, with SSH | Above 90% for 3 measured intervals |
|
||||
| Service PID changes, with SSH | Stop; possible restart/external update |
|
||||
| SSH sampling fails | 3 consecutive failures |
|
||||
|
||||
Thresholds are adjustable with `--max-error-ratio`, `--max-rss-mib`, `--min-memory-mib`, `--max-cpu-percent`, and `--monitor-interval`. Exceeding a threshold is a reason to stop and review, not automatic proof of a service bug. The memory estimate is not Linux MemAvailable and does not guarantee that every cached byte is immediately reclaimable. CPU percentages use total device capacity, not a one-core 0–400% convention.
|
||||
|
||||
If SSH is requested but initial sampling fails, no load starts. Postflight performs only a small health-check set; it does not restart or recover the router. Check the normal operations guide for recovery if the service becomes unavailable. Preserve other Internet and management services.
|
||||
|
||||
## Reports and interpretation
|
||||
|
||||
Each run creates a new private `outputs/stress/<UTC timestamp>-<PID>/` directory, or the path passed to `--output`. Existing directories are never overwritten. The output directory has mode 0700 on supported filesystems.
|
||||
|
||||
- `report.md`: phase summary and outcome.
|
||||
- `report.json`: full plan, pre/post checks, all request records and SSH samples.
|
||||
- `requests.csv`: individual request timings, status, bytes and errors.
|
||||
- `telemetry.csv`: time series of router CPU/RSS/memory/PID values.
|
||||
|
||||
Reports contain deployment URLs and request paths. Keep them private; `outputs/` is ignored by Git. Do not store results inside the public USB share. Exit code 0 means the configured run completed with checks passing; nonzero means stopped/incomplete or failed checks. It does not certify unlimited capacity.
|
||||
|
||||
Look for: zero errors, stable service PID, passing postflight, latency growth as load rises, RSS trends rather than one peak, CPU recovery during cooldown, and throughput appropriate to the chosen workload. Latencies describe completed responses and include network/TLS/body transfer; failed requests are counted separately. Bytes measure HTTP payload, not TLS/wire overhead. LAN hairpin results do not measure WAN uplink performance; repeat the same plan from an authorized external client to measure that path.
|
||||
|
||||
## Testing the runner itself
|
||||
|
||||
```sh
|
||||
make test-stress-tool
|
||||
```
|
||||
|
||||
This starts only a temporary localhost fixture and exercises reports, limits, read-only request behavior, env parsing, HEAD/keep-alive, ranges and synthetic telemetry stop logic. It does not connect to the configured deployment or need SSH. `make test` includes these checks; Python 3.10+ is therefore a development dependency, not a router runtime dependency.
|
||||
@@ -0,0 +1,486 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded, read-only RouterShelf load test; Python standard library only."""
|
||||
import argparse
|
||||
import collections
|
||||
import concurrent.futures
|
||||
import csv
|
||||
import datetime
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import random
|
||||
import shlex
|
||||
import signal
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
|
||||
def read_env(path):
|
||||
values = {}
|
||||
if not path.exists():
|
||||
return values
|
||||
for line in path.read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#'):
|
||||
continue
|
||||
if line.startswith('export '):
|
||||
line = line[7:]
|
||||
key, sep, value = line.partition('=')
|
||||
if not sep or not re.fullmatch(r'RS_[A-Z0-9_]+', key):
|
||||
continue
|
||||
words = shlex.split(value, comments=True)
|
||||
if len(words) != 1 or '$' in words[0] or '`' in words[0]:
|
||||
raise ValueError('Stress runner requires literal env values; shell code is never executed')
|
||||
values[key] = words[0]
|
||||
return values
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
return ordered[max(0, math.ceil(len(ordered) * fraction) - 1)]
|
||||
|
||||
|
||||
class Stop:
|
||||
def __init__(self):
|
||||
self.event = threading.Event()
|
||||
self.reason = None
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def abort(self, reason):
|
||||
with self.lock:
|
||||
if self.reason is None:
|
||||
self.reason = reason
|
||||
self.event.set()
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base_url, timeout=5, max_bytes=2 * 1024 * 1024, fresh=False):
|
||||
self.url = urllib.parse.urlsplit(base_url)
|
||||
self.timeout = timeout
|
||||
self.max_bytes = max_bytes
|
||||
self.fresh = fresh
|
||||
self.conn = None
|
||||
|
||||
def close(self):
|
||||
if self.conn:
|
||||
self.conn.close()
|
||||
self.conn = None
|
||||
|
||||
def request(self, path, method='GET', headers=None, expected=(200,)):
|
||||
start = time.monotonic()
|
||||
status = None
|
||||
received = 0
|
||||
response_headers = {}
|
||||
error = None
|
||||
try:
|
||||
if self.conn is None:
|
||||
cls = http.client.HTTPSConnection if self.url.scheme == 'https' else http.client.HTTPConnection
|
||||
extra = {'context': ssl.create_default_context()} if self.url.scheme == 'https' else {}
|
||||
self.conn = cls(self.url.hostname, self.url.port, timeout=self.timeout, **extra)
|
||||
self.conn.request(method, path, headers={'User-Agent': 'RouterShelfStress/1', **(headers or {})})
|
||||
if self.conn.sock:
|
||||
self.conn.sock.settimeout(max(.001, start + self.timeout - time.monotonic()))
|
||||
response = self.conn.getresponse()
|
||||
status = response.status
|
||||
response_headers = {k.lower(): v for k, v in response.getheaders()}
|
||||
body_deadline = start + self.timeout
|
||||
while True:
|
||||
remaining = body_deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError('overall request deadline exceeded')
|
||||
if self.conn.sock:
|
||||
self.conn.sock.settimeout(remaining)
|
||||
chunk = response.read1(min(65536, self.max_bytes + 1 - received))
|
||||
if not chunk:
|
||||
break
|
||||
received += len(chunk)
|
||||
if received > self.max_bytes:
|
||||
raise ValueError('response exceeded configured byte cap')
|
||||
response.close()
|
||||
if status not in expected:
|
||||
error = 'unexpected HTTP status'
|
||||
if response.will_close or self.fresh:
|
||||
self.close()
|
||||
except Exception as exc:
|
||||
error = type(exc).__name__ + ': ' + str(exc)[:160]
|
||||
self.close()
|
||||
return {'method': method, 'path': path, 'status': status, 'bytes': received,
|
||||
'ms': round((time.monotonic() - start) * 1000, 3), 'error': error,
|
||||
'headers': response_headers}
|
||||
|
||||
|
||||
def validate_url(url):
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password:
|
||||
raise ValueError('Use an HTTP(S) URL without credentials')
|
||||
if parsed.path not in ('', '/') or parsed.query or parsed.fragment:
|
||||
raise ValueError('Base URL must be the origin; choose pages with --html-path/--download-path')
|
||||
_ = parsed.port
|
||||
return url.rstrip('/')
|
||||
|
||||
|
||||
def validate_path(path):
|
||||
parsed = urllib.parse.urlsplit(path)
|
||||
if not path.startswith('/') or parsed.scheme or parsed.netloc or parsed.fragment or any(ord(c) < 32 for c in path):
|
||||
raise ValueError('Request paths must be local absolute URL paths, without a fragment')
|
||||
return path
|
||||
|
||||
|
||||
def remote_sample(alias, runtime):
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.@:-]+', alias) or alias.startswith('-'):
|
||||
raise ValueError('Invalid SSH alias')
|
||||
if not re.fullmatch(r'/[A-Za-z0-9_./-]+', runtime):
|
||||
raise ValueError('Invalid remote runtime directory')
|
||||
pidfile = shlex.quote(runtime.rstrip('/') + '/public-share-child.pid')
|
||||
command = (
|
||||
"head -n 1 /proc/stat; awk '/^cpu[0-9]+ /{n++} END{print \"cores\",n}' /proc/stat; "
|
||||
"head -n 1 /proc/loadavg; "
|
||||
"awk '/^(MemTotal|MemFree|Buffers|Cached):/{print}' /proc/meminfo; "
|
||||
"pid=$(cat " + pidfile + " 2>/dev/null); case \"$pid\" in ''|*[!0-9]*) exit 2;; esac; "
|
||||
"cat /proc/$pid/stat; awk '/^(VmRSS|Threads):/{print}' /proc/$pid/status"
|
||||
)
|
||||
result = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=4', alias, command],
|
||||
capture_output=True, text=True, timeout=7)
|
||||
if result.returncode:
|
||||
raise RuntimeError('SSH telemetry failed; check key login and service PID')
|
||||
sample = {'time': datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
||||
memory = {}
|
||||
for line in result.stdout.splitlines():
|
||||
fields = line.split()
|
||||
if line.startswith('cpu '):
|
||||
ticks = list(map(int, fields[1:9]))
|
||||
sample['cpu_ticks'] = sum(ticks)
|
||||
sample['cpu_idle_ticks'] = ticks[3] + ticks[4]
|
||||
elif line.startswith('cores '):
|
||||
sample['cores'] = int(fields[1])
|
||||
elif fields and fields[0] in ('MemTotal:', 'MemFree:', 'Buffers:', 'Cached:', 'VmRSS:', 'Threads:'):
|
||||
memory[fields[0].rstrip(':')] = int(fields[1])
|
||||
elif re.match(r'^\d+ \(', line):
|
||||
# Process names may contain spaces; fields after the last ')' start at stat field 3.
|
||||
tail = line.rsplit(')', 1)[1].split()
|
||||
sample['pid'] = int(line.split(' ', 1)[0])
|
||||
sample['process_ticks'] = int(tail[11]) + int(tail[12])
|
||||
elif re.match(r'^\d+\.\d+ ', line):
|
||||
sample['load1'] = float(fields[0])
|
||||
sample['rss_mib'] = memory['VmRSS'] / 1024
|
||||
sample['free_reclaimable_estimate_mib'] = sum(memory[k] for k in ('MemFree', 'Buffers', 'Cached')) / 1024
|
||||
sample['memory_total_mib'] = memory['MemTotal'] / 1024
|
||||
sample['threads'] = memory['Threads']
|
||||
if 'pid' not in sample or 'cpu_ticks' not in sample:
|
||||
raise RuntimeError('Incomplete SSH telemetry')
|
||||
return sample
|
||||
|
||||
|
||||
def monitor(args, stop, samples, finished):
|
||||
previous = None
|
||||
failures = 0
|
||||
high_cpu = 0
|
||||
while not finished.is_set() and not stop.event.is_set():
|
||||
try:
|
||||
current = remote_sample(args.ssh, args.remote_runtime_dir)
|
||||
failures = 0
|
||||
if previous:
|
||||
if current['pid'] != previous['pid']:
|
||||
stop.abort('Service PID changed during test (restart or external update)')
|
||||
delta = current['cpu_ticks'] - previous['cpu_ticks']
|
||||
if delta > 0:
|
||||
current['system_cpu_percent'] = round(100 * (1 - (current['cpu_idle_ticks'] - previous['cpu_idle_ticks']) / delta), 2)
|
||||
if current['pid'] == previous['pid']:
|
||||
current['process_cpu_percent_of_device'] = round(100 * (current['process_ticks'] - previous['process_ticks']) / delta, 2)
|
||||
samples.append(current)
|
||||
if current['rss_mib'] > args.max_rss_mib:
|
||||
stop.abort('Process RSS crossed configured threshold')
|
||||
if current['free_reclaimable_estimate_mib'] < args.min_memory_mib:
|
||||
stop.abort('Free plus buffers/cache estimate crossed configured threshold')
|
||||
high_cpu = high_cpu + 1 if current.get('system_cpu_percent', 0) > args.max_cpu_percent else 0
|
||||
if high_cpu >= 3:
|
||||
stop.abort('System CPU stayed above threshold for three samples')
|
||||
previous = current
|
||||
except Exception as exc:
|
||||
failures += 1
|
||||
samples.append({'time': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'error': str(exc)})
|
||||
if failures >= 3:
|
||||
stop.abort('SSH telemetry failed three consecutive times')
|
||||
finished.wait(args.monitor_interval)
|
||||
|
||||
|
||||
def phase(args, workers, seconds, endpoints, stop):
|
||||
start = time.monotonic()
|
||||
deadline = start + seconds
|
||||
rate_lock = threading.Lock()
|
||||
next_request = start
|
||||
records = []
|
||||
record_lock = threading.Lock()
|
||||
|
||||
def worker(worker_id):
|
||||
nonlocal next_request
|
||||
client = Client(args.url, args.timeout, args.max_bytes, args.fresh_connections)
|
||||
index = worker_id
|
||||
rng = random.Random(worker_id)
|
||||
try:
|
||||
while not stop.event.is_set() and time.monotonic() < deadline:
|
||||
with rate_lock:
|
||||
now = time.monotonic()
|
||||
reserved = max(now, next_request)
|
||||
next_request = reserved + 1 / args.max_rps
|
||||
wait = reserved - time.monotonic()
|
||||
if reserved >= deadline or stop.event.wait(max(0, wait)):
|
||||
break
|
||||
path, method, headers = endpoints[index % len(endpoints)]
|
||||
index += 1
|
||||
if args.random_ranges and path == args.download_path:
|
||||
offset = rng.randrange(max(1, args.download_size - args.range_bytes + 1))
|
||||
end = min(args.download_size - 1, offset + args.range_bytes - 1)
|
||||
headers = {'Range': 'bytes={}-{}'.format(offset, end)}
|
||||
record = client.request(path, method, headers, (206,) if headers.get('Range') else (200,))
|
||||
with record_lock:
|
||||
records.append(record)
|
||||
if len(records) >= 20:
|
||||
recent = records[-20:]
|
||||
if sum(r['error'] is not None for r in recent) / len(recent) > args.max_error_ratio:
|
||||
stop.abort('Recent request error ratio crossed configured threshold')
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
list(pool.map(worker, range(workers)))
|
||||
elapsed = time.monotonic() - start
|
||||
successes = [r for r in records if not r['error']]
|
||||
latency = [r['ms'] for r in successes]
|
||||
return {'workers': workers, 'requested_seconds': seconds, 'elapsed_seconds': round(elapsed, 3),
|
||||
'requests': len(records), 'successes': len(successes), 'errors': len(records) - len(successes),
|
||||
'rps': round(len(records) / elapsed, 3),
|
||||
'mib_per_second': round(sum(r['bytes'] for r in successes) / elapsed / 1048576, 3),
|
||||
'p50_ms': percentile(latency, .5), 'p95_ms': percentile(latency, .95), 'p99_ms': percentile(latency, .99),
|
||||
'statuses': dict(collections.Counter(str(r['status']) for r in records)), 'records': records}
|
||||
|
||||
|
||||
def endpoints_for(args):
|
||||
endpoints = [('/', 'GET', {}), ('/_nais/autoindex.css', 'GET', {}), ('/_nais/autoindex.js', 'GET', {}), ('/', 'HEAD', {})]
|
||||
for path in args.html_path + args.asset_path:
|
||||
endpoints.append((path, 'GET', {}))
|
||||
if args.download_path:
|
||||
endpoints.append((args.download_path, 'GET', {'Range': 'bytes=0-' + str(args.range_bytes - 1)}))
|
||||
return endpoints
|
||||
|
||||
|
||||
def health(args):
|
||||
client = Client(args.url, args.timeout, args.max_bytes)
|
||||
checks = []
|
||||
try:
|
||||
for path, method, headers in endpoints_for(args):
|
||||
checks.append(client.request(path, method, headers, (200, 206)))
|
||||
checks.append(client.request('/.env', expected=(404,)))
|
||||
checks.append(client.request('/../etc/passwd', expected=(404,)))
|
||||
for path in args.html_path:
|
||||
html = next(c for c in checks if c['path'] == path and c['method'] == 'GET')
|
||||
if not html['error'] and (not html['headers'].get('content-type', '').startswith('text/html') or 'attachment' in html['headers'].get('content-disposition', '')):
|
||||
html['error'] = 'HTML MIME/disposition regression'
|
||||
if args.download_path:
|
||||
download = next(c for c in checks if c['path'] == args.download_path)
|
||||
if not download['error'] and (download['status'] != 206 or not download['headers'].get('content-range', '').startswith('bytes 0-')):
|
||||
download['error'] = 'Byte-range response regression'
|
||||
if args.random_ranges:
|
||||
size_check = client.request(args.download_path, 'HEAD')
|
||||
try:
|
||||
args.download_size = int(size_check['headers'].get('content-length', '0'))
|
||||
if args.download_size <= 0:
|
||||
size_check['error'] = 'Random ranges require a nonempty file with Content-Length'
|
||||
except ValueError:
|
||||
size_check['error'] = 'Invalid download Content-Length'
|
||||
checks.append(size_check)
|
||||
if args.http_url:
|
||||
redirect_client = Client(args.http_url, args.timeout, args.max_bytes)
|
||||
try:
|
||||
redirect = redirect_client.request('/', 'HEAD', expected=(301,302,307,308))
|
||||
if not redirect['error'] and redirect['headers'].get('location') != args.url + '/':
|
||||
redirect['error'] = 'Unexpected HTTPS redirect target'
|
||||
redirect['path'] = 'HTTP redirect /'
|
||||
checks.append(redirect)
|
||||
finally:
|
||||
redirect_client.close()
|
||||
|
||||
finally:
|
||||
client.close()
|
||||
return checks
|
||||
|
||||
|
||||
def write_report(output, report):
|
||||
valid_samples = [s for s in report['telemetry'] if 'rss_mib' in s]
|
||||
report['resource_summary'] = {
|
||||
'peak_rss_mib': max((s['rss_mib'] for s in valid_samples), default=None),
|
||||
'peak_system_cpu_percent': max((s['system_cpu_percent'] for s in valid_samples if 'system_cpu_percent' in s), default=None),
|
||||
'peak_process_cpu_percent_of_device': max((s['process_cpu_percent_of_device'] for s in valid_samples if 'process_cpu_percent_of_device' in s), default=None),
|
||||
'minimum_free_reclaimable_estimate_mib': min((s['free_reclaimable_estimate_mib'] for s in valid_samples), default=None),
|
||||
'observed_pids': sorted(set(s['pid'] for s in valid_samples)),
|
||||
}
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
output.chmod(0o700)
|
||||
(output / 'report.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
with (output / 'requests.csv').open('w', newline='') as f:
|
||||
writer = csv.DictWriter(f, fieldnames=['phase', 'workers', 'method', 'path', 'status', 'bytes', 'ms', 'error'])
|
||||
writer.writeheader()
|
||||
for index, stage in enumerate(report['phases']):
|
||||
for record in stage['records']:
|
||||
writer.writerow({'phase': index + 1, 'workers': stage['workers'], **{k: record[k] for k in ['method', 'path', 'status', 'bytes', 'ms', 'error']}})
|
||||
with (output / 'telemetry.csv').open('w', newline='') as f:
|
||||
writer = csv.DictWriter(f, fieldnames=['time', 'pid', 'rss_mib', 'system_cpu_percent', 'process_cpu_percent_of_device', 'free_reclaimable_estimate_mib', 'threads', 'load1', 'error'], extrasaction='ignore')
|
||||
writer.writeheader()
|
||||
writer.writerows(report['telemetry'])
|
||||
rows = ['# RouterShelf stress report', '', '**Outcome:** ' + report['outcome'], '',
|
||||
'Target: ' + report['url'], '', 'Connection mode: ' + report['connection_mode'], '',
|
||||
'| Workers | Requests | Errors | req/s | MiB/s | p50 ms | p95 ms | p99 ms |',
|
||||
'| --- | --- | --- | --- | --- | --- | --- | --- |']
|
||||
for stage in report['phases']:
|
||||
rows.append('| ' + ' | '.join(str(stage[k]) for k in ['workers', 'requests', 'errors', 'rps', 'mib_per_second', 'p50_ms', 'p95_ms', 'p99_ms']) + ' |')
|
||||
if valid_samples:
|
||||
summary = report['resource_summary']
|
||||
rows += ['', '## Router resources', '',
|
||||
'Peak service RSS: {} MiB.'.format(round(summary['peak_rss_mib'], 2)),
|
||||
'Peak sampled system CPU: {}%.'.format(summary['peak_system_cpu_percent']),
|
||||
'Peak sampled service CPU, total device capacity: {}%.'.format(summary['peak_process_cpu_percent_of_device']),
|
||||
'Minimum free + buffers/cache estimate: {} MiB.'.format(round(summary['minimum_free_reclaimable_estimate_mib'], 2))]
|
||||
else:
|
||||
rows += ['', 'Router resources were not collected.']
|
||||
if report['stop_reason']:
|
||||
rows += ['', 'Stopped because: ' + report['stop_reason']]
|
||||
rows += ['', 'Telemetry and per-request details are in report.json and requests.csv.',
|
||||
'CPU percentages use total device CPU capacity. Free memory is an estimate including buffers/cache.',
|
||||
'Reports contain deployment URLs and paths; keep them private.']
|
||||
(output / 'report.md').write_text('\n'.join(rows) + '\n')
|
||||
|
||||
|
||||
def arguments(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--env', type=Path, default=Path('.env'))
|
||||
parser.add_argument('--url')
|
||||
parser.add_argument('--levels', default='1,2,4,8')
|
||||
parser.add_argument('--seconds', type=float, default=15)
|
||||
parser.add_argument('--cooldown', type=float, default=5)
|
||||
parser.add_argument('--soak', type=float, default=0, help='Additional stage at highest concurrency')
|
||||
parser.add_argument('--max-rps', type=float, default=20, help='Global request-rate ceiling, shared across workers')
|
||||
parser.add_argument('--timeout', type=float, default=5)
|
||||
parser.add_argument('--max-bytes', type=int, default=2 * 1024 * 1024)
|
||||
parser.add_argument('--range-bytes', type=int, default=1024 * 1024)
|
||||
parser.add_argument('--html-path', action='append', default=[], help='Repeat for directory index and direct HTML checks')
|
||||
parser.add_argument('--asset-path', action='append', default=[])
|
||||
parser.add_argument('--http-url', help='HTTP origin for redirect check; derived for HTTPS targets')
|
||||
parser.add_argument('--download-path')
|
||||
parser.add_argument('--random-ranges', action='store_true', help='Read deterministic pseudorandom file sections instead of repeating its start')
|
||||
parser.add_argument('--fresh-connections', action='store_true', help='New connection/TLS handshake for every request')
|
||||
parser.add_argument('--ssh', help='Optional SSH alias for router telemetry; key authentication only')
|
||||
parser.add_argument('--remote-runtime-dir')
|
||||
parser.add_argument('--monitor-interval', type=float, default=3)
|
||||
parser.add_argument('--max-rss-mib', type=float, default=48)
|
||||
parser.add_argument('--min-memory-mib', type=float, default=8)
|
||||
parser.add_argument('--max-cpu-percent', type=float, default=90)
|
||||
parser.add_argument('--max-error-ratio', type=float, default=.2)
|
||||
parser.add_argument('--output', type=Path)
|
||||
parser.add_argument('--dry-run', action='store_true', help='Show plan without any HTTP or SSH connection')
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
env = read_env(args.env)
|
||||
domain = os.environ.get('RS_DOMAIN') or env.get('RS_DOMAIN')
|
||||
port = os.environ.get('RS_PUBLIC_HTTPS_PORT') or env.get('RS_PUBLIC_HTTPS_PORT', '443')
|
||||
args.url = validate_url(args.url or ('https://' + domain + (':' + port if port != '443' else '') if domain else ''))
|
||||
if args.http_url:
|
||||
args.http_url = validate_url(args.http_url)
|
||||
elif args.url.startswith('https://'):
|
||||
http_port = env.get('RS_PUBLIC_HTTP_PORT', '80')
|
||||
hostname = urllib.parse.urlsplit(args.url).hostname
|
||||
if ':' in hostname:
|
||||
hostname = '[' + hostname + ']'
|
||||
args.http_url = validate_url('http://' + hostname + (':' + http_port if http_port != '80' else ''))
|
||||
args.levels = [int(n) for n in args.levels.split(',')]
|
||||
if not args.levels or args.levels != sorted(set(args.levels)) or not all(1 <= n <= 32 for n in args.levels):
|
||||
raise ValueError('Levels must be increasing distinct integers between 1 and 32')
|
||||
if not 0 < args.seconds <= 300 or not 0 <= args.soak <= 600 or not 0 <= args.cooldown <= 60:
|
||||
raise ValueError('Phase <=300s, soak <=600s, cooldown <=60s; durations must be nonnegative')
|
||||
if not 0 < args.max_rps <= 500 or not 0 < args.timeout <= 15 or not 1 <= args.monitor_interval <= 30:
|
||||
raise ValueError('Rate <=500 req/s, timeout <=15s, telemetry interval 1..30s')
|
||||
if not 0 < args.max_error_ratio <= 1 or not 0 < args.max_cpu_percent <= 100 or args.max_rss_mib <= 0 or args.min_memory_mib < 0:
|
||||
raise ValueError('Invalid resource/error threshold')
|
||||
if not 1 <= args.range_bytes <= args.max_bytes <= 16 * 1024 * 1024:
|
||||
raise ValueError('Require 1 <= range-bytes <= max-bytes <=16MiB')
|
||||
if args.random_ranges and not args.download_path:
|
||||
raise ValueError('--random-ranges requires --download-path')
|
||||
for path in args.html_path + args.asset_path + ([args.download_path] if args.download_path else []):
|
||||
if path:
|
||||
validate_path(path)
|
||||
args.remote_runtime_dir = args.remote_runtime_dir or env.get('RS_RUNTIME_DIR', '/tmp')
|
||||
if args.output is None:
|
||||
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
|
||||
args.output = Path('outputs/stress') / (stamp + '-' + str(os.getpid()))
|
||||
if args.output.exists():
|
||||
raise ValueError('Output directory already exists; refusing to overwrite results')
|
||||
except (ValueError, OSError) as exc:
|
||||
parser.error(str(exc))
|
||||
return args
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = arguments(argv)
|
||||
plan = {'url': args.url, 'levels': args.levels, 'seconds_per_phase': args.seconds, 'cooldown_seconds': args.cooldown,
|
||||
'soak_seconds': args.soak, 'max_rps': args.max_rps, 'fresh_connections': args.fresh_connections,
|
||||
'ssh_telemetry': bool(args.ssh), 'http_redirect_origin': args.http_url,
|
||||
'random_ranges': args.random_ranges, 'response_byte_cap': args.max_bytes, 'range_bytes': args.range_bytes,
|
||||
'stop_thresholds': {'rss_mib': args.max_rss_mib, 'memory_estimate_mib': args.min_memory_mib,
|
||||
'cpu_percent': args.max_cpu_percent, 'recent_error_ratio': args.max_error_ratio}, 'endpoints': [p for p, _, _ in endpoints_for(args)], 'output': str(args.output)}
|
||||
print(json.dumps(plan, indent=2), flush=True)
|
||||
if args.dry_run:
|
||||
return 0
|
||||
stop = Stop()
|
||||
finished = threading.Event()
|
||||
samples = []
|
||||
report = {'url': args.url, 'started_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
'plan': plan, 'connection_mode': 'fresh TLS/connection per request' if args.fresh_connections else 'per-worker keep-alive',
|
||||
'before': [], 'after': [], 'phases': [], 'telemetry': samples}
|
||||
old_handler = signal.signal(signal.SIGINT, lambda *_: stop.abort('Interrupted by user'))
|
||||
telemetry = None
|
||||
try:
|
||||
report['before'] = health(args)
|
||||
if any(c['error'] for c in report['before']):
|
||||
stop.abort('Preflight checks failed; no load stages started')
|
||||
if args.ssh and not stop.event.is_set():
|
||||
# Check monitoring before starting any load.
|
||||
samples.append(remote_sample(args.ssh, args.remote_runtime_dir))
|
||||
telemetry = threading.Thread(target=monitor, args=(args, stop, samples, finished), daemon=True)
|
||||
telemetry.start()
|
||||
for workers in args.levels:
|
||||
if stop.event.is_set():
|
||||
break
|
||||
stage = phase(args, workers, args.seconds, endpoints_for(args), stop)
|
||||
report['phases'].append(stage)
|
||||
print('workers={} requests={} errors={} p95={}ms'.format(workers, stage['requests'], stage['errors'], stage['p95_ms']), flush=True)
|
||||
if stop.event.wait(args.cooldown):
|
||||
break
|
||||
if args.soak and not stop.event.is_set():
|
||||
report['phases'].append(phase(args, args.levels[-1], args.soak, endpoints_for(args), stop))
|
||||
stop.event.wait(args.cooldown)
|
||||
report['after'] = health(args)
|
||||
except Exception as exc:
|
||||
stop.abort(type(exc).__name__ + ': ' + str(exc))
|
||||
finally:
|
||||
finished.set()
|
||||
if telemetry:
|
||||
telemetry.join(timeout=8)
|
||||
signal.signal(signal.SIGINT, old_handler)
|
||||
report['stop_reason'] = stop.reason
|
||||
report['finished_utc'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
failed = bool(stop.reason) or any(c['error'] for c in report['after']) or any(p['errors'] for p in report['phases'])
|
||||
report['outcome'] = 'incomplete/failed checks' if failed else 'completed configured workload'
|
||||
write_report(args.output, report)
|
||||
print('Report: ' + str(args.output / 'report.md'), flush=True)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,144 @@
|
||||
import contextlib
|
||||
import http.server
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from types import SimpleNamespace
|
||||
import sys
|
||||
|
||||
spec = importlib.util.spec_from_file_location('stress', Path(__file__).parents[1] / 'stress_test.py')
|
||||
stress = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(stress)
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_HEAD(self):
|
||||
self.do_GET()
|
||||
|
||||
def do_GET(self):
|
||||
missing = self.path in ('/.env', '/../etc/passwd')
|
||||
body = b'<h1>Test</h1>' if self.path == '/page.html' else b'healthy'
|
||||
is_range = self.path == '/download.bin' and self.headers.get('Range')
|
||||
self.send_response(206 if is_range else (404 if missing else 200))
|
||||
if is_range:
|
||||
self.send_header('Content-Range', 'bytes 0-6/7')
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.send_header('Content-Type', 'text/html' if self.path == '/page.html' else 'text/plain')
|
||||
self.end_headers()
|
||||
if self.command != 'HEAD':
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
class QuietServer(http.server.ThreadingHTTPServer):
|
||||
def handle_error(self, request, client_address):
|
||||
if not isinstance(sys.exc_info()[1], (ConnectionResetError, BrokenPipeError)):
|
||||
super().handle_error(request, client_address)
|
||||
|
||||
|
||||
class StressTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.server = QuietServer(('127.0.0.1', 0), Handler)
|
||||
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.url = 'http://127.0.0.1:' + str(cls.server.server_port)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.shutdown()
|
||||
cls.server.server_close()
|
||||
cls.thread.join()
|
||||
|
||||
def test_full_local_run_and_report(self):
|
||||
with tempfile.TemporaryDirectory() as temp, contextlib.redirect_stdout(io.StringIO()):
|
||||
output = Path(temp) / 'report'
|
||||
code = stress.main(['--url', self.url, '--env', str(Path(temp) / 'absent.env'),
|
||||
'--levels', '1,2', '--seconds', '.15', '--cooldown', '0',
|
||||
'--max-rps', '40', '--html-path', '/page.html', '--output', str(output)])
|
||||
report = json.loads((output / 'report.json').read_text())
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(len(report['phases']), 2)
|
||||
self.assertTrue(all(stage['requests'] > 0 and stage['errors'] == 0 for stage in report['phases']))
|
||||
self.assertTrue((output / 'requests.csv').exists())
|
||||
self.assertTrue((output / 'report.md').exists())
|
||||
self.assertEqual(report['before'][-1]['status'], 404)
|
||||
|
||||
def test_client_status_and_body_cap(self):
|
||||
client = stress.Client(self.url, max_bytes=3)
|
||||
try:
|
||||
result = client.request('/')
|
||||
self.assertIn('byte cap', result['error'])
|
||||
finally:
|
||||
client.close()
|
||||
client = stress.Client(self.url)
|
||||
try:
|
||||
self.assertIsNotNone(client.request('/.env')['error'])
|
||||
self.assertIsNone(client.request('/.env', expected=(404,))['error'])
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
def test_range_and_error_abort(self):
|
||||
args = stress.arguments(['--url', self.url, '--download-path', '/download.bin', '--random-ranges'])
|
||||
self.assertTrue(all(not c['error'] for c in stress.health(args)))
|
||||
args.max_rps = 100
|
||||
stop = stress.Stop()
|
||||
stage = stress.phase(args, 2, 1, [('/.env', 'GET', {})], stop)
|
||||
self.assertTrue(stop.event.is_set())
|
||||
self.assertGreaterEqual(stage['errors'], 20)
|
||||
self.assertIn('error ratio', stop.reason)
|
||||
|
||||
def test_env_is_not_executed(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
path = Path(temp) / '.env'
|
||||
path.write_text('RS_DOMAIN=files.example.com\nRS_RUNTIME_DIR="/tmp" # note\n')
|
||||
self.assertEqual(stress.read_env(path)['RS_DOMAIN'], 'files.example.com')
|
||||
path.write_text('RS_DOMAIN=$(touch /tmp/not-executed)\n')
|
||||
with self.assertRaises(ValueError):
|
||||
stress.read_env(path)
|
||||
|
||||
def test_dry_run_does_not_connect(self):
|
||||
with tempfile.TemporaryDirectory() as temp, contextlib.redirect_stdout(io.StringIO()):
|
||||
output = Path(temp) / 'results'
|
||||
self.assertEqual(stress.main(['--url', 'https://files.example.com', '--env', str(Path(temp) / 'absent'),
|
||||
'--output', str(output), '--dry-run']), 0)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_telemetry_parser_and_memory_stop(self):
|
||||
tail = ['S'] + ['0'] * 20
|
||||
tail[11], tail[12] = '12', '3'
|
||||
stdout = 'cpu 100 0 10 500 2 0 0 0 0 0\ncores 4\n0.01 0.02 0.03 1/60 9\nMemTotal: 126280 kB\nMemFree: 16000 kB\nBuffers: 26000 kB\nCached: 36000 kB\n123 (name with spaces) ' + ' '.join(tail) + '\nVmRSS: 8192 kB\nThreads: 5\n'
|
||||
with patch.object(stress.subprocess, 'run', return_value=SimpleNamespace(returncode=0, stdout=stdout)):
|
||||
sample = stress.remote_sample('router', '/tmp')
|
||||
self.assertEqual(sample['process_ticks'], 15)
|
||||
self.assertEqual(sample['rss_mib'], 8)
|
||||
args = SimpleNamespace(ssh='router', remote_runtime_dir='/tmp', max_rss_mib=7,
|
||||
min_memory_mib=8, max_cpu_percent=90, monitor_interval=.01)
|
||||
stop = stress.Stop()
|
||||
samples = []
|
||||
with patch.object(stress, 'remote_sample', return_value=sample):
|
||||
stress.monitor(args, stop, samples, threading.Event())
|
||||
self.assertTrue(stop.event.is_set())
|
||||
self.assertIn('RSS', stop.reason)
|
||||
|
||||
def test_limits_percentiles_and_paths(self):
|
||||
self.assertEqual(stress.percentile([40, 10, 20, 30], .95), 40)
|
||||
self.assertIsNone(stress.percentile([], .95))
|
||||
for path in ['https://other.example/', '//other.example/', '/x\nheader']:
|
||||
with self.assertRaises(ValueError):
|
||||
stress.validate_path(path)
|
||||
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
stress.arguments(['--url', self.url, '--levels', '64'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user