Record architecture B corrections and measurement tooling
No files matched your search
@@ -0,0 +1,74 @@
|
||||
# Architecture B adaptation
|
||||
|
||||
Copied tracked JMeter tooling and PasswordHash source from read-only Architecture A
|
||||
revision `2117236366130775214d9fd2611984d4348f2b79`. Original file SHA-256 hashes
|
||||
are preserved in source-manifest.json. Private credentials, generated hash binaries,
|
||||
raw experiment runs and installed JMeter/Java/plugins were not copied. Historical
|
||||
26-thread calibration evidence is retained and labelled as Architecture A evidence.
|
||||
|
||||
## Compatibility findings and changes
|
||||
|
||||
All six generated JMX plans remain byte-for-byte identical to the source. The public
|
||||
HTTPS routes, DTO fields, opaque bearer-ticket login/renewal, patient ownership and
|
||||
professional assignment interfaces are preserved by B. There is no need to replace
|
||||
scenario requests or add internal service calls. Workload mix, Gaussian pacing,
|
||||
random seed, ramp, 30-minute warmup and four-hour measurement defaults are retained.
|
||||
No automatic retries or acceptance of 503/504 as success were added. B's admission
|
||||
limits may make a workload fail; those failures must remain visible.
|
||||
|
||||
Account provisioning did require adaptation: create-accounts.py now generates a
|
||||
private COPY of B appsettings.json instead of A gateway.env. It supports both the
|
||||
native installer's colon-delimited keys and nested example JSON, retains existing
|
||||
settings/accounts, refuses regeneration and writes mode-600 files in a private new
|
||||
directory. Mixed flat/nested account definitions are rejected. PasswordHash is built
|
||||
from source. Installation/restart remains an explicit test-host administration step;
|
||||
use root:healthapp-b mode 640 for installed config. The runner records architecture B.
|
||||
|
||||
Python 3.13+ enables additional strict X.509 profile checks. The B-generated prototype
|
||||
certificate lacks Authority Key Identifier, so the unchanged Python preflight failed
|
||||
on Python 3.14. tls.application_context removes only VERIFY_X509_STRICT, preserving
|
||||
CERT_REQUIRED, trusted-CA chain/signature/expiry verification and hostname checks.
|
||||
There is no trust-all fallback. This matches standard verification used by older
|
||||
Python versions. JMeter's inherited HTTPS client behavior is unchanged: encrypted
|
||||
traffic, but its stock client does not establish certificate-validation correctness.
|
||||
Use the Python preflight; this workload is not a TLS security test.
|
||||
|
||||
## Running
|
||||
|
||||
Follow README.md to build the hash helper, prepare accounts/history outside the
|
||||
measurement window and run the selected scenario against B's host/port (default
|
||||
5443). The native unit is healthapp-b.service, configuration is under /etc/healthapp-b,
|
||||
and public client CA is healthapp-ca.crt. Never export installed configuration to the
|
||||
load generator; it contains database/private-key secrets. No A database is accessed.
|
||||
|
||||
Install JMeter 5.6.3, compatible Java (the existing launcher uses Java 17), jpgc-perfmon
|
||||
2.1 and Matplotlib on the load generator. The default launcher path is
|
||||
~/.local/bin/jmeter, override with --jmeter. These dependencies are not bundled.
|
||||
For isolated checks use --no-perfmon --no-shelly; real experiments need separately
|
||||
verified agents/meter settings. Original monitoring host defaults are configurable
|
||||
and must be checked for the B test environment.
|
||||
|
||||
## Verification
|
||||
|
||||
- generate-plans.py regenerated six plans identically to their source hashes.
|
||||
- verify-plans.py passed HTTPS contract-stub checks: preparation, recording/review/
|
||||
correction/mixed/professional, dynamic IDs, short-lived token renewal, unexpected
|
||||
503 invalidation, and synthetic four-hour power integration.
|
||||
- verify-idle.py passed: no application requests, no login/preflight, warmup excluded.
|
||||
- verify-tls.py passed: trusted CA accepted, wrong hostname and untrusted CA rejected.
|
||||
- verify-report.py passed: one-second timing, aggregation and missing-data handling.
|
||||
- verify-b.py is a reproducible short smoke against the actual published B host,
|
||||
verified HTTPS and a disposable PostgreSQL 18.6 database with restricted runtime
|
||||
credentials. All six scenarios passed with zero failed HTTP requests (idle sent zero HTTP requests). See [verification-b.json](verification-b.json) for counts and the tested application DLL hash.
|
||||
|
||||
Reproduce real-host smoke after building a new B release and hash helper:
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/verify-b.py --release /absolute/path/to/release --dotnet /absolute/path/to/dotnet
|
||||
```
|
||||
|
||||
This optional check requires Docker access and the PostgreSQL image; Docker is test
|
||||
infrastructure, not an application deployment requirement. It uses synthetic data,
|
||||
local ephemeral ports and a unique disposable container, then cleans up. PerfMon and
|
||||
Shelly are disabled. No full-duration capacity run, physical testserver load, live
|
||||
monitoring validation or energy comparison is established by these smoke tests.
|
||||
@@ -0,0 +1,316 @@
|
||||
# Architecture B JMeter workloads
|
||||
|
||||
See [adaptation and verification](ARCHITECTURE-B.md) for provenance, compatibility and test limits.
|
||||
|
||||
|
||||
JMeter 5.6.3 is installed on this development computer at `~/.local/bin/jmeter`.
|
||||
Its launcher uses the installed Java 17; the default Java 26 cannot compile
|
||||
JMeter's bundled Groovy scripts. The `jpgc-perfmon` 2.1 plugin is installed for live server monitoring.
|
||||
|
||||
Runs default to **30 minutes of warmup + 4 hours of measurement**. A few additional
|
||||
seconds allow startup/draining. Only requests entirely inside the four-hour window
|
||||
appear in `measured.csv`. Full raw samples remain in `samples.csv`. `run.json` and
|
||||
`timeline.json` identify exact UTC measurement boundaries for your external meter.
|
||||
|
||||
## Scenarios
|
||||
|
||||
| Plan | User workflow |
|
||||
|---|---|
|
||||
| `recording` | View guidance/profile, save a home resting reading, retrieve it, view overview. |
|
||||
| `review` | Profile, latest reading, filtered history, numerical insights, trends, overview. |
|
||||
| `correction` | Record an erroneous/duplicate entry, correct it, check overview, delete that entry, confirm removal. |
|
||||
| `mixed` | Expected session mix: 65% review, 30% recording, 5% correction. |
|
||||
| `professional` | Assigned-patient list, profile/latest/history/insights/trends/overview; no writes. |
|
||||
| `idle` | No measured API traffic; application and PostgreSQL remain running for the same observation period. |
|
||||
|
||||
Each thread retains its own account, patient and opaque token. Login occurs initially
|
||||
and before token expiry, including during four-hour runs. Requests use the single Architecture B HTTPS application;
|
||||
IDs come from actual responses. Nonexpected HTTP statuses and semantic failures stop
|
||||
the affected user and invalidate the run. Only newly created correction-scenario
|
||||
observations are deleted. Baseline and ordinary recording observations remain.
|
||||
|
||||
Per-user seeded random generators produce independent **Gaussian delays**:
|
||||
interaction mean 1 second, standard deviation 250 ms, minimum 500 ms; between-session mean
|
||||
120 seconds, standard deviation 30 seconds. Interaction delays use a Gaussian truncated symmetrically between 500 and 1500 ms,
|
||||
retaining a 1-second expected mean. Between-session negative draws are clamped to zero. Threads also ramp up over
|
||||
120 seconds. The seed is recorded; OS scheduling still affects exact timings.
|
||||
These are configurable experimental assumptions, not measured population behaviour.
|
||||
The default session frequency represents sustained, accelerated prototype activity;
|
||||
for less frequent patient visits increase `--session-pause-ms` and its deviation.
|
||||
A closed-loop user waits for each response; throughput decreases when the server slows.
|
||||
Concurrency means resident simulated users, including their idle/thinking time.
|
||||
|
||||
## Live NUC monitoring in JMeter
|
||||
|
||||
All six plans contain **jp@gc – PerfMon Metrics Collector**, including idle.
|
||||
The listener connects over TCP to the agent on the target (default port 4444),
|
||||
samples every second, and writes `perfmon.csv` directly on this computer
|
||||
through JMeter during the run. No server log transfer is needed. In GUI mode the
|
||||
listener shows live graphs; use CLI mode for actual energy experiments.
|
||||
|
||||
Collected host metrics: CPU combined utilisation and I/O wait (%), memory usage
|
||||
(% and actual-used bytes), swap-used bytes, disk read/write bytes per second,
|
||||
and network received/sent bytes per second. These are system totals, not per-service
|
||||
attribution. Network/disk counters depend on SIGAR's device support; zero values on
|
||||
an idle host do not establish their accuracy. Compare the readings against Linux
|
||||
utilities before treating the agent as a validated measurement instrument.
|
||||
|
||||
The runner checks agent access/metric availability before starting. It records
|
||||
`--perfmon-host`, `--perfmon-port` and `--perfmon-interval-ms` (default 1000) in
|
||||
`run.json`; by default the agent host matches `--host`. Failed, missing or widely
|
||||
spaced measurements invalidate monitoring. `perfmon-measured.csv` excludes warmup,
|
||||
decodes the plugin's synthetic `elapsed` field into metric values/units, and retains
|
||||
timestamps from this computer's collector, not server-origin timestamps.
|
||||
**PerfMon's elapsed field is not HTTP latency.** Host metrics stay separate
|
||||
from application request counts. Raw `perfmon.csv` contains warmup and measured data.
|
||||
`run.json` also includes each metric's sample count, mean and maximum.
|
||||
|
||||
Keep the agent running on the NUC for the full warmup and measured run. Its TCP
|
||||
connection is plain-text and provides no authentication; restrict port 4444 to the
|
||||
load-generator computer. Restart it with `--no-exec --udp-port 0 --tcp-port 4444`
|
||||
to disable the agent's executable custom metrics; these plans use only built-in metrics.
|
||||
`--no-perfmon` is for isolated workflow testing and explicitly records that no server
|
||||
monitoring was collected. The plugin must still be installed to load its JMX element.
|
||||
The validation fixture uses this switch and does not connect to the NUC.
|
||||
|
||||
[PerfMon listener documentation](https://jmeter-plugins.org/wiki/PerfMon/),
|
||||
[agent metrics/protocol](https://github.com/undera/perfmon-agent).
|
||||
|
||||
## Live Shelly power in JMeter
|
||||
|
||||
Every scenario, including idle, contains one **Shelly live power** thread. It polls
|
||||
`http://192.168.1.44/rpc/Switch.GetStatus?id=0` every second directly from
|
||||
JMeter, independently of simulated users. There is no cloud dependency and no
|
||||
post-run network transfer. No switch/set/reset commands are sent.
|
||||
|
||||
`shelly.csv` is written while JMeter runs, with timestamps, request status,
|
||||
`shelly_power_watts`, `shelly_voltage_volts`, `shelly_current_amps` and cumulative
|
||||
`shelly_energy_wh`. Raw readings include warmup. `shelly-measured.csv` brackets only
|
||||
the measured interval, interpolating its boundaries; `run.json` includes mean watts,
|
||||
integrated joules/kWh and the counter's Wh delta converted to joules/kWh.
|
||||
The timestamp is approximated by each polling request's midpoint on this computer.
|
||||
Meter requests are excluded from the application's request-rate and latency summary.
|
||||
JMeter's overall console summary includes meter polls; use `run.json` and
|
||||
`measured.csv` for the application-only figures.
|
||||
|
||||
Energy from sampled power is the sum of the recorded in-window power values, each multiplied by the nominal polling interval. This assumes each reading represents that interval; actual polling timestamps may differ and sample coverage is reported. Counter deltas provide a separate cross-check;
|
||||
the device's counter update granularity can make short runs report little or no
|
||||
counter change despite nonzero power. Both boundary interpolation and meter accuracy
|
||||
limit precision; this does not claim calibration. The plug measures what is connected
|
||||
to its outlet, including the NUC's power-adapter losses. Connect only the intended
|
||||
measured equipment. Its internal temperature is **not the NUC CPU temperature**.
|
||||
|
||||
The runner defaults to this plug and checks its status before starting. Override with
|
||||
`--shelly-host`, `--shelly-port`, `--shelly-switch-id` or `--shelly-interval-ms`.
|
||||
There is a short unmeasured drain after the four-hour window to obtain its closing
|
||||
boundary. Missing samples, long gaps, failed polls and counter resets invalidate the
|
||||
power measurement; they are not treated as zero watts. `--no-shelly` is for isolated
|
||||
workflow testing, and records that power monitoring was disabled. The current plug
|
||||
has authentication disabled; authenticated device access is not yet implemented.
|
||||
|
||||
The runner configures JMeter's `sample_variables` so the numeric columns are saved.
|
||||
For a manual GUI/CLI launch, pass:
|
||||
|
||||
```bash
|
||||
-Jsample_variables=shelly_power_watts,shelly_voltage_volts,shelly_current_amps,shelly_energy_wh
|
||||
```
|
||||
|
||||
Use the runner for experiment timing, summaries and completeness checks. A new
|
||||
power-monitoring-only check can be run without application requests:
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/verify-shelly.py --host 192.168.1.44 --output tools/energy-jmeter/results/shelly-check-new
|
||||
```
|
||||
|
||||
[Shelly switch status and energy units](https://shelly-api-docs.shelly.cloud/gen2/ComponentsAndServices/Switch/).
|
||||
|
||||
## 1. Prepare Architecture B accounts (outside measurement)
|
||||
|
||||
Use a disposable B installation and synthetic data. The generator reads a **copy** of
|
||||
B's JSON configuration, retains all existing settings/accounts/assignments, and
|
||||
adds patient password hashes. It does not change the installed file. No registration
|
||||
API or application code change is needed.
|
||||
|
||||
Build the portable hash helper from this repository (do not copy old binaries):
|
||||
|
||||
```bash
|
||||
dotnet publish tools/PasswordHash -c Release --self-contained false -p:UseAppHost=false -o tools/energy-jmeter/hash-tool
|
||||
```
|
||||
|
||||
Copy this tooling and hash-tool output to the B test host, then generate a new fixture:
|
||||
|
||||
```bash
|
||||
sudo python3 tools/energy-jmeter/create-accounts.py --configuration /etc/healthapp-b/appsettings.json --output /var/lib/healthapp-b-energy-fixture --count 100
|
||||
```
|
||||
|
||||
Review `/var/lib/healthapp-b-energy-fixture/appsettings.json` privately. Back up the
|
||||
installed configuration, then install this copy **root:healthapp-b, mode 640** at
|
||||
`/etc/healthapp-b/appsettings.json` and restart `healthapp-b.service`. Preserve the
|
||||
original accounts and predefined assignments. This is an explicit test-host setup
|
||||
operation; the generator never installs configuration or restarts services.
|
||||
|
||||
Transfer only generated `accounts.json` privately to the load generator, and export
|
||||
`/etc/healthapp-b/healthapp-ca.crt` as its application trust root. Do not transfer the
|
||||
installed appsettings.json (it contains database/private-key configuration).
|
||||
|
||||
```bash
|
||||
mkdir -p tools/energy-jmeter/.private
|
||||
chmod 700 tools/energy-jmeter/.private
|
||||
# Place accounts.json (mode 600) and healthapp-ca.crt in this private directory.
|
||||
python3 tools/energy-jmeter/prepare.py --base-url https://B_HOST:5443 --ca tools/energy-jmeter/.private/healthapp-ca.crt --accounts tools/energy-jmeter/.private/accounts.json --output tools/energy-jmeter/.private/dataset --days 30
|
||||
```
|
||||
|
||||
Preparation uses the preserved public API and verified HTTPS, creates/reuses profiles,
|
||||
and seeds 60 readings per patient with the original distribution of contexts. It
|
||||
excludes installation-check. It does not reset workload-created records. Use equivalent
|
||||
fresh/restored synthetic datasets for A/B comparison; do not access live A databases.
|
||||
A new output folder is required when preparing again.
|
||||
|
||||
For read-only shared-account runs supply a CSV with account_id,password,patient_id
|
||||
and explicitly use `--allow-shared-read-account`. Professional runs need a separate
|
||||
CSV of configured professional credentials and assigned patient IDs. B's generated
|
||||
professional has no assignments; configure Access:ProfessionalAssignments outside
|
||||
measurement and restart the application. Preflight rejects missing role/assignments.
|
||||
See [B installation](../../deploy/INSTALLATION.md) for configuration ownership and trust.
|
||||
|
||||
## 2. Find a suitable concurrency before the four-hour run
|
||||
|
||||
For the 8 GB, 8th/9th-generation Intel NUC, try 10, 25, 50 and 100 users in short
|
||||
capacity runs. Generate more accounts before trying 200. Age/RAM do not establish
|
||||
capacity. Review CPU, RAM, thermal throttling, error rate and latency on the NUC.
|
||||
Choose your acceptable latency before deciding which level to measure for four hours.
|
||||
For example, this trial lasts 2 minutes of warmup plus 5 measured minutes:
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/run.py mixed --host 192.168.1.125 --ca tools/energy-jmeter/.private/healthapp-ca.crt --users-file tools/energy-jmeter/.private/dataset/users.csv --users 50 --warmup 120 --duration 300 --output tools/energy-jmeter/results/capacity-50
|
||||
```
|
||||
|
||||
A short check identifies obvious overload; it does not establish thermal stability
|
||||
or long-run capacity. Output directories must be new. Failed users are not silently
|
||||
replaced. Do not use a partial/failed run as a successful four-hour measurement.
|
||||
|
||||
## 3. Run a full experiment
|
||||
|
||||
Ensure the NUC is powered through the Shelly plug at **192.168.1.44**, then run:
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/run.py mixed --host 192.168.1.125 --ca tools/energy-jmeter/.private/healthapp-ca.crt --users-file tools/energy-jmeter/.private/dataset/users.csv --users 100 --warmup 1800 --duration 14400 --output tools/energy-jmeter/results/mixed-100-run1
|
||||
```
|
||||
|
||||
Substitute another scenario or concurrency as needed. `--warmup 600` or `1200`
|
||||
selects 10/20 minutes; the four measured hours remain unchanged. Choose a warmup
|
||||
that reaches stable server temperature/power rather than assuming a universal value.
|
||||
`--seed 42`, `--think-min-ms`, `--think-mean-ms`, `--think-stddev-ms`, `--session-pause-ms` and
|
||||
`--session-stddev-ms` control timing. Include these identically across comparisons.
|
||||
|
||||
Use the same-duration `idle` run to establish baseline power:
|
||||
|
||||
```bash
|
||||
bash tools/energy-jmeter/run-idle.sh
|
||||
```
|
||||
|
||||
The idle runner sends zero application requests, including during startup. No CA, credentials or dataset is needed. JMeter collects only PerfMon host metrics and Shelly power readings.
|
||||
The application/PostgreSQL stay running as they are. The runner does not start, stop or restart them. Keep the PerfMon agent running. The one-command launcher creates a timestamped result folder under `results/idle-*`. The load generator and HTML-report
|
||||
creation stay on this computer, outside the NUC's energy measurement. Keep server
|
||||
power settings, dataset, service versions, logging and other workloads consistent.
|
||||
Record those settings, thermal state, meter sampling interval and clock synchronisation.
|
||||
Repeat runs and vary their order to check drift. The inherited live-monitoring observations refer to Architecture A. B verification and its limits are recorded separately in ARCHITECTURE-B.md.
|
||||
|
||||
## 4. Read results and energy
|
||||
|
||||
`run.json` contains measurement boundaries, request/error counts, request rate,
|
||||
p95 latency, random seed, timings and plan hash. JMeter CSV excludes response bodies,
|
||||
request headers and passwords. The private runtime credential CSV is deleted at exit;
|
||||
keep the whole result directory private and inspect logs before sharing.
|
||||
|
||||
JMeter now collects the Shelly readings live and the runner calculates measured-window energy automatically. For another external meter, export its readings as
|
||||
CSV with `timestamp,power_watts` (timezone-qualified ISO timestamps, increasing,
|
||||
covering the full interval), then integrate only the measured four hours:
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/energy.py tools/energy-jmeter/results/mixed-100-run1/run.json power.csv
|
||||
```
|
||||
|
||||
The tool interpolates interval edges and integrates watts using trapezoids. It reports
|
||||
joules, kWh, mean watts and joules per HTTP request. `--idle-watts VALUE` additionally
|
||||
reports energy above the measured idle mean. A request is not a user session;
|
||||
compare scenario/mix and achieved throughput when interpreting efficiency.
|
||||
Raw meter data must be preserved; missing intervals cannot be repaired by JMeter. The same rule applies to Shelly polls.
|
||||
|
||||
JMeter's stock HTTPS client trusts test certificates. The Python runner verifies the
|
||||
provided CA and hostname during preflight; JMeter traffic itself remains encrypted
|
||||
but does not provide certificate validation. Do not describe this as a TLS security test.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/generate-plans.py
|
||||
python3 tools/energy-jmeter/verify-plans.py
|
||||
python3 tools/energy-jmeter/verify-perfmon.py
|
||||
python3 tools/energy-jmeter/verify-shelly.py
|
||||
python3 tools/energy-jmeter/verify-idle.py
|
||||
```
|
||||
|
||||
The validation script exercises every plan against an isolated local HTTPS contract
|
||||
stub, including dynamic IDs, token renewal, status/semantic assertions, deletion and
|
||||
warmup exclusion. It does not prove capacity or replace the application's acceptance
|
||||
suite. The real-server short capacity trial is required before a four-hour measurement.
|
||||
|
||||
References: [Apache release](https://jmeter.apache.org/download_jmeter.cgi),
|
||||
[CLI load testing](https://jmeter.apache.org/usermanual/get-started.html),
|
||||
[JMeter components](https://jmeter.apache.org/usermanual/component_reference.html).
|
||||
|
||||
For a short live monitoring-only check (no patient requests):
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/verify-perfmon.py --host 192.168.1.125 --output tools/energy-jmeter/results/perfmon-check-new
|
||||
```
|
||||
|
||||
This verifies that JMeter saves readings while it is still running, then checks
|
||||
metric coverage and decoding. An inherited Architecture A monitoring-only check succeeded against the NUC;
|
||||
comparison with independent Linux readings is still needed to validate accuracy.
|
||||
|
||||
## Time-aligned graphs and one-second request reporting
|
||||
|
||||
Every finished run generates `report.html` (interactive), `report.png`, `report.svg`
|
||||
and `per-second.csv`. The plotting dependency is Matplotlib, already installed on
|
||||
this computer. If setting up another load generator, install Matplotlib there.
|
||||
All panels share UTC timestamps and experiment-relative one-second intervals,
|
||||
starting at the recorded warmup start. Warmup is shaded; measurement begins after
|
||||
the exact configured warmup duration.
|
||||
|
||||
CPU, RAM, power, disk and network values are averaged only when multiple samples
|
||||
fall into a second; missing readings stay blank and create graph gaps. Application
|
||||
requests and failed requests are counted individually per second. Mean/p95/max
|
||||
latency is grouped by request start time, with p95 using the nearest-rank definition.
|
||||
Requests spanning the measurement end are excluded from measured application figures,
|
||||
matching `run.json`. Meter requests and internal timing samples never count as
|
||||
application traffic. Seconds without requests have zero request/error counts and
|
||||
no response-time value. The graph keeps every one-second bin; a wide full-run view
|
||||
can visually compress points. Use the interactive range controls to inspect seconds.
|
||||
|
||||
For a running experiment, generate a snapshot or keep refreshing its artifacts:
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/report.py tools/energy-jmeter/results/RUN_FOLDER
|
||||
python3 tools/energy-jmeter/report.py tools/energy-jmeter/results/RUN_FOLDER --follow
|
||||
```
|
||||
|
||||
`--follow` refreshes artifacts every minute, using one-second data, and generates the
|
||||
final report when the run finishes. Open `report.html` locally and use **Refresh
|
||||
snapshot** to load new data. It provides a shared cursor across panels and a measured-
|
||||
window selection. The latest seconds of a running snapshot are provisional because
|
||||
JMeter writes request samples after their responses arrive. Missing future seconds
|
||||
are not plotted as zeros. Report creation runs on the load generator.
|
||||
|
||||
Verify aggregation with `python3 tools/energy-jmeter/verify-report.py`.
|
||||
|
||||
For intentionally heavy shared-data capacity trials, use `review`,
|
||||
`--allow-shared-read-account`, `--capacity-trial` and the desired thread count.
|
||||
`--capacity-trial` restarts a read-only session after failures to maintain the trial
|
||||
duration. Errors are still recorded and the run is marked unsuccessful if any occur;
|
||||
the graphs remain useful for finding capacity. This mode permits no write scenarios.
|
||||
First-use certificate pinning, when used instead of the installation CA, trusts the
|
||||
certificate presented on that first connection; it is not an independently verified CA.
|
||||
|
||||
The inherited Architecture A 26-thread selection and its historical evidence are preserved in [WORKLOAD-SELECTION.md](WORKLOAD-SELECTION.md). This is not a B capacity result. For paired comparisons keep concurrency/pacing/workload identical and record B admission settings; do not tune away 503 responses or exclude failures.
|
||||
@@ -0,0 +1,182 @@
|
||||
> Historical Architecture A calibration, copied unchanged below. It does not establish Architecture B capacity.
|
||||
|
||||
# Why the loaded measurement uses 26 threads
|
||||
|
||||
**Decision, 9 October 2026:** use **26 JMeter threads** for the main loaded energy
|
||||
experiment, with **30 minutes of warmup followed by four measured hours**. Collect
|
||||
CPU, memory, power and request results at one-second resolution. This is the chosen
|
||||
protocol; the four-hour loaded run has not yet been performed.
|
||||
|
||||
The aim is to produce substantial application load while preserving headroom for
|
||||
background activity. The response-time knee informs the choice, but the main
|
||||
experiment deliberately operates below its steep-rise region.
|
||||
|
||||
## Measurements used for the decision
|
||||
|
||||
Calibration used the same read-only review workflow and one shared patient dataset.
|
||||
Each thread repeatedly retrieved profile, latest observation, filtered history,
|
||||
insights, trends and overview, with an initial login and renewal if required.
|
||||
Account provisioning and synthetic data preparation were separate from measurement.
|
||||
This is concurrent use of one shared dataset, not 26 independently provisioned patients.
|
||||
|
||||
All comparable trials used:
|
||||
|
||||
- One-minute ramp/warmup followed by ten measured minutes.
|
||||
- Gaussian request pauses with a **500 ms minimum**, **1,000 ms expected mean** and
|
||||
**1,500 ms maximum**. The parent Gaussian standard deviation is 250 ms; symmetric
|
||||
truncation preserves the expected mean and changes the resulting standard deviation.
|
||||
- No additional pause between review sessions; this represents sustained active use.
|
||||
- The same dataset, application deployment, workflow, seed and one-second monitoring.
|
||||
- Sequential runs to prevent workload overlap. Mean response times exclude think time.
|
||||
|
||||
The initial trials with 100 ms mean pauses are excluded from the comparable curve.
|
||||
The incomplete 80-thread trial is also excluded. The latest identical-pacing
|
||||
30-thread repeat is used; it closely reproduced the earlier 30-thread result.
|
||||
All 19 selected calibration points completed with zero failed requests and valid
|
||||
monitoring. This does not establish the same behaviour for different patients,
|
||||
data volumes, workflow mixes or deployment arrangements.
|
||||
|
||||
| Threads | Mean response | Requests/s | Mean CPU | Mean power |
|
||||
|---:|---:|---:|---:|---:|
|
||||
| 25 | 128 ms | 22.15 | 78.16% | 8.76 W |
|
||||
| **26 — selected** | **139 ms** | **22.81** | **80.60%** | **8.90 W** |
|
||||
| 27 | 148 ms | 23.52 | 82.96% | 9.04 W |
|
||||
| 30 | 183 ms | 25.34 | 89.00% | 9.34 W |
|
||||
| 35 | 280 ms | 27.32 | 95.65% | 9.65 W |
|
||||
| 40 | 425 ms | 28.05 | 98.25% | 9.75 W |
|
||||
| 50 | 785 ms | 27.95 | 98.72% | 9.81 W |
|
||||
|
||||
Full measured points: [calibration.csv](evidence/26-thread-choice/calibration.csv).
|
||||
|
||||
## Response-time knee
|
||||
|
||||

|
||||
|
||||
The curve steepens as utilisation approaches saturation. From 35 to 40 threads,
|
||||
mean response time rises from 280 to 425 ms, while throughput grows only about 2.7%.
|
||||
At 50 threads, response time rises further without increased throughput.
|
||||
|
||||
We adopted **35 threads as a practical knee marker**, based on the response-time
|
||||
curve and a mean response time of approximately 280 ms being barely acceptable
|
||||
for this experiment. The finer 26–39-thread trials support a gradual bend followed
|
||||
by a steep-rise region, rather than a uniquely established abrupt threshold.
|
||||
The figures use **mean response time only**. P95 remains in the original results
|
||||
but is not mixed into this particular queueing comparison.
|
||||
|
||||
The simplified queueing model used to interpret the shape is:
|
||||
|
||||
\[
|
||||
R = W + S,\qquad W = \frac{SU}{1-U},\qquad R = \frac{S}{1-U}.
|
||||
\]
|
||||
|
||||
Here, `R` is mean response time, `W` waiting time, `S` service time and `U`
|
||||
utilisation expressed as a fraction. Near saturation, a small increase in `U`
|
||||
produces a disproportionately large increase in `R`.
|
||||
|
||||
This model motivates preserving headroom. The plots show **measured points**,
|
||||
not a fitted theoretical curve: service time was not measured separately, and
|
||||
whole-machine CPU utilisation is being used as a practical utilisation proxy.
|
||||
The model does not prove a precise knee or distinguish the application's individual
|
||||
queues and resources.
|
||||
|
||||
## Background activity and the headroom rule
|
||||
|
||||

|
||||
|
||||
The four-hour idle baseline made **zero application requests**, with services and
|
||||
monitoring running. It recorded 14,395 CPU samples at nominal one-second intervals:
|
||||
mean utilisation **0.505%**, maximum **11.055%**, seven samples at least 5% and one
|
||||
sample at least 10%. These include monitoring overhead and other background work;
|
||||
we did not collect process-level attribution.
|
||||
|
||||
Loaded trials had application requests in every measured second. Consequently,
|
||||
those traces cannot isolate request-free background spikes or establish which
|
||||
process caused a particular loaded-run peak.
|
||||
|
||||
The agreed conservative planning rule reserves the observed idle maximum as
|
||||
**11.055 percentage points** against a chosen **95% CPU reference**:
|
||||
|
||||
\[
|
||||
U_{\text{planning ceiling}} = 95\% - 11.055\text{ percentage points}
|
||||
= 83.945\%.
|
||||
\]
|
||||
|
||||

|
||||
|
||||
At 26 threads, average CPU is **80.603%**, leaving approximately **14.397 percentage
|
||||
points** below the 95% reference: about **3.342 points beyond the reserved budget**.
|
||||
At 27 threads, the average still meets the planning ceiling, but leaves only about
|
||||
0.983 points beyond that budget. At 28 threads, average CPU is already above it.
|
||||
|
||||
We therefore chose **26 rather than 27 threads** for additional margin, and 26
|
||||
rather than 25 to retain slightly more application load. It is also close to the
|
||||
original approximately 80% utilisation objective. The measured mean response time
|
||||
was 139 ms with zero failed requests.
|
||||
|
||||
The idle maximum is **not** a proven incremental disturbance that can simply be
|
||||
added to loaded CPU, and it is not a guaranteed future maximum. Reserving its full
|
||||
observed value is a planning assumption. The 95% reference is likewise our operating
|
||||
criterion, not a demonstrated universal performance boundary.
|
||||
|
||||
## What the choice does not guarantee
|
||||
|
||||

|
||||
|
||||
An average below the planning ceiling does not keep every second below it. The
|
||||
26-thread trial reached **98.994% CPU**, with **25 of 600 samples at least 95%**
|
||||
(4.17%) and seven at least 98% (1.17%). Those transient peaks caused no recorded
|
||||
request errors in this ten-minute trial, but they show that saturation remains
|
||||
possible. The choice reduces exposure; it does not guarantee its elimination.
|
||||
|
||||
Calibration contains one trial at most thread counts and only one matching repeat
|
||||
at 30. Run order was generally ascending and was not randomised; thermal/background
|
||||
drift and measurement variation have not been fully separated. Four-hour stability
|
||||
must be assessed in the actual long run, and repeat measurements are needed to
|
||||
quantify variability. CPU measurements are PerfMon/SIGAR readings and have not been
|
||||
independently validated against Linux counters.
|
||||
|
||||
## Main loaded measurement protocol
|
||||
|
||||
Use the **same shared-data read-only review scenario**, with:
|
||||
|
||||
| Setting | Value |
|
||||
|---|---|
|
||||
| Concurrent threads | **26** |
|
||||
| Ramp | 60 seconds, inside warmup |
|
||||
| Warmup excluded from analysis | **1,800 seconds** |
|
||||
| Measured duration | **14,400 seconds** |
|
||||
| Request pauses | Gaussian, 500–1,500 ms, expected mean 1,000 ms |
|
||||
| Between-session pause | None |
|
||||
| CPU and Shelly polling | **1,000 ms** |
|
||||
| Error handling | Record failures; begin the next read-only session |
|
||||
|
||||
Keep application configuration, dataset, monitoring, power settings and other
|
||||
activity consistent across comparisons. Preserve raw measurements. Inspect
|
||||
per-second CPU/latency/error traces rather than relying only on run averages.
|
||||
The Shelly measures the connected equipment, including adapter losses; power-meter
|
||||
accuracy has not been independently calibrated. Treat its cumulative counter delta
|
||||
as a separate cross-check to integration of sampled watts.
|
||||
|
||||
See the [execution guide](README.md) for run commands and reporting. The experiment
|
||||
runs from the development computer, using application and monitoring APIs, without
|
||||
SSH or administrative changes to the NUC.
|
||||
|
||||
## Evidence and reproducibility
|
||||
|
||||
The evidence accompanying this document contains no passwords or tokens:
|
||||
|
||||
- [Calibration points](evidence/26-thread-choice/calibration.csv).
|
||||
- [Idle CPU trace](evidence/26-thread-choice/idle-cpu.csv).
|
||||
- [Selected workload CPU trace](evidence/26-thread-choice/selected-cpu.csv).
|
||||
- [Calculated evidence summary and source run names](evidence/26-thread-choice/evidence-summary.json).
|
||||
- PNG figures above and same-stem SVG files for export.
|
||||
|
||||
The original complete results remain under `tools/energy-jmeter/results/`, which
|
||||
is Git-ignored. Regenerate this evidence from those files with:
|
||||
|
||||
```bash
|
||||
python3 tools/energy-jmeter/document-choice.py
|
||||
```
|
||||
|
||||
No architecture, service behaviour or authoritative requirements were changed by
|
||||
this experiment decision.
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate synthetic accounts in a COPY of Architecture B's protected JSON config."""
|
||||
import argparse, json, os, re, secrets, subprocess
|
||||
from pathlib import Path
|
||||
p=argparse.ArgumentParser()
|
||||
p.add_argument('--configuration',required=True,help='Installed B appsettings.json; never modified')
|
||||
p.add_argument('--output',required=True)
|
||||
p.add_argument('--count',type=int,default=100);p.add_argument('--dotnet',default='dotnet')
|
||||
p.add_argument('--hash-tool',default=str(Path(__file__).parent/'hash-tool/PasswordHash.dll'))
|
||||
a=p.parse_args()
|
||||
if not 1<=a.count<=10000: p.error('count must be 1..10000')
|
||||
config=json.loads(Path(a.configuration).read_text())
|
||||
# The native installer emits colon-delimited keys; hand-written examples use nested JSON.
|
||||
flat_indices=[int(m.group(1)) for key in config if (m:=re.fullmatch(r'Authentication:Accounts:(\d+):AccountId',key,re.I))]
|
||||
existing=config.get('Authentication',{}).get('Accounts')
|
||||
if flat_indices and existing is not None: p.error('Mixed flat/nested account configuration is ambiguous')
|
||||
flat=bool(flat_indices)
|
||||
if flat:
|
||||
existing=[{'AccountId':v} for k,v in config.items() if re.fullmatch(r'Authentication:Accounts:\d+:AccountId',k,re.I)]
|
||||
if not isinstance(existing,list) or not existing: p.error('No installer-created Authentication:Accounts found')
|
||||
if any(x.get('AccountId','').startswith('energy-patient-') for x in existing):
|
||||
p.error('Energy accounts already exist; reuse their credentials rather than overwrite')
|
||||
next_index=max(flat_indices)+1 if flat else len(existing)
|
||||
out=Path(a.output);out.mkdir(mode=0o700,parents=True,exist_ok=False)
|
||||
accounts=[]
|
||||
for i in range(a.count):
|
||||
account={'AccountId':f'energy-patient-{i+1:04d}','Role':'Patient','Password':secrets.token_hex(24)}
|
||||
result=subprocess.run([a.dotnet,a.hash_tool],input=account['Password']+'\n',text=True,capture_output=True)
|
||||
if result.returncode: raise SystemExit('Password hash tool failed; no configuration installed')
|
||||
hashed=result.stdout.strip()
|
||||
if not hashed or '\n' in hashed: raise SystemExit('Password hash tool returned unexpected output')
|
||||
entry={'AccountId':account['AccountId'],'Role':account['Role'],'PasswordHash':hashed}
|
||||
if flat:
|
||||
for key,value in entry.items(): config[f'Authentication:Accounts:{next_index+i}:{key}']=value
|
||||
else: existing.append(entry)
|
||||
accounts.append(account)
|
||||
for name,value in [('appsettings.json',config),('accounts.json',accounts)]:
|
||||
path=out/name
|
||||
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
||||
with os.fdopen(fd,'w') as f: json.dump(value,f,indent=2); f.write('\n')
|
||||
print(f'Generated {a.count} synthetic accounts. Original configuration was not changed.')
|
||||
print('Review and install',out/'appsettings.json','with root:healthapp-b ownership and mode 640, then restart healthapp-b.')
|
||||
print('Keep accounts.json private. No database or application configuration was installed automatically.')
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export nonsecret measured evidence and figures supporting the 26-thread choice."""
|
||||
from pathlib import Path
|
||||
import argparse,csv,json,statistics,os,datetime as dt
|
||||
HERE=Path(__file__).resolve().parent
|
||||
p=argparse.ArgumentParser();p.add_argument('--results',type=Path,default=HERE/'results');p.add_argument('--output',type=Path,default=HERE/'evidence/26-thread-choice');a=p.parse_args()
|
||||
a.output.mkdir(parents=True,exist_ok=True);os.environ.setdefault('MPLCONFIGDIR',str(a.results/'.figure-cache'))
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.dates as dates
|
||||
rows=[]
|
||||
for n in [15,20,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,50]:
|
||||
run=2 if n==30 else 1;folder=a.results/f'capacity-shared-{n}-human-delay-run{run}'
|
||||
m=json.loads((folder/'run.json').read_text())
|
||||
assert m['exit_code']==0 and m['think_min_ms']==500 and m['think_mean_ms']==1000
|
||||
with (folder/'measured.csv').open() as f:samples=list(csv.DictReader(f))
|
||||
rows.append({'threads':n,'run':folder.name,'cpu_percent':m['server_metrics']['192.168.1.125 CPU combined']['mean'],'mean_response_ms':statistics.mean(int(r['elapsed']) for r in samples),'requests_per_second':m['measured_http_requests_per_second'],'power_watts':m['power_energy']['average_watts'],'failed_requests':m['measured_failed_http_samples']})
|
||||
with (a.output/'calibration.csv').open('w') as f:w=csv.DictWriter(f,fieldnames=list(rows[0]),lineterminator='\n');w.writeheader();w.writerows(rows)
|
||||
def cpu_trace(name,filename):
|
||||
folder=a.results/name;m=json.loads((folder/'run.json').read_text())
|
||||
with (folder/'perfmon.csv').open() as f:trace=[{'timestamp_ms':int(r['timeStamp']),'cpu_percent':float(r['elapsed'])/1000} for r in csv.DictReader(f) if r['label'].endswith(' CPU combined') and r['success']=='true' and m['measurement_start_ms']<=int(r['timeStamp'])<m['measurement_end_ms']]
|
||||
with (a.output/filename).open('w') as f:w=csv.DictWriter(f,fieldnames=['timestamp_ms','cpu_percent'],lineterminator='\n');w.writeheader();w.writerows(trace)
|
||||
return m,trace
|
||||
idle,idle_trace=cpu_trace('idle-20261008T104130Z','idle-cpu.csv')
|
||||
selected,selected_trace=cpu_trace('capacity-shared-26-human-delay-run1','selected-cpu.csv')
|
||||
reserve=max(p['cpu_percent'] for p in idle_trace);ceiling=95-reserve
|
||||
summary={'idle_run':'idle-20261008T104130Z','selected_run':'capacity-shared-26-human-delay-run1','observed_idle_peak_percent':reserve,'assumed_reserve_percentage_points':reserve,'planning_ceiling_percent':ceiling,'selected_cpu_mean_percent':selected['server_metrics']['192.168.1.125 CPU combined']['mean'],'selected_cpu_peak_percent':max(p['cpu_percent'] for p in selected_trace),'selected_samples':len(selected_trace),'selected_samples_ge95':sum(p['cpu_percent']>=95 for p in selected_trace),'selected_samples_ge98':sum(p['cpu_percent']>=98 for p in selected_trace),'idle_samples':len(idle_trace),'idle_samples_ge5':sum(p['cpu_percent']>=5 for p in idle_trace),'idle_samples_ge10':sum(p['cpu_percent']>=10 for p in idle_trace),'idle_power_watts':idle['power_energy']['average_watts'],'selected_power_watts':selected['power_energy']['average_watts'],'long_run_protocol':{'threads':26,'warmup_seconds':1800,'measurement_seconds':14400,'sampling_interval_ms':1000,'think_min_ms':500,'think_mean_ms':1000,'think_parent_gaussian_sd_ms':250,'think_max_ms':1500,'session_pause_ms':0},'qualification':'Observed idle peak is a planning reserve, not an independently measured incremental disturbance or guaranteed bound.'}
|
||||
(a.output/'evidence-summary.json').write_text(json.dumps(summary,indent=2))
|
||||
def save(fig,name):
|
||||
fig.savefig(a.output/(name+'.png'),dpi=170);fig.savefig(a.output/(name+'.svg'));plt.close(fig)
|
||||
svg=a.output/(name+'.svg');svg.write_text('\n'.join(line.rstrip() for line in svg.read_text().splitlines())+'\n')
|
||||
fig,axes=plt.subplots(1,2,figsize=(13,5),layout='constrained')
|
||||
for ax,xfield,xlabel in [(axes[0],'threads','Concurrent threads'),(axes[1],'cpu_percent','Mean whole-machine CPU utilisation (%)')]:
|
||||
ax.plot([r[xfield] for r in rows],[r['mean_response_ms'] for r in rows],'o-',markersize=4,label='Measured mean response time')
|
||||
choice=next(r for r in rows if r['threads']==26);ax.scatter([choice[xfield]],[choice['mean_response_ms']],s=110,color='#b34416',zorder=4,label='Selected: 26 threads')
|
||||
for n in [26,35,40,50]:
|
||||
r=next(r for r in rows if r['threads']==n);ax.annotate(str(n)+' threads',(r[xfield],r['mean_response_ms']),xytext=(-5,10),textcoords='offset points',ha='right',fontsize=8)
|
||||
ax.set_xlabel(xlabel);ax.set_ylabel('Mean response time (ms)');ax.set_ylim(bottom=0);ax.grid(alpha=.25);ax.legend(loc='upper left',fontsize=8)
|
||||
axes[1].set_xlim(45,100)
|
||||
fig.suptitle('Selected workload is below the observed steep-rise region\nMatched request pacing and shared data; ten-minute calibration trials')
|
||||
save(fig,'mean-response-knee')
|
||||
fig,ax=plt.subplots(figsize=(10,5),layout='constrained')
|
||||
ax.plot([r['threads'] for r in rows],[r['cpu_percent'] for r in rows],'o-',markersize=4,label='Measured mean CPU')
|
||||
ax.axhline(95,color='#ad3828',linestyle='--',label='95% planning limit')
|
||||
ax.axhline(ceiling,color='#86671d',linestyle='--',label=f'Planning ceiling: 95 − {reserve:.3f} = {ceiling:.3f}%')
|
||||
choice=next(r for r in rows if r['threads']==26);ax.scatter([26],[choice['cpu_percent']],s=120,color='#217a52',zorder=4);ax.annotate(f'26 threads: {choice["cpu_percent"]:.1f}%',(26,choice['cpu_percent']),xytext=(-45,-32),textcoords='offset points',arrowprops={'arrowstyle':'->'})
|
||||
ax.set_xlabel('Concurrent threads');ax.set_ylabel('Mean CPU utilisation (%)');ax.set_ylim(40,102);ax.grid(alpha=.25);ax.legend(loc='lower right',fontsize=8);ax.set_title('Headroom rule applied to average CPU — not a per-second guarantee')
|
||||
save(fig,'cpu-headroom')
|
||||
fig,ax=plt.subplots(figsize=(12,4),layout='constrained')
|
||||
x=[dt.datetime.fromtimestamp(r['timestamp_ms']/1000,dt.timezone.utc) for r in idle_trace]
|
||||
ax.plot(x,[r['cpu_percent'] for r in idle_trace],linewidth=.7)
|
||||
peak=max(idle_trace,key=lambda r:r['cpu_percent']);instant=dt.datetime.fromtimestamp(peak['timestamp_ms']/1000,dt.timezone.utc)
|
||||
ax.annotate(f'Observed maximum: {reserve:.3f}%',(instant,reserve),xytext=(20,-25),textcoords='offset points',arrowprops={'arrowstyle':'->'})
|
||||
ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M',tz=dt.timezone.utc));ax.set_xlabel('UTC time on 2026-10-08');ax.set_ylabel('CPU utilisation (%)');ax.set_ylim(0,13);ax.grid(alpha=.25);ax.set_title('Four-hour idle baseline: zero application requests; monitoring active')
|
||||
save(fig,'idle-cpu-spikes')
|
||||
fig,ax=plt.subplots(figsize=(12,4),layout='constrained')
|
||||
x=[(r['timestamp_ms']-selected['measurement_start_ms'])/1000 for r in selected_trace]
|
||||
ax.plot(x,[r['cpu_percent'] for r in selected_trace],linewidth=.8,label='One-second CPU readings')
|
||||
ax.axhline(choice['cpu_percent'],color='#217a52',label=f'Mean: {choice["cpu_percent"]:.1f}%')
|
||||
ax.axhline(95,color='#ad3828',linestyle='--',label='95% reference')
|
||||
ax.set_xlabel('Seconds into the ten-minute measured window');ax.set_ylabel('CPU utilisation (%)');ax.set_ylim(40,102);ax.grid(alpha=.25);ax.legend(loc='lower right',fontsize=8);ax.set_title('26 threads: transient saturation remains possible (25 / 600 samples ≥95%)')
|
||||
save(fig,'selected-cpu-trace')
|
||||
print('Exported four figures, calibration table, CPU traces and evidence summary:',a.output)
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sum timestamped external power readings at the nominal polling interval."""
|
||||
import argparse, csv, datetime as dt, json
|
||||
from pathlib import Path
|
||||
p=argparse.ArgumentParser();p.add_argument('run');p.add_argument('power_csv');p.add_argument('--idle-watts',type=float);p.add_argument('--interval-seconds',type=float,default=1);a=p.parse_args()
|
||||
run=json.loads(Path(a.run).read_text());start=run['measurement_start_ms']/1000;end=run['measurement_end_ms']/1000
|
||||
points=[]
|
||||
with open(a.power_csv) as f:
|
||||
for r in csv.DictReader(f):
|
||||
instant=dt.datetime.fromisoformat(r['timestamp'].replace('Z','+00:00'))
|
||||
if instant.tzinfo is None: p.error('Power timestamps require a timezone')
|
||||
watts=float(r['power_watts'])
|
||||
if not 0<=watts<float('inf'):p.error('Power must be finite and nonnegative')
|
||||
points.append((instant.timestamp(),watts))
|
||||
if len(points)<2 or any(b[0]<=a[0] for a,b in zip(points,points[1:])):p.error('Power timestamps must be strictly increasing')
|
||||
if points[0][0]>start or points[-1][0]<end:p.error('Power samples must cover the entire measurement interval')
|
||||
if a.interval_seconds<=0:p.error('Interval must be positive')
|
||||
measured=[power for timestamp,power in points if start<=timestamp<end]
|
||||
if not measured:p.error('No power readings in measurement window')
|
||||
coverage=len(measured)*a.interval_seconds
|
||||
joules=sum(measured)*a.interval_seconds
|
||||
result={'duration_seconds':end-start,'power_sample_count':len(measured),'nominal_sample_coverage_seconds':coverage,'method':'sum of recorded power readings multiplied by nominal interval','joules':joules,'kWh':joules/3600000,'average_watts':sum(measured)/len(measured)}
|
||||
if a.idle_watts is not None:result['joules_above_idle']=joules-a.idle_watts*coverage
|
||||
count=run.get('measured_http_samples',0)
|
||||
if count:result['joules_per_http_request']=joules/count
|
||||
print(json.dumps(result,indent=2))
|
||||
@@ -0,0 +1,20 @@
|
||||
threads,run,cpu_percent,mean_response_ms,requests_per_second,power_watts,failed_requests
|
||||
15,capacity-shared-15-human-delay-run1,50.895801666666664,79.34052499101043,13.905,7.311085382211325,0
|
||||
20,capacity-shared-20-human-delay-run1,65.083935,98.86954928545255,18.19333333333333,8.0890766215625,0
|
||||
25,capacity-shared-25-human-delay-run1,78.16213333333333,128.36280189601987,22.151666666666667,8.764036898464678,0
|
||||
26,capacity-shared-26-human-delay-run1,80.60345333333333,139.38706613080015,22.808333333333334,8.899511694113961,0
|
||||
27,capacity-shared-27-human-delay-run1,82.96233333333333,148.47303139839818,23.515,9.036443046141601,0
|
||||
28,capacity-shared-28-human-delay-run1,85.14292333333333,161.7337208497682,24.085,9.17391177691059,0
|
||||
29,capacity-shared-29-human-delay-run1,87.06948666666668,173.3995543250726,24.68166666666667,9.21969683437396,0
|
||||
30,capacity-shared-30-human-delay-run2,88.99881333333333,182.9120626151013,25.34,9.337538094281125,0
|
||||
31,capacity-shared-31-human-delay-run1,90.41707833333334,205.14021541655853,25.686666666666667,9.406692395193705,0
|
||||
32,capacity-shared-32-human-delay-run1,92.08799333333333,218.39473851432928,26.22833333333333,9.47666378438836,0
|
||||
33,capacity-shared-33-human-delay-run1,93.45843666666666,237.0786376158277,26.62,9.510238336982816,0
|
||||
34,capacity-shared-34-human-delay-run1,94.94577166666667,253.21672816728167,27.1,9.625515573054285,0
|
||||
35,capacity-shared-35-human-delay-run1,95.64982,279.99633900787114,27.315,9.653541583333334,0
|
||||
36,capacity-shared-36-human-delay-run1,96.68018166666666,308.8980768064066,27.471666666666668,9.700332333333334,0
|
||||
37,capacity-shared-37-human-delay-run1,97.42113666666667,338.35063367531683,27.616666666666667,9.73826068038247,0
|
||||
38,capacity-shared-38-human-delay-run1,97.793315,381.2771442436006,27.476666666666667,9.750565151409038,0
|
||||
39,capacity-shared-39-human-delay-run1,98.11210833333334,415.07466844304486,27.52166666666667,9.74681905188326,0
|
||||
40,capacity-shared-40-human-delay-run1,98.25498333333333,424.66961792144514,28.048333333333332,9.748927936868148,0
|
||||
50,capacity-shared-50-human-delay-run1,98.71679666666667,784.9196039840162,27.945,9.807314705581957,0
|
||||
|
|
After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"idle_run": "idle-20261008T104130Z",
|
||||
"selected_run": "capacity-shared-26-human-delay-run1",
|
||||
"observed_idle_peak_percent": 11.055,
|
||||
"assumed_reserve_percentage_points": 11.055,
|
||||
"planning_ceiling_percent": 83.945,
|
||||
"selected_cpu_mean_percent": 80.60345333333333,
|
||||
"selected_cpu_peak_percent": 98.994,
|
||||
"selected_samples": 600,
|
||||
"selected_samples_ge95": 25,
|
||||
"selected_samples_ge98": 7,
|
||||
"idle_samples": 14395,
|
||||
"idle_samples_ge5": 7,
|
||||
"idle_samples_ge10": 1,
|
||||
"idle_power_watts": 4.450219402777778,
|
||||
"selected_power_watts": 8.899511694113961,
|
||||
"long_run_protocol": {
|
||||
"threads": 26,
|
||||
"warmup_seconds": 1800,
|
||||
"measurement_seconds": 14400,
|
||||
"sampling_interval_ms": 1000,
|
||||
"think_min_ms": 500,
|
||||
"think_mean_ms": 1000,
|
||||
"think_parent_gaussian_sd_ms": 250,
|
||||
"think_max_ms": 1500,
|
||||
"session_pause_ms": 0
|
||||
},
|
||||
"qualification": "Observed idle peak is a planning reserve, not an independently measured incremental disturbance or guaranteed bound."
|
||||
}
|
||||
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 278 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 259 KiB |
|
After Width: | Height: | Size: 58 KiB |
@@ -0,0 +1,601 @@
|
||||
timestamp_ms,cpu_percent
|
||||
1791502598833,72.222
|
||||
1791502599833,90.909
|
||||
1791502600833,86.934
|
||||
1791502601834,76.02
|
||||
1791502602834,61.224
|
||||
1791502603834,76.5
|
||||
1791502604834,92.893
|
||||
1791502605834,83.838
|
||||
1791502606835,76.53
|
||||
1791502607835,90.954
|
||||
1791502608835,73.604
|
||||
1791502609835,72.081
|
||||
1791502610836,79.797
|
||||
1791502611836,90.862
|
||||
1791502612836,74.747
|
||||
1791502613836,77.435
|
||||
1791502614837,96.482
|
||||
1791502615837,77.777
|
||||
1791502616837,81.313
|
||||
1791502617838,86.5
|
||||
1791502618838,83.838
|
||||
1791502619838,74.242
|
||||
1791502620838,72.959
|
||||
1791502621838,84.924
|
||||
1791502622839,76.884
|
||||
1791502623839,89.847
|
||||
1791502624839,73.096
|
||||
1791502625839,83.919
|
||||
1791502626840,73.846
|
||||
1791502627840,84.848
|
||||
1791502628840,81.313
|
||||
1791502629840,85.929
|
||||
1791502630841,79.081
|
||||
1791502631841,76.142
|
||||
1791502632841,84.422
|
||||
1791502633841,64.974
|
||||
1791502634842,92.385
|
||||
1791502635842,83.333
|
||||
1791502636842,82.323
|
||||
1791502637842,73.096
|
||||
1791502638843,85.858
|
||||
1791502639843,76.923
|
||||
1791502640843,82.323
|
||||
1791502641843,85.279
|
||||
1791502642843,84.343
|
||||
1791502643844,90.862
|
||||
1791502644844,71.938
|
||||
1791502645844,80.904
|
||||
1791502646844,72.588
|
||||
1791502647845,77.272
|
||||
1791502648845,88.888
|
||||
1791502649845,80.303
|
||||
1791502650845,84.343
|
||||
1791502651846,73.604
|
||||
1791502652846,83.756
|
||||
1791502653846,68.205
|
||||
1791502654846,79.695
|
||||
1791502655846,89.949
|
||||
1791502656847,78.68
|
||||
1791502657847,86.363
|
||||
1791502658847,78.68
|
||||
1791502659847,72.588
|
||||
1791502660847,82.142
|
||||
1791502661848,81.818
|
||||
1791502662848,81.218
|
||||
1791502663848,82.323
|
||||
1791502664848,86.934
|
||||
1791502665849,68.367
|
||||
1791502666849,72.864
|
||||
1791502667849,87.878
|
||||
1791502668849,85.929
|
||||
1791502669849,95.959
|
||||
1791502670850,89.795
|
||||
1791502671850,84.343
|
||||
1791502672850,75.757
|
||||
1791502673850,69.035
|
||||
1791502674850,76.142
|
||||
1791502675851,87.437
|
||||
1791502676851,84.848
|
||||
1791502677851,74.489
|
||||
1791502678851,98.5
|
||||
1791502679851,55.329
|
||||
1791502680851,86.294
|
||||
1791502681852,66.326
|
||||
1791502682852,83.919
|
||||
1791502683852,82.142
|
||||
1791502684852,74.242
|
||||
1791502685852,86.363
|
||||
1791502686853,73.0
|
||||
1791502687853,80.412
|
||||
1791502688853,73.0
|
||||
1791502689853,87.309
|
||||
1791502690853,85.427
|
||||
1791502691854,76.767
|
||||
1791502692854,86.432
|
||||
1791502693854,79.081
|
||||
1791502694854,77.272
|
||||
1791502695855,78.499
|
||||
1791502696855,72.959
|
||||
1791502697855,84.924
|
||||
1791502698855,88.442
|
||||
1791502699855,81.122
|
||||
1791502700856,78.68
|
||||
1791502701856,77.04
|
||||
1791502702856,77.664
|
||||
1791502703856,75.634
|
||||
1791502704856,88.383
|
||||
1791502705857,72.081
|
||||
1791502706857,98.507
|
||||
1791502707857,67.346
|
||||
1791502708857,76.649
|
||||
1791502709857,67.525
|
||||
1791502710858,86.432
|
||||
1791502711858,91.414
|
||||
1791502712858,83.838
|
||||
1791502713858,84.263
|
||||
1791502714858,80.102
|
||||
1791502715859,74.0
|
||||
1791502716859,78.68
|
||||
1791502717859,82.741
|
||||
1791502718859,80.71
|
||||
1791502719859,84.924
|
||||
1791502720860,84.422
|
||||
1791502721860,73.604
|
||||
1791502722860,71.212
|
||||
1791502723860,87.817
|
||||
1791502724860,79.899
|
||||
1791502725861,88.888
|
||||
1791502726861,76.884
|
||||
1791502727861,83.756
|
||||
1791502728861,76.142
|
||||
1791502729861,85.353
|
||||
1791502730862,87.755
|
||||
1791502731862,80.303
|
||||
1791502732862,77.386
|
||||
1791502733862,87.878
|
||||
1791502734863,69.897
|
||||
1791502735863,88.888
|
||||
1791502736863,81.218
|
||||
1791502737863,69.191
|
||||
1791502738863,85.858
|
||||
1791502739864,97.0
|
||||
1791502740864,70.618
|
||||
1791502741864,67.676
|
||||
1791502742864,86.432
|
||||
1791502743864,74.489
|
||||
1791502744865,74.242
|
||||
1791502745865,91.919
|
||||
1791502746865,98.507
|
||||
1791502747865,58.974
|
||||
1791502748865,85.572
|
||||
1791502749866,84.263
|
||||
1791502750866,71.212
|
||||
1791502751866,74.747
|
||||
1791502752866,98.994
|
||||
1791502753866,75.376
|
||||
1791502754867,79.797
|
||||
1791502755867,90.909
|
||||
1791502756867,75.252
|
||||
1791502757867,69.035
|
||||
1791502758867,89.393
|
||||
1791502759868,80.71
|
||||
1791502760868,83.582
|
||||
1791502761868,89.847
|
||||
1791502762868,82.412
|
||||
1791502763868,62.244
|
||||
1791502764869,80.612
|
||||
1791502765869,79.187
|
||||
1791502766869,80.0
|
||||
1791502767869,78.974
|
||||
1791502768869,87.437
|
||||
1791502769870,68.527
|
||||
1791502770870,75.252
|
||||
1791502771870,87.5
|
||||
1791502772870,79.695
|
||||
1791502773870,88.0
|
||||
1791502774871,78.787
|
||||
1791502775871,85.858
|
||||
1791502776871,80.808
|
||||
1791502777871,72.588
|
||||
1791502778871,90.954
|
||||
1791502779872,80.303
|
||||
1791502780872,84.343
|
||||
1791502781872,80.102
|
||||
1791502782872,97.5
|
||||
1791502783872,65.989
|
||||
1791502784873,74.747
|
||||
1791502785873,81.725
|
||||
1791502786873,89.393
|
||||
1791502787873,77.272
|
||||
1791502788873,79.695
|
||||
1791502789874,90.909
|
||||
1791502790874,66.497
|
||||
1791502791874,83.756
|
||||
1791502792874,84.422
|
||||
1791502793874,78.974
|
||||
1791502794875,87.373
|
||||
1791502795875,77.551
|
||||
1791502796875,84.0
|
||||
1791502797875,76.02
|
||||
1791502798875,74.747
|
||||
1791502799876,82.323
|
||||
1791502800876,87.939
|
||||
1791502801876,78.172
|
||||
1791502802876,83.582
|
||||
1791502803876,79.292
|
||||
1791502804877,79.187
|
||||
1791502805877,73.737
|
||||
1791502806877,81.725
|
||||
1791502807877,85.353
|
||||
1791502808877,80.102
|
||||
1791502809877,81.313
|
||||
1791502810878,87.373
|
||||
1791502811878,80.5
|
||||
1791502812878,77.777
|
||||
1791502813878,74.874
|
||||
1791502814878,85.786
|
||||
1791502815879,82.914
|
||||
1791502816879,88.5
|
||||
1791502817879,74.619
|
||||
1791502818879,85.279
|
||||
1791502819879,73.979
|
||||
1791502820879,76.649
|
||||
1791502821880,75.757
|
||||
1791502822880,87.373
|
||||
1791502823880,96.0
|
||||
1791502824880,70.351
|
||||
1791502825880,73.333
|
||||
1791502826881,83.417
|
||||
1791502827881,84.343
|
||||
1791502828881,74.747
|
||||
1791502829881,89.34
|
||||
1791502830881,92.385
|
||||
1791502831882,83.417
|
||||
1791502832882,69.035
|
||||
1791502833882,75.252
|
||||
1791502834882,86.868
|
||||
1791502835882,81.909
|
||||
1791502836882,79.187
|
||||
1791502837883,75.879
|
||||
1791502838883,97.487
|
||||
1791502839883,68.844
|
||||
1791502840883,70.351
|
||||
1791502841883,77.948
|
||||
1791502842884,88.383
|
||||
1791502843884,96.984
|
||||
1791502844884,83.756
|
||||
1791502845884,81.909
|
||||
1791502846884,78.68
|
||||
1791502847885,73.096
|
||||
1791502848885,83.417
|
||||
1791502849885,86.294
|
||||
1791502850885,78.894
|
||||
1791502851885,79.081
|
||||
1791502852885,89.898
|
||||
1791502853886,75.634
|
||||
1791502854886,64.141
|
||||
1791502855886,95.477
|
||||
1791502856886,77.272
|
||||
1791502857886,85.786
|
||||
1791502858887,82.828
|
||||
1791502859887,91.457
|
||||
1791502860887,66.836
|
||||
1791502861887,85.204
|
||||
1791502862887,75.124
|
||||
1791502863887,82.828
|
||||
1791502864888,80.303
|
||||
1791502865888,80.904
|
||||
1791502866888,79.695
|
||||
1791502867888,77.272
|
||||
1791502868888,80.5
|
||||
1791502869889,81.909
|
||||
1791502870889,81.313
|
||||
1791502871889,97.474
|
||||
1791502872889,78.391
|
||||
1791502873889,64.974
|
||||
1791502874890,67.857
|
||||
1791502875890,88.442
|
||||
1791502876890,78.68
|
||||
1791502877890,76.142
|
||||
1791502878890,94.444
|
||||
1791502879890,79.5
|
||||
1791502880891,57.142
|
||||
1791502881891,76.262
|
||||
1791502882891,83.333
|
||||
1791502883891,78.0
|
||||
1791502884891,87.437
|
||||
1791502885892,82.323
|
||||
1791502886892,87.373
|
||||
1791502887892,69.387
|
||||
1791502888892,76.884
|
||||
1791502889892,78.172
|
||||
1791502890892,76.767
|
||||
1791502891893,90.954
|
||||
1791502892893,81.313
|
||||
1791502893893,80.303
|
||||
1791502894893,75.252
|
||||
1791502895893,72.588
|
||||
1791502896894,87.878
|
||||
1791502897894,89.898
|
||||
1791502898894,96.446
|
||||
1791502899894,77.499
|
||||
1791502900894,81.725
|
||||
1791502901895,85.858
|
||||
1791502902895,69.23
|
||||
1791502903895,84.422
|
||||
1791502904895,90.954
|
||||
1791502905895,82.828
|
||||
1791502906895,82.233
|
||||
1791502907896,81.218
|
||||
1791502908896,74.874
|
||||
1791502909896,71.717
|
||||
1791502910896,73.604
|
||||
1791502911896,97.487
|
||||
1791502912896,82.914
|
||||
1791502913897,84.343
|
||||
1791502914897,89.393
|
||||
1791502915897,67.676
|
||||
1791502916897,70.918
|
||||
1791502917897,85.353
|
||||
1791502918898,81.407
|
||||
1791502919898,71.794
|
||||
1791502920898,89.949
|
||||
1791502921898,84.0
|
||||
1791502922898,75.126
|
||||
1791502923899,77.889
|
||||
1791502924899,81.122
|
||||
1791502925899,83.919
|
||||
1791502926899,79.797
|
||||
1791502927899,89.447
|
||||
1791502928900,79.695
|
||||
1791502929900,78.68
|
||||
1791502930900,73.869
|
||||
1791502931900,94.472
|
||||
1791502932900,73.979
|
||||
1791502933901,85.427
|
||||
1791502934901,79.396
|
||||
1791502935901,97.0
|
||||
1791502936901,60.406
|
||||
1791502937901,70.707
|
||||
1791502938901,89.393
|
||||
1791502939902,77.777
|
||||
1791502940902,72.727
|
||||
1791502941902,84.771
|
||||
1791502942902,84.848
|
||||
1791502943902,77.889
|
||||
1791502944902,88.383
|
||||
1791502945903,79.695
|
||||
1791502946903,76.767
|
||||
1791502947903,76.262
|
||||
1791502948903,91.37
|
||||
1791502949903,90.954
|
||||
1791502950904,73.604
|
||||
1791502951904,74.747
|
||||
1791502952904,83.248
|
||||
1791502953904,87.939
|
||||
1791502954904,76.02
|
||||
1791502955904,89.898
|
||||
1791502956905,68.527
|
||||
1791502957905,87.309
|
||||
1791502958905,80.303
|
||||
1791502959905,73.869
|
||||
1791502960905,92.893
|
||||
1791502961905,83.673
|
||||
1791502962906,79.396
|
||||
1791502963906,81.909
|
||||
1791502964907,83.5
|
||||
1791502965907,65.816
|
||||
1791502966907,79.695
|
||||
1791502967907,77.272
|
||||
1791502968907,89.898
|
||||
1791502969908,72.588
|
||||
1791502970908,80.808
|
||||
1791502971908,77.777
|
||||
1791502972908,79.292
|
||||
1791502973908,79.292
|
||||
1791502974908,76.41
|
||||
1791502975909,74.747
|
||||
1791502976909,82.412
|
||||
1791502977909,83.756
|
||||
1791502978909,76.884
|
||||
1791502979909,81.122
|
||||
1791502980910,82.914
|
||||
1791502981910,72.959
|
||||
1791502982910,70.707
|
||||
1791502983910,88.832
|
||||
1791502984910,70.558
|
||||
1791502985911,90.355
|
||||
1791502986911,85.858
|
||||
1791502987911,70.707
|
||||
1791502988911,80.808
|
||||
1791502989911,80.904
|
||||
1791502990911,84.771
|
||||
1791502991912,84.422
|
||||
1791502992912,76.262
|
||||
1791502993912,81.725
|
||||
1791502994912,91.919
|
||||
1791502995912,78.391
|
||||
1791502996913,72.081
|
||||
1791502997913,84.343
|
||||
1791502998913,89.949
|
||||
1791502999913,68.181
|
||||
1791503000913,83.248
|
||||
1791503001913,77.777
|
||||
1791503002914,79.292
|
||||
1791503003914,80.102
|
||||
1791503004914,83.417
|
||||
1791503005914,76.649
|
||||
1791503006914,75.252
|
||||
1791503007915,84.422
|
||||
1791503008915,76.142
|
||||
1791503009915,78.894
|
||||
1791503010915,82.914
|
||||
1791503011915,73.979
|
||||
1791503012915,96.984
|
||||
1791503013916,61.111
|
||||
1791503014916,77.664
|
||||
1791503015916,98.484
|
||||
1791503016916,74.371
|
||||
1791503017916,73.604
|
||||
1791503018917,96.969
|
||||
1791503019917,86.363
|
||||
1791503020917,69.696
|
||||
1791503021917,84.263
|
||||
1791503022917,90.954
|
||||
1791503023917,71.794
|
||||
1791503024918,81.0
|
||||
1791503025918,78.787
|
||||
1791503026918,79.899
|
||||
1791503027918,80.102
|
||||
1791503028918,77.664
|
||||
1791503029919,79.292
|
||||
1791503030919,95.0
|
||||
1791503031919,72.588
|
||||
1791503032919,78.68
|
||||
1791503033919,76.649
|
||||
1791503034919,81.909
|
||||
1791503035920,84.422
|
||||
1791503036920,78.172
|
||||
1791503037920,86.868
|
||||
1791503038920,83.838
|
||||
1791503039920,83.163
|
||||
1791503040920,77.551
|
||||
1791503041921,73.232
|
||||
1791503042921,76.41
|
||||
1791503043921,87.373
|
||||
1791503044921,88.832
|
||||
1791503045921,76.884
|
||||
1791503046922,86.294
|
||||
1791503047922,62.626
|
||||
1791503048922,92.424
|
||||
1791503049922,79.899
|
||||
1791503050922,73.604
|
||||
1791503051923,87.939
|
||||
1791503052923,78.172
|
||||
1791503053923,72.081
|
||||
1791503054923,77.664
|
||||
1791503055923,77.499
|
||||
1791503056924,85.279
|
||||
1791503057924,78.282
|
||||
1791503058924,95.0
|
||||
1791503059924,63.959
|
||||
1791503060924,84.924
|
||||
1791503061924,78.172
|
||||
1791503062925,74.619
|
||||
1791503063925,92.893
|
||||
1791503064925,87.5
|
||||
1791503065925,83.756
|
||||
1791503066925,85.858
|
||||
1791503067926,73.737
|
||||
1791503068926,77.664
|
||||
1791503069926,77.272
|
||||
1791503070926,93.939
|
||||
1791503071926,83.919
|
||||
1791503072926,71.573
|
||||
1791503073927,75.126
|
||||
1791503074927,84.924
|
||||
1791503075927,86.802
|
||||
1791503076927,82.089
|
||||
1791503077927,85.279
|
||||
1791503078927,88.888
|
||||
1791503079928,75.252
|
||||
1791503080928,91.878
|
||||
1791503081928,69.696
|
||||
1791503082928,84.924
|
||||
1791503083928,80.203
|
||||
1791503084929,82.741
|
||||
1791503085929,81.218
|
||||
1791503086929,81.538
|
||||
1791503087929,83.838
|
||||
1791503088929,73.737
|
||||
1791503089929,90.909
|
||||
1791503090930,73.096
|
||||
1791503091930,86.934
|
||||
1791503092930,83.417
|
||||
1791503093930,78.061
|
||||
1791503094930,91.414
|
||||
1791503095930,67.857
|
||||
1791503096931,84.577
|
||||
1791503097931,78.68
|
||||
1791503098931,73.737
|
||||
1791503099931,95.959
|
||||
1791503100931,87.562
|
||||
1791503101932,79.292
|
||||
1791503102932,70.558
|
||||
1791503103932,80.904
|
||||
1791503104932,84.848
|
||||
1791503105932,78.391
|
||||
1791503106932,83.417
|
||||
1791503107933,79.187
|
||||
1791503108933,88.888
|
||||
1791503109933,66.834
|
||||
1791503110933,78.061
|
||||
1791503111933,83.919
|
||||
1791503112933,74.242
|
||||
1791503113934,93.0
|
||||
1791503114934,65.816
|
||||
1791503115934,78.894
|
||||
1791503116934,76.884
|
||||
1791503117934,85.714
|
||||
1791503118935,82.5
|
||||
1791503119935,58.375
|
||||
1791503120935,98.009
|
||||
1791503121935,62.755
|
||||
1791503122935,76.53
|
||||
1791503123935,93.467
|
||||
1791503124936,75.126
|
||||
1791503125936,72.081
|
||||
1791503126936,77.948
|
||||
1791503127936,90.404
|
||||
1791503128936,78.68
|
||||
1791503129936,78.282
|
||||
1791503130937,78.172
|
||||
1791503131937,71.938
|
||||
1791503132937,82.914
|
||||
1791503133937,74.619
|
||||
1791503134937,94.472
|
||||
1791503135938,80.203
|
||||
1791503136938,68.02
|
||||
1791503137938,81.218
|
||||
1791503138938,78.68
|
||||
1791503139938,82.323
|
||||
1791503140939,74.242
|
||||
1791503141939,98.492
|
||||
1791503142939,72.727
|
||||
1791503143939,82.323
|
||||
1791503144939,75.51
|
||||
1791503145939,87.437
|
||||
1791503146940,75.897
|
||||
1791503147940,82.412
|
||||
1791503148940,83.838
|
||||
1791503149940,77.157
|
||||
1791503150940,82.653
|
||||
1791503151940,80.303
|
||||
1791503152941,88.888
|
||||
1791503153941,81.909
|
||||
1791503154941,88.324
|
||||
1791503155941,70.707
|
||||
1791503156941,85.858
|
||||
1791503157942,80.71
|
||||
1791503158942,85.427
|
||||
1791503159942,69.897
|
||||
1791503160942,66.834
|
||||
1791503161942,94.472
|
||||
1791503162942,90.0
|
||||
1791503163943,67.171
|
||||
1791503164943,77.777
|
||||
1791503165943,88.383
|
||||
1791503166943,59.595
|
||||
1791503167943,69.543
|
||||
1791503168943,96.5
|
||||
1791503169944,67.512
|
||||
1791503170944,69.897
|
||||
1791503171944,93.034
|
||||
1791503172944,79.797
|
||||
1791503173944,65.816
|
||||
1791503174945,83.756
|
||||
1791503175945,90.0
|
||||
1791503176945,68.367
|
||||
1791503177945,78.894
|
||||
1791503178945,89.393
|
||||
1791503179945,80.203
|
||||
1791503180946,64.615
|
||||
1791503181946,81.632
|
||||
1791503182946,80.904
|
||||
1791503183946,88.324
|
||||
1791503184946,84.183
|
||||
1791503185947,78.787
|
||||
1791503186947,83.248
|
||||
1791503187947,87.939
|
||||
1791503188947,82.323
|
||||
1791503189947,81.725
|
||||
1791503190947,88.888
|
||||
1791503191948,76.649
|
||||
1791503192948,73.979
|
||||
1791503193948,94.472
|
||||
1791503194948,63.451
|
||||
1791503195948,91.919
|
||||
1791503196949,66.836
|
||||
1791503197949,84.263
|
||||
|
@@ -0,0 +1,186 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate JMeter plans with the PerfMon listener; no application changes required."""
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as E
|
||||
from perfmon import METRICS
|
||||
|
||||
OUT = Path(__file__).parent / 'plans'
|
||||
|
||||
def prop(parent, name, value, kind='stringProp'):
|
||||
E.SubElement(parent, kind, name=name).text = str(value).lower() if isinstance(value, bool) else str(value)
|
||||
|
||||
def element(tree, tag, gui, name, **attrs):
|
||||
e = E.SubElement(tree, tag, guiclass=gui, testclass=tag, testname=name, enabled='true', **attrs)
|
||||
return e, E.SubElement(tree, 'hashTree')
|
||||
|
||||
def script(tree, tag, name, code):
|
||||
e, t = element(tree, tag, tag+'Gui', name)
|
||||
for k,v in [('scriptLanguage','groovy'),('cacheKey','true'),('filename',''),('parameters',''),('script',code)]: prop(e,k,v)
|
||||
return t
|
||||
|
||||
def request(tree, name, method, path, body='', status=200, check=''):
|
||||
e, t = element(tree,'HTTPSamplerProxy','HttpTestSampleGui','HTTP '+name)
|
||||
args = E.SubElement(e,'elementProp',name='HTTPsampler.Arguments',elementType='Arguments',guiclass='HTTPArgumentsPanel',testclass='Arguments',enabled='true')
|
||||
collection = E.SubElement(args,'collectionProp',name='Arguments.arguments')
|
||||
if body:
|
||||
arg = E.SubElement(collection,'elementProp',name='',elementType='HTTPArgument')
|
||||
prop(arg,'HTTPArgument.always_encode',False,'boolProp'); prop(arg,'Argument.value',body); prop(arg,'Argument.metadata','=')
|
||||
for k,v in [('HTTPSampler.domain','${__P(host,127.0.0.1)}'),('HTTPSampler.port','${__P(port,5443)}'),('HTTPSampler.protocol','https'),('HTTPSampler.path',path),('HTTPSampler.method',method),('HTTPSampler.implementation','HttpClient4'),('HTTPSampler.connect_timeout','10000'),('HTTPSampler.response_timeout','30000')]: prop(e,k,v)
|
||||
for k,v in [('HTTPSampler.postBodyRaw',bool(body)),('HTTPSampler.follow_redirects',False),('HTTPSampler.auto_redirects',False),('HTTPSampler.use_keepalive',True),('HTTPSampler.DO_MULTIPART_POST',False)]: prop(e,k,v,'boolProp')
|
||||
# HTTP status and semantic checks fail the thread rather than generating cascades.
|
||||
script(t,'JSR223Assertion','Expected response',f'''if (prev.getResponseCode() != '{status}') {{
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
{('def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())' if check else '')}
|
||||
{check}
|
||||
''')
|
||||
script(t,'JSR223Timer','Gaussian interaction pause', """def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
""")
|
||||
|
||||
PERIOD = 'from=${period_from}&to=${period_to}'
|
||||
PATIENT = '/api/patients/${patient_id}'
|
||||
|
||||
def review(t, professional=False):
|
||||
if professional:
|
||||
request(t,'Assigned patients','GET','/api/professionals/me/patients',check="assert json.any { it.patientId == vars.get('patient_id') } : 'Target patient is not assigned'")
|
||||
request(t,'Read profile','GET',PATIENT if professional else '/api/patients/me',check="assert json.patientId == vars.get('patient_id')")
|
||||
request(t,'Latest reading','GET',PATIENT+'/observations/latest',check="assert json.patientId == vars.get('patient_id')")
|
||||
request(t,'Home resting history','GET',PATIENT+'/observations?'+PERIOD+'&setting=Home&activityCondition=AtRest',check="assert json instanceof List && !json.empty : 'Seed observations first'")
|
||||
request(t,'Numerical insights','GET',PATIENT+'/insights?'+PERIOD+'&setting=Home&activityCondition=AtRest',check="assert json.contributingCount > 0")
|
||||
request(t,'Trends','GET',PATIENT+'/trends?'+PERIOD)
|
||||
overview(t)
|
||||
|
||||
def overview(t):
|
||||
request(t,'Health overview','GET',PATIENT+'/overview?'+PERIOD,check="assert json.patient.patientId == vars.get('patient_id'); assert json.latestObservation != null; assert json.insight != null")
|
||||
|
||||
def record(t, correction=False):
|
||||
request(t,'Measurement guidance','GET','/api/measurement-guidance?setting=Home&activityCondition=AtRest')
|
||||
request(t,'Read own profile','GET','/api/patients/me',check="assert json.patientId == vars.get('patient_id')")
|
||||
request(t,'Record synthetic measurement','POST',PATIENT+'/observations','${observation_body}',201,"assert json.patientId == vars.get('patient_id'); assert json.observationId; vars.put('observation_id',json.observationId)")
|
||||
if correction:
|
||||
request(t,'Correct entry and context','PATCH','/api/observations/${observation_id}','{"systolic":128,"measurementContext":{"additionalCircumstances":"Corrected synthetic entry"}}',check="assert json.systolic == 128")
|
||||
request(t,'Confirm saved reading','GET','/api/observations/${observation_id}',check="assert json.observationId == vars.get('observation_id')")
|
||||
overview(t)
|
||||
if correction:
|
||||
request(t,'Remove duplicate test entry','DELETE','/api/observations/${observation_id}',status=204)
|
||||
request(t,'Confirm removal','GET','/api/observations/${observation_id}',status=404)
|
||||
|
||||
def shelly_group(tree):
|
||||
group,gt=element(tree,'ThreadGroup','ThreadGroupGui','Shelly live power')
|
||||
prop(group,'ThreadGroup.on_sample_error','continue')
|
||||
loop=E.SubElement(group,'elementProp',name='ThreadGroup.main_controller',elementType='LoopController',guiclass='LoopControlPanel',testclass='LoopController',enabled='true')
|
||||
prop(loop,'LoopController.continue_forever',False,'boolProp');prop(loop,'LoopController.loops',-1)
|
||||
for k,v in [('ThreadGroup.num_threads','1'),('ThreadGroup.ramp_time','0'),('ThreadGroup.duration','${__P(total_duration_seconds,16210)}'),('ThreadGroup.delay','0')]:prop(group,k,v)
|
||||
prop(group,'ThreadGroup.scheduler',True,'boolProp')
|
||||
e,t=element(gt,'HTTPSamplerProxy','HttpTestSampleGui','POWER Shelly status')
|
||||
E.SubElement(E.SubElement(e,'elementProp',name='HTTPsampler.Arguments',elementType='Arguments'),'collectionProp',name='Arguments.arguments')
|
||||
for k,v in [('HTTPSampler.domain','${__P(shelly_host,192.168.1.44)}'),('HTTPSampler.port','${__P(shelly_port,80)}'),('HTTPSampler.protocol','http'),('HTTPSampler.path','/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}'),('HTTPSampler.method','GET'),('HTTPSampler.implementation','HttpClient4'),('HTTPSampler.connect_timeout','3000'),('HTTPSampler.response_timeout','3000')]:prop(e,k,v)
|
||||
for k,v in [('HTTPSampler.follow_redirects',False),('HTTPSampler.use_keepalive',True)]:prop(e,k,v,'boolProp')
|
||||
script(t,'JSR223Timer','Fixed meter cadence', "if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','1000')) - System.currentTimeMillis())")
|
||||
script(t,'JSR223PreProcessor','Clear stale power values', "['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }")
|
||||
script(t,'JSR223Assertion','Validate and extract plug readings', """vars.put('shelly_last_poll_ms',prev.getStartTime().toString())
|
||||
try {
|
||||
assert prev.getResponseCode() == '200'
|
||||
def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.output == true : 'Outlet is off'
|
||||
def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total]
|
||||
readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) }
|
||||
} catch (Throwable error) {
|
||||
AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false)
|
||||
}
|
||||
""")
|
||||
collector,_=element(gt,'ResultCollector','SimpleDataWriter','Shelly measurements saved live')
|
||||
prop(collector,'filename','${__P(shelly_file,shelly.csv)}');prop(collector,'ResultCollector.error_logging',False,'boolProp')
|
||||
|
||||
for scenario in ['recording','review','correction','professional','mixed','idle']:
|
||||
root=E.Element('jmeterTestPlan',version='1.2',properties='5.0',jmeter='5.6.3'); tree=E.SubElement(root,'hashTree')
|
||||
plan, pt=element(tree,'TestPlan','TestPlanGui','HealthApp energy: '+scenario)
|
||||
prop(plan,'TestPlan.comments','Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.')
|
||||
prop(plan,'TestPlan.functional_mode',False,'boolProp'); prop(plan,'TestPlan.serialize_threadgroups',False,'boolProp')
|
||||
E.SubElement(E.SubElement(plan,'elementProp',name='TestPlan.user_defined_variables',elementType='Arguments',guiclass='ArgumentsPanel',testclass='Arguments',enabled='true'),'collectionProp',name='Arguments.arguments')
|
||||
shelly_group(pt)
|
||||
collector, _ = element(pt,'kg.apc.jmeter.perfmon.PerfMonCollector','kg.apc.jmeter.vizualizers.PerfMonGui','NUC live CPU RAM disk and network')
|
||||
collector.set('enabled','true')
|
||||
prop(collector,'filename','${__P(perfmon_file,perfmon.csv)}')
|
||||
prop(collector,'ResultCollector.error_logging',False,'boolProp')
|
||||
connections=E.SubElement(collector,'collectionProp',name='metricConnections')
|
||||
for i,(kind,param,unit) in enumerate(METRICS):
|
||||
row=E.SubElement(connections,'collectionProp',name=str(i))
|
||||
for j,value in enumerate(['${__P(perfmon_host,192.168.1.125)}','${__P(perfmon_port,4444)}',kind,param]):prop(row,str(j),value)
|
||||
group, gt=element(pt,'ThreadGroup','ThreadGroupGui','Users')
|
||||
prop(group,'ThreadGroup.on_sample_error','stopthread')
|
||||
loop=E.SubElement(group,'elementProp',name='ThreadGroup.main_controller',elementType='LoopController',guiclass='LoopControlPanel',testclass='LoopController',enabled='true')
|
||||
prop(loop,'LoopController.continue_forever',False,'boolProp'); prop(loop,'LoopController.loops',-1)
|
||||
for k,v in [('ThreadGroup.num_threads','${__P(users,1)}'),('ThreadGroup.ramp_time','${__P(ramp_seconds,60)}'),('ThreadGroup.duration','${__P(total_duration_seconds,16210)}'),('ThreadGroup.delay','0')]: prop(group,k,v)
|
||||
prop(group,'ThreadGroup.scheduler',True,'boolProp'); prop(group,'ThreadGroup.same_user_on_next_iteration',True,'boolProp')
|
||||
if scenario=='idle':
|
||||
prop(group,'ThreadGroup.num_threads','1');prop(group,'ThreadGroup.ramp_time','0')
|
||||
once, ot=element(gt,'OnceOnlyController','OnceOnlyControllerGui','Record idle measurement window')
|
||||
script(ot,'JSR223Sampler','Idle timing', '''long start=System.currentTimeMillis()
|
||||
long measurement=start+Long.parseLong(props.getProperty('warmup_seconds','1800'))*1000
|
||||
long end=measurement+Long.parseLong(props.getProperty('duration_seconds','14400'))*1000
|
||||
if (props.get('timeline_file')) new File(props.get('timeline_file')).text=groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
||||
''')
|
||||
pause,_=element(gt,'TestAction','TestActionGui','Idle wait; no application requests')
|
||||
prop(pause,'ActionProcessor.action',1,'intProp');prop(pause,'ActionProcessor.target',0,'intProp');prop(pause,'ActionProcessor.duration','1000')
|
||||
E.indent(root);E.ElementTree(root).write(OUT/(scenario+'.jmx'),encoding='utf-8',xml_declaration=True)
|
||||
continue
|
||||
headers, _=element(gt,'HeaderManager','HeaderPanel','JSON and bearer token')
|
||||
coll=E.SubElement(headers,'collectionProp',name='HeaderManager.headers')
|
||||
for name,value in [('Content-Type','application/json'),('Authorization','Bearer ${token}')]:
|
||||
h=E.SubElement(coll,'elementProp',name='',elementType='Header');prop(h,'Header.name',name);prop(h,'Header.value',value)
|
||||
once, ot=element(gt,'OnceOnlyController','OnceOnlyControllerGui','Assign one account per user')
|
||||
script(ot,'JSR223Sampler','Initialize user', '''def rows = new File(props.get('users_file')).readLines('UTF-8').drop(1).findAll { it.trim() }
|
||||
def row = rows[ctx.getThreadNum()].split(',', -1)
|
||||
vars.put('account_id', row[0]); vars.put('password', row[1]); vars.put('patient_id', row[2])
|
||||
vars.put('token', ''); vars.put('expires_at', '0'); vars.put('session_number','0')
|
||||
vars.putObject('user_random', new Random(Long.parseLong(props.getProperty('random_seed','42')) + ctx.getThreadNum()))
|
||||
synchronized(props) {
|
||||
if (props.get('timeline_file') && !props.get('workload_start_ms')) {
|
||||
long start = System.currentTimeMillis()
|
||||
long measurement = start + Long.parseLong(props.getProperty('warmup_seconds','1800')) * 1000
|
||||
long end = measurement + Long.parseLong(props.getProperty('duration_seconds','14400')) * 1000
|
||||
props.put('workload_start_ms',start.toString())
|
||||
new File(props.get('timeline_file')).text = groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
||||
}
|
||||
}
|
||||
''')
|
||||
script(gt,'JSR223Sampler','Prepare session', '''def now = java.time.Instant.now()
|
||||
vars.put('refresh_login', (now.epochSecond >= Long.parseLong(vars.get('expires_at')) - 60).toString())
|
||||
vars.put('login_body',groovy.json.JsonOutput.toJson([accountId:vars.get('account_id'),password:vars.get('password')]))
|
||||
vars.put('period_from',props.get('period_from')); vars.put('period_to',props.get('period_to'))
|
||||
int n = Integer.parseInt(vars.get('session_number')); vars.put('session_number',(n+1).toString())
|
||||
// Random session mix: expected 65% review, 30% recording, 5% correction.
|
||||
int slot = vars.getObject('user_random').nextInt(20)
|
||||
vars.put('session_kind',slot < 13 ? 'review' : slot < 19 ? 'recording' : 'correction')
|
||||
double mean = Double.parseDouble(props.getProperty('session_pause_ms','120000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('session_stddev_ms','30000'))
|
||||
vars.put('session_delay_ms',Math.max(0L,Math.round(mean + vars.getObject('user_random').nextGaussian()*deviation)).toString())
|
||||
vars.put('observation_body',groovy.json.JsonOutput.toJson([measuredAt:now.toString(),systolic:128+(n%7),diastolic:82+(n%4),pulse:68+(n%6),measurementContext:[setting:'Home',activityCondition:'AtRest',restDurationMinutes:5,bodyPosition:'Seated'],note:'Synthetic JMeter energy workload']))
|
||||
''')
|
||||
login, lt=element(gt,'IfController','IfControllerPanel','Login or renew expired token')
|
||||
prop(login,'IfController.condition','${refresh_login}');prop(login,'IfController.evaluateAll',False,'boolProp');prop(login,'IfController.useExpression',True,'boolProp')
|
||||
request(lt,'Login','POST','/api/authentication/login','${login_body}',check="assert json.accessToken; vars.put('token',json.accessToken); vars.put('expires_at',(java.time.Instant.now().epochSecond + (json.expiresIn as long)).toString())")
|
||||
if scenario=='mixed':
|
||||
for kind in ['review','recording','correction']:
|
||||
branch,bt=element(gt,'IfController','IfControllerPanel',kind+' session')
|
||||
prop(branch,'IfController.condition',"${__groovy(vars.get('session_kind') == '"+kind+"')}");prop(branch,'IfController.useExpression',True,'boolProp');prop(branch,'IfController.evaluateAll',False,'boolProp')
|
||||
review(bt) if kind=='review' else record(bt,kind=='correction')
|
||||
elif scenario in ['review','professional']: review(gt,scenario=='professional')
|
||||
else: record(gt,scenario=='correction')
|
||||
pause, _ = element(gt,'TestAction','TestActionGui','Between-session pause')
|
||||
prop(pause,'ActionProcessor.action',1,'intProp'); prop(pause,'ActionProcessor.target',0,'intProp'); prop(pause,'ActionProcessor.duration','${session_delay_ms}')
|
||||
E.indent(root); E.ElementTree(root).write(OUT/(scenario+'.jmx'),encoding='utf-8',xml_declaration=True)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""PerfMon agent preflight and JMeter's metric-file decoding."""
|
||||
import csv, math, socket
|
||||
METRICS=[('CPU','combined','percent'),('CPU','iowait','percent'),('Memory','usedperc','percent'),('Memory','actualused','bytes'),('Swap','used','bytes'),('Disks I/O','readbytes','bytes/second'),('Disks I/O','writebytes','bytes/second'),('Network I/O','bytesrecv','bytes/second'),('Network I/O','bytessent','bytes/second')]
|
||||
TYPES={'CPU':'cpu','Memory':'memory','Swap':'swap','Disks I/O':'disks','Network I/O':'network'}
|
||||
def check_agent(host,port):
|
||||
specs=[TYPES[k]+':'+param for k,param,_ in METRICS]
|
||||
with socket.create_connection((host,port),timeout=5) as s:
|
||||
s.settimeout(5);s.sendall(('metrics-single:'+'\t'.join(specs)+'\n').encode())
|
||||
values=s.makefile('r').readline(8192).strip().split('\t')
|
||||
if len(values)!=len(specs):raise ValueError('PerfMon returned an incomplete metric response')
|
||||
if any(not math.isfinite(float(v)) or float(v)<0 for v in values):raise ValueError('PerfMon reported unavailable/invalid metrics')
|
||||
return dict(zip(specs,map(float,values)))
|
||||
def summarize(raw,output,start,end,interval_ms):
|
||||
with raw.open() as f: rows=list(csv.DictReader(f))
|
||||
result=[];by_metric={}
|
||||
for row in rows:
|
||||
# PerfMon encodes the metric as synthetic elapsed milliseconds, not HTTP latency.
|
||||
if row.get('success','true').lower()!='true':raise ValueError('PerfMon collector reported a failed sample')
|
||||
value=float(row['elapsed'])/1000
|
||||
if not math.isfinite(value) or value<0:raise ValueError('PerfMon collector reported a metric error')
|
||||
timestamp=int(row['timeStamp'])
|
||||
if not start<=timestamp<=end:continue
|
||||
label=row['label']; unit=next((unit for kind,param,unit in METRICS if label.endswith(kind+' '+param)),'unknown')
|
||||
if unit=='unknown':raise ValueError('Unknown PerfMon label: '+label)
|
||||
result.append({'timestamp_ms':timestamp,'metric':label,'value':value,'unit':unit})
|
||||
by_metric.setdefault(label,[]).append((timestamp,value))
|
||||
if len(by_metric)!=len(METRICS):raise ValueError('Measured interval is missing required PerfMon metrics')
|
||||
stats={}
|
||||
for label,points in by_metric.items():
|
||||
points.sort();gaps=[b[0]-a[0] for a,b in zip(points,points[1:])]
|
||||
if max([points[0][0]-start,end-points[-1][0],*gaps])>interval_ms*3:raise ValueError('Gap in live monitoring: '+label)
|
||||
stats[label]={'samples':len(points),'mean':sum(v for _,v in points)/len(points),'max':max(v for _,v in points)}
|
||||
with output.open('w') as f:
|
||||
w=csv.DictWriter(f,fieldnames=['timestamp_ms','metric','value','unit']);w.writeheader();w.writerows(result)
|
||||
return stats
|
||||
@@ -0,0 +1,745 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: correction" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','1000')) - System.currentTimeMillis())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">vars.put('shelly_last_poll_ms',prev.getStartTime().toString())
|
||||
try {
|
||||
assert prev.getResponseCode() == '200'
|
||||
def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.output == true : 'Outlet is off'
|
||||
def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total]
|
||||
readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) }
|
||||
} catch (Throwable error) {
|
||||
AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<collectionProp name="metricConnections">
|
||||
<collectionProp name="0">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">combined</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="1">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">iowait</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="2">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">usedperc</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="3">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">actualused</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="4">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Swap</stringProp>
|
||||
<stringProp name="3">used</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="5">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">readbytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="6">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">writebytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="7">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytesrecv</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="8">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytessent</stringProp>
|
||||
</collectionProp>
|
||||
</collectionProp>
|
||||
</kg.apc.jmeter.perfmon.PerfMonCollector>
|
||||
<hashTree />
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="JSON and bearer token" enabled="true">
|
||||
<collectionProp name="HeaderManager.headers">
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Content-Type</stringProp>
|
||||
<stringProp name="Header.value">application/json</stringProp>
|
||||
</elementProp>
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Authorization</stringProp>
|
||||
<stringProp name="Header.value">Bearer ${token}</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</HeaderManager>
|
||||
<hashTree />
|
||||
<OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Assign one account per user" enabled="true" />
|
||||
<hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Initialize user" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rows = new File(props.get('users_file')).readLines('UTF-8').drop(1).findAll { it.trim() }
|
||||
def row = rows[ctx.getThreadNum()].split(',', -1)
|
||||
vars.put('account_id', row[0]); vars.put('password', row[1]); vars.put('patient_id', row[2])
|
||||
vars.put('token', ''); vars.put('expires_at', '0'); vars.put('session_number','0')
|
||||
vars.putObject('user_random', new Random(Long.parseLong(props.getProperty('random_seed','42')) + ctx.getThreadNum()))
|
||||
synchronized(props) {
|
||||
if (props.get('timeline_file') && !props.get('workload_start_ms')) {
|
||||
long start = System.currentTimeMillis()
|
||||
long measurement = start + Long.parseLong(props.getProperty('warmup_seconds','1800')) * 1000
|
||||
long end = measurement + Long.parseLong(props.getProperty('duration_seconds','14400')) * 1000
|
||||
props.put('workload_start_ms',start.toString())
|
||||
new File(props.get('timeline_file')).text = groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
||||
}
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Prepare session" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def now = java.time.Instant.now()
|
||||
vars.put('refresh_login', (now.epochSecond >= Long.parseLong(vars.get('expires_at')) - 60).toString())
|
||||
vars.put('login_body',groovy.json.JsonOutput.toJson([accountId:vars.get('account_id'),password:vars.get('password')]))
|
||||
vars.put('period_from',props.get('period_from')); vars.put('period_to',props.get('period_to'))
|
||||
int n = Integer.parseInt(vars.get('session_number')); vars.put('session_number',(n+1).toString())
|
||||
// Random session mix: expected 65% review, 30% recording, 5% correction.
|
||||
int slot = vars.getObject('user_random').nextInt(20)
|
||||
vars.put('session_kind',slot < 13 ? 'review' : slot < 19 ? 'recording' : 'correction')
|
||||
double mean = Double.parseDouble(props.getProperty('session_pause_ms','120000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('session_stddev_ms','30000'))
|
||||
vars.put('session_delay_ms',Math.max(0L,Math.round(mean + vars.getObject('user_random').nextGaussian()*deviation)).toString())
|
||||
vars.put('observation_body',groovy.json.JsonOutput.toJson([measuredAt:now.toString(),systolic:128+(n%7),diastolic:82+(n%4),pulse:68+(n%6),measurementContext:[setting:'Home',activityCondition:'AtRest',restDurationMinutes:5,bodyPosition:'Seated'],note:'Synthetic JMeter energy workload']))
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
<IfController guiclass="IfControllerPanel" testclass="IfController" testname="Login or renew expired token" enabled="true">
|
||||
<stringProp name="IfController.condition">${refresh_login}</stringProp>
|
||||
<boolProp name="IfController.evaluateAll">false</boolProp>
|
||||
<boolProp name="IfController.useExpression">true</boolProp>
|
||||
</IfController>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Login" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments">
|
||||
<elementProp name="" elementType="HTTPArgument">
|
||||
<boolProp name="HTTPArgument.always_encode">false</boolProp>
|
||||
<stringProp name="Argument.value">${login_body}</stringProp>
|
||||
<stringProp name="Argument.metadata">=</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/authentication/login</stringProp>
|
||||
<stringProp name="HTTPSampler.method">POST</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.accessToken; vars.put('token',json.accessToken); vars.put('expires_at',(java.time.Instant.now().epochSecond + (json.expiresIn as long)).toString())
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Measurement guidance" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/measurement-guidance?setting=Home&activityCondition=AtRest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
|
||||
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Read own profile" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/me</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Record synthetic measurement" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments">
|
||||
<elementProp name="" elementType="HTTPArgument">
|
||||
<boolProp name="HTTPArgument.always_encode">false</boolProp>
|
||||
<stringProp name="Argument.value">${observation_body}</stringProp>
|
||||
<stringProp name="Argument.metadata">=</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/observations</stringProp>
|
||||
<stringProp name="HTTPSampler.method">POST</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '201') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id'); assert json.observationId; vars.put('observation_id',json.observationId)
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Correct entry and context" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments">
|
||||
<elementProp name="" elementType="HTTPArgument">
|
||||
<boolProp name="HTTPArgument.always_encode">false</boolProp>
|
||||
<stringProp name="Argument.value">{"systolic":128,"measurementContext":{"additionalCircumstances":"Corrected synthetic entry"}}</stringProp>
|
||||
<stringProp name="Argument.metadata">=</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/observations/${observation_id}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">PATCH</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.systolic == 128
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Confirm saved reading" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/observations/${observation_id}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.observationId == vars.get('observation_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Health overview" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/overview?from=${period_from}&to=${period_to}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patient.patientId == vars.get('patient_id'); assert json.latestObservation != null; assert json.insight != null
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Remove duplicate test entry" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/observations/${observation_id}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">DELETE</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '204') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
|
||||
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Confirm removal" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/observations/${observation_id}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '404') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
|
||||
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<TestAction guiclass="TestActionGui" testclass="TestAction" testname="Between-session pause" enabled="true">
|
||||
<intProp name="ActionProcessor.action">1</intProp>
|
||||
<intProp name="ActionProcessor.target">0</intProp>
|
||||
<stringProp name="ActionProcessor.duration">${session_delay_ms}</stringProp>
|
||||
</TestAction>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</jmeterTestPlan>
|
||||
@@ -0,0 +1,184 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: idle" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','1000')) - System.currentTimeMillis())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">vars.put('shelly_last_poll_ms',prev.getStartTime().toString())
|
||||
try {
|
||||
assert prev.getResponseCode() == '200'
|
||||
def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.output == true : 'Outlet is off'
|
||||
def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total]
|
||||
readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) }
|
||||
} catch (Throwable error) {
|
||||
AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<collectionProp name="metricConnections">
|
||||
<collectionProp name="0">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">combined</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="1">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">iowait</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="2">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">usedperc</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="3">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">actualused</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="4">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Swap</stringProp>
|
||||
<stringProp name="3">used</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="5">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">readbytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="6">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">writebytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="7">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytesrecv</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="8">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytessent</stringProp>
|
||||
</collectionProp>
|
||||
</collectionProp>
|
||||
</kg.apc.jmeter.perfmon.PerfMonCollector>
|
||||
<hashTree />
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Record idle measurement window" enabled="true" />
|
||||
<hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Idle timing" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">long start=System.currentTimeMillis()
|
||||
long measurement=start+Long.parseLong(props.getProperty('warmup_seconds','1800'))*1000
|
||||
long end=measurement+Long.parseLong(props.getProperty('duration_seconds','14400'))*1000
|
||||
if (props.get('timeline_file')) new File(props.get('timeline_file')).text=groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<TestAction guiclass="TestActionGui" testclass="TestAction" testname="Idle wait; no application requests" enabled="true">
|
||||
<intProp name="ActionProcessor.action">1</intProp>
|
||||
<intProp name="ActionProcessor.target">0</intProp>
|
||||
<stringProp name="ActionProcessor.duration">1000</stringProp>
|
||||
</TestAction>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</jmeterTestPlan>
|
||||
@@ -0,0 +1,678 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: professional" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','1000')) - System.currentTimeMillis())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">vars.put('shelly_last_poll_ms',prev.getStartTime().toString())
|
||||
try {
|
||||
assert prev.getResponseCode() == '200'
|
||||
def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.output == true : 'Outlet is off'
|
||||
def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total]
|
||||
readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) }
|
||||
} catch (Throwable error) {
|
||||
AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<collectionProp name="metricConnections">
|
||||
<collectionProp name="0">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">combined</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="1">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">iowait</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="2">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">usedperc</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="3">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">actualused</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="4">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Swap</stringProp>
|
||||
<stringProp name="3">used</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="5">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">readbytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="6">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">writebytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="7">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytesrecv</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="8">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytessent</stringProp>
|
||||
</collectionProp>
|
||||
</collectionProp>
|
||||
</kg.apc.jmeter.perfmon.PerfMonCollector>
|
||||
<hashTree />
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="JSON and bearer token" enabled="true">
|
||||
<collectionProp name="HeaderManager.headers">
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Content-Type</stringProp>
|
||||
<stringProp name="Header.value">application/json</stringProp>
|
||||
</elementProp>
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Authorization</stringProp>
|
||||
<stringProp name="Header.value">Bearer ${token}</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</HeaderManager>
|
||||
<hashTree />
|
||||
<OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Assign one account per user" enabled="true" />
|
||||
<hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Initialize user" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rows = new File(props.get('users_file')).readLines('UTF-8').drop(1).findAll { it.trim() }
|
||||
def row = rows[ctx.getThreadNum()].split(',', -1)
|
||||
vars.put('account_id', row[0]); vars.put('password', row[1]); vars.put('patient_id', row[2])
|
||||
vars.put('token', ''); vars.put('expires_at', '0'); vars.put('session_number','0')
|
||||
vars.putObject('user_random', new Random(Long.parseLong(props.getProperty('random_seed','42')) + ctx.getThreadNum()))
|
||||
synchronized(props) {
|
||||
if (props.get('timeline_file') && !props.get('workload_start_ms')) {
|
||||
long start = System.currentTimeMillis()
|
||||
long measurement = start + Long.parseLong(props.getProperty('warmup_seconds','1800')) * 1000
|
||||
long end = measurement + Long.parseLong(props.getProperty('duration_seconds','14400')) * 1000
|
||||
props.put('workload_start_ms',start.toString())
|
||||
new File(props.get('timeline_file')).text = groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
||||
}
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Prepare session" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def now = java.time.Instant.now()
|
||||
vars.put('refresh_login', (now.epochSecond >= Long.parseLong(vars.get('expires_at')) - 60).toString())
|
||||
vars.put('login_body',groovy.json.JsonOutput.toJson([accountId:vars.get('account_id'),password:vars.get('password')]))
|
||||
vars.put('period_from',props.get('period_from')); vars.put('period_to',props.get('period_to'))
|
||||
int n = Integer.parseInt(vars.get('session_number')); vars.put('session_number',(n+1).toString())
|
||||
// Random session mix: expected 65% review, 30% recording, 5% correction.
|
||||
int slot = vars.getObject('user_random').nextInt(20)
|
||||
vars.put('session_kind',slot < 13 ? 'review' : slot < 19 ? 'recording' : 'correction')
|
||||
double mean = Double.parseDouble(props.getProperty('session_pause_ms','120000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('session_stddev_ms','30000'))
|
||||
vars.put('session_delay_ms',Math.max(0L,Math.round(mean + vars.getObject('user_random').nextGaussian()*deviation)).toString())
|
||||
vars.put('observation_body',groovy.json.JsonOutput.toJson([measuredAt:now.toString(),systolic:128+(n%7),diastolic:82+(n%4),pulse:68+(n%6),measurementContext:[setting:'Home',activityCondition:'AtRest',restDurationMinutes:5,bodyPosition:'Seated'],note:'Synthetic JMeter energy workload']))
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
<IfController guiclass="IfControllerPanel" testclass="IfController" testname="Login or renew expired token" enabled="true">
|
||||
<stringProp name="IfController.condition">${refresh_login}</stringProp>
|
||||
<boolProp name="IfController.evaluateAll">false</boolProp>
|
||||
<boolProp name="IfController.useExpression">true</boolProp>
|
||||
</IfController>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Login" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments">
|
||||
<elementProp name="" elementType="HTTPArgument">
|
||||
<boolProp name="HTTPArgument.always_encode">false</boolProp>
|
||||
<stringProp name="Argument.value">${login_body}</stringProp>
|
||||
<stringProp name="Argument.metadata">=</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/authentication/login</stringProp>
|
||||
<stringProp name="HTTPSampler.method">POST</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.accessToken; vars.put('token',json.accessToken); vars.put('expires_at',(java.time.Instant.now().epochSecond + (json.expiresIn as long)).toString())
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Assigned patients" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/professionals/me/patients</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.any { it.patientId == vars.get('patient_id') } : 'Target patient is not assigned'
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Read profile" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Latest reading" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/observations/latest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Home resting history" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/observations?from=${period_from}&to=${period_to}&setting=Home&activityCondition=AtRest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json instanceof List && !json.empty : 'Seed observations first'
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Numerical insights" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/insights?from=${period_from}&to=${period_to}&setting=Home&activityCondition=AtRest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.contributingCount > 0
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Trends" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/trends?from=${period_from}&to=${period_to}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
|
||||
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Health overview" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/overview?from=${period_from}&to=${period_to}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patient.patientId == vars.get('patient_id'); assert json.latestObservation != null; assert json.insight != null
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<TestAction guiclass="TestActionGui" testclass="TestAction" testname="Between-session pause" enabled="true">
|
||||
<intProp name="ActionProcessor.action">1</intProp>
|
||||
<intProp name="ActionProcessor.target">0</intProp>
|
||||
<stringProp name="ActionProcessor.duration">${session_delay_ms}</stringProp>
|
||||
</TestAction>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</jmeterTestPlan>
|
||||
@@ -0,0 +1,574 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: recording" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','1000')) - System.currentTimeMillis())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">vars.put('shelly_last_poll_ms',prev.getStartTime().toString())
|
||||
try {
|
||||
assert prev.getResponseCode() == '200'
|
||||
def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.output == true : 'Outlet is off'
|
||||
def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total]
|
||||
readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) }
|
||||
} catch (Throwable error) {
|
||||
AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<collectionProp name="metricConnections">
|
||||
<collectionProp name="0">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">combined</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="1">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">iowait</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="2">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">usedperc</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="3">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">actualused</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="4">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Swap</stringProp>
|
||||
<stringProp name="3">used</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="5">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">readbytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="6">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">writebytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="7">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytesrecv</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="8">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytessent</stringProp>
|
||||
</collectionProp>
|
||||
</collectionProp>
|
||||
</kg.apc.jmeter.perfmon.PerfMonCollector>
|
||||
<hashTree />
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="JSON and bearer token" enabled="true">
|
||||
<collectionProp name="HeaderManager.headers">
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Content-Type</stringProp>
|
||||
<stringProp name="Header.value">application/json</stringProp>
|
||||
</elementProp>
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Authorization</stringProp>
|
||||
<stringProp name="Header.value">Bearer ${token}</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</HeaderManager>
|
||||
<hashTree />
|
||||
<OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Assign one account per user" enabled="true" />
|
||||
<hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Initialize user" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rows = new File(props.get('users_file')).readLines('UTF-8').drop(1).findAll { it.trim() }
|
||||
def row = rows[ctx.getThreadNum()].split(',', -1)
|
||||
vars.put('account_id', row[0]); vars.put('password', row[1]); vars.put('patient_id', row[2])
|
||||
vars.put('token', ''); vars.put('expires_at', '0'); vars.put('session_number','0')
|
||||
vars.putObject('user_random', new Random(Long.parseLong(props.getProperty('random_seed','42')) + ctx.getThreadNum()))
|
||||
synchronized(props) {
|
||||
if (props.get('timeline_file') && !props.get('workload_start_ms')) {
|
||||
long start = System.currentTimeMillis()
|
||||
long measurement = start + Long.parseLong(props.getProperty('warmup_seconds','1800')) * 1000
|
||||
long end = measurement + Long.parseLong(props.getProperty('duration_seconds','14400')) * 1000
|
||||
props.put('workload_start_ms',start.toString())
|
||||
new File(props.get('timeline_file')).text = groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
||||
}
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Prepare session" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def now = java.time.Instant.now()
|
||||
vars.put('refresh_login', (now.epochSecond >= Long.parseLong(vars.get('expires_at')) - 60).toString())
|
||||
vars.put('login_body',groovy.json.JsonOutput.toJson([accountId:vars.get('account_id'),password:vars.get('password')]))
|
||||
vars.put('period_from',props.get('period_from')); vars.put('period_to',props.get('period_to'))
|
||||
int n = Integer.parseInt(vars.get('session_number')); vars.put('session_number',(n+1).toString())
|
||||
// Random session mix: expected 65% review, 30% recording, 5% correction.
|
||||
int slot = vars.getObject('user_random').nextInt(20)
|
||||
vars.put('session_kind',slot < 13 ? 'review' : slot < 19 ? 'recording' : 'correction')
|
||||
double mean = Double.parseDouble(props.getProperty('session_pause_ms','120000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('session_stddev_ms','30000'))
|
||||
vars.put('session_delay_ms',Math.max(0L,Math.round(mean + vars.getObject('user_random').nextGaussian()*deviation)).toString())
|
||||
vars.put('observation_body',groovy.json.JsonOutput.toJson([measuredAt:now.toString(),systolic:128+(n%7),diastolic:82+(n%4),pulse:68+(n%6),measurementContext:[setting:'Home',activityCondition:'AtRest',restDurationMinutes:5,bodyPosition:'Seated'],note:'Synthetic JMeter energy workload']))
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
<IfController guiclass="IfControllerPanel" testclass="IfController" testname="Login or renew expired token" enabled="true">
|
||||
<stringProp name="IfController.condition">${refresh_login}</stringProp>
|
||||
<boolProp name="IfController.evaluateAll">false</boolProp>
|
||||
<boolProp name="IfController.useExpression">true</boolProp>
|
||||
</IfController>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Login" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments">
|
||||
<elementProp name="" elementType="HTTPArgument">
|
||||
<boolProp name="HTTPArgument.always_encode">false</boolProp>
|
||||
<stringProp name="Argument.value">${login_body}</stringProp>
|
||||
<stringProp name="Argument.metadata">=</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/authentication/login</stringProp>
|
||||
<stringProp name="HTTPSampler.method">POST</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.accessToken; vars.put('token',json.accessToken); vars.put('expires_at',(java.time.Instant.now().epochSecond + (json.expiresIn as long)).toString())
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Measurement guidance" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/measurement-guidance?setting=Home&activityCondition=AtRest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
|
||||
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Read own profile" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/me</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Record synthetic measurement" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments">
|
||||
<elementProp name="" elementType="HTTPArgument">
|
||||
<boolProp name="HTTPArgument.always_encode">false</boolProp>
|
||||
<stringProp name="Argument.value">${observation_body}</stringProp>
|
||||
<stringProp name="Argument.metadata">=</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/observations</stringProp>
|
||||
<stringProp name="HTTPSampler.method">POST</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '201') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id'); assert json.observationId; vars.put('observation_id',json.observationId)
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Confirm saved reading" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/observations/${observation_id}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.observationId == vars.get('observation_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Health overview" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/overview?from=${period_from}&to=${period_to}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patient.patientId == vars.get('patient_id'); assert json.latestObservation != null; assert json.insight != null
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<TestAction guiclass="TestActionGui" testclass="TestAction" testname="Between-session pause" enabled="true">
|
||||
<intProp name="ActionProcessor.action">1</intProp>
|
||||
<intProp name="ActionProcessor.target">0</intProp>
|
||||
<stringProp name="ActionProcessor.duration">${session_delay_ms}</stringProp>
|
||||
</TestAction>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</jmeterTestPlan>
|
||||
@@ -0,0 +1,623 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: review" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','1000')) - System.currentTimeMillis())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">vars.put('shelly_last_poll_ms',prev.getStartTime().toString())
|
||||
try {
|
||||
assert prev.getResponseCode() == '200'
|
||||
def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.output == true : 'Outlet is off'
|
||||
def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total]
|
||||
readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) }
|
||||
} catch (Throwable error) {
|
||||
AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<collectionProp name="metricConnections">
|
||||
<collectionProp name="0">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">combined</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="1">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">CPU</stringProp>
|
||||
<stringProp name="3">iowait</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="2">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">usedperc</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="3">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Memory</stringProp>
|
||||
<stringProp name="3">actualused</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="4">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Swap</stringProp>
|
||||
<stringProp name="3">used</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="5">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">readbytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="6">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Disks I/O</stringProp>
|
||||
<stringProp name="3">writebytes</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="7">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytesrecv</stringProp>
|
||||
</collectionProp>
|
||||
<collectionProp name="8">
|
||||
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
|
||||
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
|
||||
<stringProp name="2">Network I/O</stringProp>
|
||||
<stringProp name="3">bytessent</stringProp>
|
||||
</collectionProp>
|
||||
</collectionProp>
|
||||
</kg.apc.jmeter.perfmon.PerfMonCollector>
|
||||
<hashTree />
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="JSON and bearer token" enabled="true">
|
||||
<collectionProp name="HeaderManager.headers">
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Content-Type</stringProp>
|
||||
<stringProp name="Header.value">application/json</stringProp>
|
||||
</elementProp>
|
||||
<elementProp name="" elementType="Header">
|
||||
<stringProp name="Header.name">Authorization</stringProp>
|
||||
<stringProp name="Header.value">Bearer ${token}</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</HeaderManager>
|
||||
<hashTree />
|
||||
<OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Assign one account per user" enabled="true" />
|
||||
<hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Initialize user" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rows = new File(props.get('users_file')).readLines('UTF-8').drop(1).findAll { it.trim() }
|
||||
def row = rows[ctx.getThreadNum()].split(',', -1)
|
||||
vars.put('account_id', row[0]); vars.put('password', row[1]); vars.put('patient_id', row[2])
|
||||
vars.put('token', ''); vars.put('expires_at', '0'); vars.put('session_number','0')
|
||||
vars.putObject('user_random', new Random(Long.parseLong(props.getProperty('random_seed','42')) + ctx.getThreadNum()))
|
||||
synchronized(props) {
|
||||
if (props.get('timeline_file') && !props.get('workload_start_ms')) {
|
||||
long start = System.currentTimeMillis()
|
||||
long measurement = start + Long.parseLong(props.getProperty('warmup_seconds','1800')) * 1000
|
||||
long end = measurement + Long.parseLong(props.getProperty('duration_seconds','14400')) * 1000
|
||||
props.put('workload_start_ms',start.toString())
|
||||
new File(props.get('timeline_file')).text = groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
||||
}
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Prepare session" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def now = java.time.Instant.now()
|
||||
vars.put('refresh_login', (now.epochSecond >= Long.parseLong(vars.get('expires_at')) - 60).toString())
|
||||
vars.put('login_body',groovy.json.JsonOutput.toJson([accountId:vars.get('account_id'),password:vars.get('password')]))
|
||||
vars.put('period_from',props.get('period_from')); vars.put('period_to',props.get('period_to'))
|
||||
int n = Integer.parseInt(vars.get('session_number')); vars.put('session_number',(n+1).toString())
|
||||
// Random session mix: expected 65% review, 30% recording, 5% correction.
|
||||
int slot = vars.getObject('user_random').nextInt(20)
|
||||
vars.put('session_kind',slot < 13 ? 'review' : slot < 19 ? 'recording' : 'correction')
|
||||
double mean = Double.parseDouble(props.getProperty('session_pause_ms','120000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('session_stddev_ms','30000'))
|
||||
vars.put('session_delay_ms',Math.max(0L,Math.round(mean + vars.getObject('user_random').nextGaussian()*deviation)).toString())
|
||||
vars.put('observation_body',groovy.json.JsonOutput.toJson([measuredAt:now.toString(),systolic:128+(n%7),diastolic:82+(n%4),pulse:68+(n%6),measurementContext:[setting:'Home',activityCondition:'AtRest',restDurationMinutes:5,bodyPosition:'Seated'],note:'Synthetic JMeter energy workload']))
|
||||
</stringProp>
|
||||
</JSR223Sampler>
|
||||
<hashTree />
|
||||
<IfController guiclass="IfControllerPanel" testclass="IfController" testname="Login or renew expired token" enabled="true">
|
||||
<stringProp name="IfController.condition">${refresh_login}</stringProp>
|
||||
<boolProp name="IfController.evaluateAll">false</boolProp>
|
||||
<boolProp name="IfController.useExpression">true</boolProp>
|
||||
</IfController>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Login" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments">
|
||||
<elementProp name="" elementType="HTTPArgument">
|
||||
<boolProp name="HTTPArgument.always_encode">false</boolProp>
|
||||
<stringProp name="Argument.value">${login_body}</stringProp>
|
||||
<stringProp name="Argument.metadata">=</stringProp>
|
||||
</elementProp>
|
||||
</collectionProp>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/authentication/login</stringProp>
|
||||
<stringProp name="HTTPSampler.method">POST</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.accessToken; vars.put('token',json.accessToken); vars.put('expires_at',(java.time.Instant.now().epochSecond + (json.expiresIn as long)).toString())
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Read profile" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/me</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Latest reading" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/observations/latest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patientId == vars.get('patient_id')
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Home resting history" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/observations?from=${period_from}&to=${period_to}&setting=Home&activityCondition=AtRest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json instanceof List && !json.empty : 'Seed observations first'
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Numerical insights" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/insights?from=${period_from}&to=${period_to}&setting=Home&activityCondition=AtRest</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.contributingCount > 0
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Trends" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/trends?from=${period_from}&to=${period_to}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
|
||||
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Health overview" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(host,127.0.0.1)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(port,5443)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">https</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/patients/${patient_id}/overview?from=${period_from}&to=${period_to}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">10000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">30000</stringProp>
|
||||
<boolProp name="HTTPSampler.postBodyRaw">false</boolProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Expected response" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">if (prev.getResponseCode() != '200') {
|
||||
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
||||
}
|
||||
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
||||
prev.setSuccessful(true)
|
||||
def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
||||
assert json.patient.patientId == vars.get('patient_id'); assert json.latestObservation != null; assert json.insight != null
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Gaussian interaction pause" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">def rng = vars.getObject('user_random')
|
||||
double mean = Double.parseDouble(props.getProperty('think_mean_ms','1000'))
|
||||
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','250'))
|
||||
double minimum = Double.parseDouble(props.getProperty('think_min_ms','500'))
|
||||
// Symmetric truncation keeps the expected mean at the configured value.
|
||||
double maximum = 2 * mean - minimum
|
||||
if (deviation == 0 || maximum == minimum) return Math.round(mean)
|
||||
double delay
|
||||
while (true) {
|
||||
delay = mean + rng.nextGaussian() * deviation
|
||||
if (delay >= minimum && delay <= maximum) return Math.round(delay)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<TestAction guiclass="TestActionGui" testclass="TestAction" testname="Between-session pause" enabled="true">
|
||||
<intProp name="ActionProcessor.action">1</intProp>
|
||||
<intProp name="ActionProcessor.target">0</intProp>
|
||||
<stringProp name="ActionProcessor.duration">${session_delay_ms}</stringProp>
|
||||
</TestAction>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</jmeterTestPlan>
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare synthetic profiles/history outside the measurement window."""
|
||||
import argparse, csv, datetime as dt, json, os, ssl, urllib.request, urllib.error
|
||||
from tls import application_context
|
||||
from pathlib import Path
|
||||
p=argparse.ArgumentParser()
|
||||
p.add_argument('--base-url', required=True); p.add_argument('--ca', required=True)
|
||||
p.add_argument('--accounts', required=True, help='Private JSON: AccountId, Password, Role')
|
||||
p.add_argument('--output', required=True); p.add_argument('--days', type=int, default=30)
|
||||
a=p.parse_args()
|
||||
if not a.base_url.startswith('https://'): p.error('HTTPS is required')
|
||||
if not 2 <= a.days <= 365: p.error('days must be 2..365')
|
||||
context=application_context(cafile=a.ca)
|
||||
def call(method,path,body=None,token=None):
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token: headers['Authorization']='Bearer '+token
|
||||
req=urllib.request.Request(a.base_url.rstrip('/')+path, data=json.dumps(body).encode() if body is not None else None, headers=headers,method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req,context=context,timeout=60) as r: return r.status,json.load(r)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code==404: return 404,None
|
||||
raise RuntimeError(f'{method} {path}: HTTP {e.code}') from None
|
||||
out=Path(a.output)
|
||||
out.mkdir(mode=0o700,parents=True,exist_ok=True); os.chmod(out,0o700)
|
||||
if (out/'users.csv').exists(): p.error('Output users.csv already exists; use a new directory')
|
||||
rows=[]
|
||||
for account in json.loads(Path(a.accounts).read_text()):
|
||||
if account['Role']!='Patient' or account['AccountId']=='installation-check': continue
|
||||
_,login=call('POST','/api/authentication/login',{'accountId':account['AccountId'],'password':account['Password']})
|
||||
token=login['accessToken']
|
||||
status,profile=call('GET','/api/patients/me',token=token)
|
||||
if status==404:
|
||||
_,profile=call('POST','/api/patients',{'name':'Synthetic energy test '+account['AccountId'],'dateOfBirth':'1990-01-01','contactInfo':'energy@example.test'},token)
|
||||
pid=profile['patientId']
|
||||
now=dt.datetime.now(dt.timezone.utc)
|
||||
# Seed only absent exact synthetic timestamps; rerunning does not duplicate baseline rows.
|
||||
start=(now-dt.timedelta(days=a.days)).replace(hour=0,minute=0,second=0,microsecond=0)
|
||||
_,existing=call('GET',f'/api/patients/{pid}/observations?from={start.isoformat().replace("+00:00","Z")}&to={now.isoformat().replace("+00:00","Z")}',token=token)
|
||||
times={o['measuredAt'].rstrip('Z') for o in existing}
|
||||
for day in range(a.days):
|
||||
for hour in [8,18]:
|
||||
instant=(start+dt.timedelta(days=day,hours=hour)).isoformat().replace('+00:00','Z')
|
||||
if instant.rstrip('Z') in times: continue
|
||||
call('POST',f'/api/patients/{pid}/observations',{'measuredAt':instant,'systolic':122+day%12,'diastolic':76+day%8,'pulse':62+day%10,'measurementContext':{'setting':'Clinic' if day%10==0 else 'Unknown' if day%10==1 else 'Home','activityCondition':'AfterActivity' if day%10==2 else 'Unknown' if day%10==1 else 'AtRest','restDurationMinutes':None if day%10 in [1,2] else 5,'bodyPosition':None if day%10==1 else 'Seated'},'note':'Synthetic energy baseline'},token)
|
||||
rows.append([account['AccountId'],account['Password'],pid])
|
||||
print('Prepared synthetic patient:',account['AccountId'])
|
||||
with (out/'users.csv').open('x') as f:
|
||||
os.chmod(f.name,0o600); w=csv.writer(f);w.writerow(['account_id','password','patient_id']);w.writerows(rows)
|
||||
if not rows: raise SystemExit('No patient accounts supplied')
|
||||
print(f'Prepared {len(rows)} patients; private CSV: {out / "users.csv"}')
|
||||
@@ -0,0 +1,25 @@
|
||||
<!doctype html><html lang="en"><meta charset="utf-8"><title>HealthApp measurement report</title>
|
||||
<style>body{font:15px system-ui;margin:24px;background:#f6f8fb;color:#182230}header,section{background:white;padding:18px;margin-bottom:16px;border-radius:8px}canvas{width:100%;height:210px}h2{font-size:16px;margin:0 0 8px}.controls{position:sticky;top:0;background:white;padding:12px;z-index:2;border-bottom:1px solid #ccc}input{width:220px}#cursor{font-family:monospace}small{color:#485566}</style>
|
||||
<header><h1>HealthApp — one-second measurements</h1><p id="status"></p><p id="window"></p><small>All panels share the same UTC timeline. Grey shading marks warmup. Missing measurements are gaps, never zero-filled. Latency is grouped by request start time; intervals with no requests have no latency value. Counter values are the plug’s absolute Wh counter.</small></header>
|
||||
<div class="controls"><button onclick="location.reload()">Refresh snapshot</button> <button id="all">Include warmup</button> <button id="measured">Measured window</button> <label>From second <input id="from" type="number" min="0"></label> <label>To second <input id="to" type="number" min="1"></label><p id="cursor">Move over any graph to inspect the same second across all panels.</p></div><main id="charts"></main>
|
||||
<script type="application/json" id="data">PAYLOAD_JSON</script><script>
|
||||
const data=JSON.parse(document.getElementById('data').textContent),rows=data.rows,fields=data.fields,idx=Object.fromEntries(fields.map((f,i)=>[f,i]));
|
||||
const panels=[['CPU (%)',['cpu_percent','cpu_iowait_percent']],['RAM (%)',['ram_percent']],['RAM / swap (MiB)',['ram_MiB','swap_MiB']],['Power (W)',['power_watts']],['Application requests / errors per second',['requests_s','errors_s']],['Application latency (ms)',['latency_mean_ms','latency_p95_ms','latency_max_ms']],['Disk / network (KiB/s)',['disk_read_KiB_s','disk_write_KiB_s','network_receive_KiB_s','network_send_KiB_s']],['Plug counter (Wh)',['energy_counter_Wh']]];
|
||||
const colors=['#176bc1','#dc5a18','#379d55','#9450bd'];let lo=0,hi=rows.length-1,selected=null;
|
||||
const date=t=>new Date(t).toISOString();document.getElementById('status').textContent=`${data.scenario}: ${data.status}. ${rows.length} recorded one-second intervals.`;
|
||||
document.getElementById('window').textContent=`Measured window: ${date(data.timeline.measurement_start_ms)} — ${date(data.timeline.measurement_end_ms)}. All times UTC.`;
|
||||
document.getElementById('measured').disabled=rows[rows.length-1][0]<data.timeline.measurement_start_ms;
|
||||
const canvases=panels.map(([title,keys])=>{const s=document.createElement('section');s.innerHTML=`<h2>${title}</h2><canvas></canvas><small></small>`;document.getElementById('charts').append(s);return {canvas:s.querySelector('canvas'),legend:s.querySelector('small'),keys}});
|
||||
function draw(){for(const {canvas,legend,keys} of canvases){const rect=canvas.getBoundingClientRect(),dpr=window.devicePixelRatio||1;canvas.width=rect.width*dpr;canvas.height=210*dpr;const c=canvas.getContext('2d');c.scale(dpr,dpr);const w=rect.width,h=210,left=55,right=w-15,top=12,bottom=h-32;
|
||||
const x=i=>left+(right-left)*(i-lo)/Math.max(1,hi-lo);let max=1;for(let i=lo;i<=hi;i++)for(const k of keys){const v=rows[i][idx[k]];if(v!==null)max=Math.max(max,v)}max*=1.08;const y=v=>bottom-(bottom-top)*v/max;
|
||||
const warmupIndex=(data.timeline.measurement_start_ms-rows[0][0])/1000;if(warmupIndex>lo){c.fillStyle='#e9ebee';c.fillRect(left,top,Math.max(0,Math.min(right,x(warmupIndex))-left),bottom-top)}
|
||||
c.font='11px system-ui';for(let j=0;j<=4;j++){const yy=bottom-j*(bottom-top)/4;c.strokeStyle='#e4e7ec';c.beginPath();c.moveTo(left,yy);c.lineTo(right,yy);c.stroke();c.fillStyle='#526070';c.fillText((max*j/4).toFixed(max<10?2:0),2,yy+3)}
|
||||
keys.forEach((k,n)=>{c.strokeStyle=colors[n];c.lineWidth=1.2;c.beginPath();let pen=false;for(let i=lo;i<=hi;i++){const v=rows[i][idx[k]];if(v===null){pen=false;continue}if(!pen)c.moveTo(x(i),y(v));else c.lineTo(x(i),y(v));pen=true}c.stroke()});
|
||||
c.fillStyle='#526070';for(let j=0;j<=3;j++){const i=Math.round(lo+(hi-lo)*j/3);c.fillText(date(rows[i][0]).slice(11,19),Math.max(left,Math.min(right-55,x(i)-22)),h-10)}
|
||||
if(selected!==null&&selected>=lo&&selected<=hi){c.strokeStyle='#182230';c.beginPath();c.moveTo(x(selected),top);c.lineTo(x(selected),bottom);c.stroke()}
|
||||
legend.innerHTML=keys.map((k,n)=>`<span style="color:${colors[n]}">${k}${selected===null?'':': '+(rows[selected][idx[k]]===null?'missing':rows[selected][idx[k]].toFixed(3))}</span>`).join(' · ');
|
||||
canvas.onmousemove=e=>{selected=Math.max(lo,Math.min(hi,Math.round(lo+(e.offsetX-left)/(right-left)*Math.max(1,hi-lo))));document.getElementById('cursor').textContent=`${date(rows[selected][0])} — ${rows[selected][idx.phase]}`;draw()};}}
|
||||
function limits(a,b){lo=Math.max(0,Math.min(rows.length-1,a));hi=Math.max(lo,Math.min(rows.length-1,b));selected=null;document.getElementById('from').value=lo;document.getElementById('to').value=hi;draw()}
|
||||
document.getElementById('all').onclick=()=>limits(0,rows.length-1);document.getElementById('measured').onclick=()=>limits(Math.floor((data.timeline.measurement_start_ms-rows[0][0])/1000),rows.length-1);
|
||||
for(const id of ['from','to'])document.getElementById(id).onchange=()=>limits(Number(document.getElementById('from').value),Number(document.getElementById('to').value));window.onresize=draw;limits(0,rows.length-1);
|
||||
</script></html>
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Align raw JMeter measurements into experiment-relative one-second bins."""
|
||||
import os,time
|
||||
import argparse,csv,datetime as dt,json,math
|
||||
from pathlib import Path
|
||||
FIELDS=['timestamp_ms','phase','cpu_percent','cpu_iowait_percent','ram_percent','ram_MiB','swap_MiB','power_watts','energy_counter_Wh','disk_read_KiB_s','disk_write_KiB_s','network_receive_KiB_s','network_send_KiB_s','requests_s','errors_s','error_percent','latency_mean_ms','latency_p95_ms','latency_max_ms','power_poll_errors_s']
|
||||
METRIC_FIELDS={'CPU combined':('cpu_percent',1),'CPU iowait':('cpu_iowait_percent',1),'Memory usedperc':('ram_percent',1),'Memory actualused':('ram_MiB',1/1048576),'Swap used':('swap_MiB',1/1048576),'Disks I/O readbytes':('disk_read_KiB_s',1/1024),'Disks I/O writebytes':('disk_write_KiB_s',1/1024),'Network I/O bytesrecv':('network_receive_KiB_s',1/1024),'Network I/O bytessent':('network_send_KiB_s',1/1024)}
|
||||
def read_csv(path):
|
||||
if not path.exists():return []
|
||||
with path.open(newline='') as f:
|
||||
# Autoflush can expose the final line during a write; ignore incomplete rows.
|
||||
return [r for r in csv.DictReader(f) if r and None not in r and all(v is not None for v in r.values())]
|
||||
def finished(meta):
|
||||
return ('finished_utc' in meta
|
||||
and (not meta.get('perfmon',{}).get('enabled') or 'server_metrics' in meta or 'monitoring_error' in meta)
|
||||
and (not meta.get('shelly',{}).get('enabled') or 'power_energy' in meta or 'power_error' in meta))
|
||||
def build(folder):
|
||||
folder=Path(folder);meta=json.loads((folder/'run.json').read_text());timeline=json.loads((folder/'timeline.json').read_text())
|
||||
start=timeline['warmup_start_ms'];measurement_start=timeline['measurement_start_ms'];end=timeline['measurement_end_ms']
|
||||
bins={};latest=start;bad_rows=0
|
||||
def bucket(timestamp):
|
||||
nonlocal latest
|
||||
if not start<=timestamp<end:return None
|
||||
index=int((timestamp-start)//1000);latest=max(latest,timestamp)
|
||||
return bins.setdefault(index,{'averages':{},'latencies':[],'requests_s':0,'errors_s':0,'power_poll_errors_s':0})
|
||||
def reading(timestamp,field,value):
|
||||
row=bucket(timestamp)
|
||||
if row is not None and math.isfinite(value):row['averages'].setdefault(field,[]).append(value)
|
||||
for r in read_csv(folder/'perfmon.csv'):
|
||||
try:
|
||||
if r.get('success','true').lower()!='true':continue
|
||||
timestamp=float(r['timeStamp']);value=float(r['elapsed'])/1000
|
||||
if value<0:continue
|
||||
for suffix,(field,scale) in METRIC_FIELDS.items():
|
||||
if r['label'].endswith(' '+suffix):reading(timestamp,field,value*scale);break
|
||||
except (ValueError,KeyError,TypeError):bad_rows+=1
|
||||
for r in read_csv(folder/'shelly.csv'):
|
||||
try:
|
||||
timestamp=float(r['timeStamp'])+float(r['elapsed'])/2
|
||||
row=bucket(timestamp)
|
||||
if r['success'].lower()!='true':
|
||||
if row is not None:row['power_poll_errors_s']+=1
|
||||
continue
|
||||
reading(timestamp,'power_watts',float(r['shelly_power_watts']))
|
||||
reading(timestamp,'energy_counter_Wh',float(r['shelly_energy_wh']))
|
||||
except (ValueError,KeyError,TypeError):bad_rows+=1
|
||||
for r in read_csv(folder/'samples.csv'):
|
||||
try:
|
||||
if not r['label'].startswith('HTTP '):continue
|
||||
row=bucket(float(r['timeStamp']))
|
||||
if row is None:continue
|
||||
if float(r['timeStamp'])>=measurement_start and float(r['timeStamp'])+float(r['elapsed'])>end:continue
|
||||
row['requests_s']+=1;row['errors_s']+=r['success'].lower()!='true';row['latencies'].append(float(r['elapsed']))
|
||||
except (ValueError,KeyError,TypeError):bad_rows+=1
|
||||
completed=finished(meta)
|
||||
if completed:
|
||||
finish=int(dt.datetime.fromisoformat(meta['finished_utc']).timestamp()*1000)
|
||||
observed_end=min(end,finish)
|
||||
else:observed_end=min(end,int(latest)+1)
|
||||
count=max(1,math.ceil((observed_end-start)/1000));rows=[]
|
||||
for index in range(count):
|
||||
timestamp=start+index*1000;source=bins.get(index,{'averages':{},'latencies':[],'requests_s':0,'errors_s':0,'power_poll_errors_s':0})
|
||||
row={field:None for field in FIELDS};row.update(timestamp_ms=timestamp,phase='warmup' if timestamp<measurement_start else 'measurement')
|
||||
for field,values in source['averages'].items():row[field]=sum(values)/len(values)
|
||||
for field in ['requests_s','errors_s','power_poll_errors_s']:row[field]=source[field]
|
||||
latencies=sorted(source['latencies'])
|
||||
if latencies:
|
||||
row.update(error_percent=100*source['errors_s']/len(latencies),latency_mean_ms=sum(latencies)/len(latencies),latency_p95_ms=latencies[max(0,math.ceil(.95*len(latencies))-1)],latency_max_ms=max(latencies))
|
||||
rows.append(row)
|
||||
with (folder/'per-second.csv').open('w') as f:
|
||||
w=csv.DictWriter(f,fieldnames=FIELDS);w.writeheader();w.writerows(rows)
|
||||
payload={'fields':FIELDS,'rows':[[r[k] for k in FIELDS] for r in rows],'timeline':timeline,'status':'completed' if meta.get('exit_code')==0 else 'incomplete/failed' if completed else 'running — snapshot','scenario':meta['scenario'],'skipped_rows':bad_rows,'interval_ms':1000}
|
||||
encoded=json.dumps(payload,separators=(',',':'),allow_nan=False).replace('<','\\u003c')
|
||||
template=(Path(__file__).parent/'report-template.html').read_text()
|
||||
(folder/'report.html').write_text(template.replace('PAYLOAD_JSON',encoded))
|
||||
plot(rows,timeline,folder,payload['status'])
|
||||
print(f'Report saved: {folder / "report.html"}; {count} one-second intervals; {payload["status"]}')
|
||||
return rows
|
||||
PANELS=[('CPU utilisation (%)',['cpu_percent','cpu_iowait_percent']),('RAM usage (%)',['ram_percent']),('RAM / swap (MiB)',['ram_MiB','swap_MiB']),('Power (W)',['power_watts']),('Application requests / errors per second',['requests_s','errors_s']),('Application latency (ms)',['latency_mean_ms','latency_p95_ms','latency_max_ms']),('Disk / network (KiB/s)',['disk_read_KiB_s','disk_write_KiB_s','network_receive_KiB_s','network_send_KiB_s']),('Plug energy counter (Wh)',['energy_counter_Wh'])]
|
||||
def plot(rows,timeline,folder,status):
|
||||
os.environ.setdefault('MPLCONFIGDIR',str(folder/'.matplotlib'))
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.dates as mdates
|
||||
times=[dt.datetime.fromtimestamp(r['timestamp_ms']/1000,dt.timezone.utc) for r in rows]
|
||||
warmup_end=dt.datetime.fromtimestamp(timeline['measurement_start_ms']/1000,dt.timezone.utc)
|
||||
finish=dt.datetime.fromtimestamp(timeline['measurement_end_ms']/1000,dt.timezone.utc)
|
||||
figure,axes=plt.subplots(len(PANELS),1,sharex=True,figsize=(16,19),layout='constrained')
|
||||
for ax,(title,fields) in zip(axes,PANELS):
|
||||
for field in fields:ax.plot(times,[float('nan') if r[field] is None else r[field] for r in rows],label=field,linewidth=.8)
|
||||
ax.set_ylabel(title);ax.grid(alpha=.2);ax.legend(loc='upper right',fontsize=7)
|
||||
if times[0]<warmup_end:ax.axvspan(times[0],min(warmup_end,times[-1]),color='gray',alpha=.15)
|
||||
if times[0]<=warmup_end<=times[-1]:ax.axvline(warmup_end,color='black',linestyle='--',linewidth=.8)
|
||||
ax.set_ylim(bottom=0)
|
||||
if fields[0]=='requests_s' and not any(r['requests_s'] for r in rows):
|
||||
ax.set_ylim(-.05,1);ax.text(.5,.5,'Zero application requests',transform=ax.transAxes,ha='center')
|
||||
if fields[0]=='latency_mean_ms' and all(r['latency_mean_ms'] is None for r in rows):
|
||||
ax.set_ylim(0,1);ax.text(.5,.5,'No requests: response time unavailable',transform=ax.transAxes,ha='center')
|
||||
axes[-1].xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S',tz=dt.timezone.utc))
|
||||
axes[-1].set_xlabel('UTC time — experiment-relative one-second bins; shaded area is warmup')
|
||||
figure.suptitle('HealthApp measurements — '+status+'\nMeasured window: '+warmup_end.isoformat()+' to '+finish.isoformat(),fontsize=13)
|
||||
figure.savefig(folder/'report.png',dpi=150);figure.savefig(folder/'report.svg');plt.close(figure)
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser();parser.add_argument('run_folder');parser.add_argument('--follow',action='store_true');args=parser.parse_args()
|
||||
while True:
|
||||
build(args.run_folder)
|
||||
if not args.follow or finished(json.loads((Path(args.run_folder)/'run.json').read_text())):break
|
||||
time.sleep(60)
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||
run_id=$(date -u +%Y%m%dT%H%M%SZ)
|
||||
exec python3 "$script_dir/run.py" idle \
|
||||
--host "${HEALTHAPP_HOST:-192.168.1.125}" \
|
||||
--shelly-host "${SHELLY_HOST:-192.168.1.44}" \
|
||||
--warmup 1800 --duration 14400 \
|
||||
--perfmon-interval-ms 1000 --shelly-interval-ms 1000 \
|
||||
--output "$script_dir/results/idle-$run_id" "$@"
|
||||
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Preflight and run JMeter; record actual timing for external power measurements."""
|
||||
import xml.etree.ElementTree as E
|
||||
import argparse, csv, datetime as dt, hashlib, json, os, platform, subprocess, time, ssl, urllib.request
|
||||
from tls import application_context
|
||||
from pathlib import Path
|
||||
from perfmon import check_agent, summarize
|
||||
import shelly
|
||||
HERE=Path(__file__).resolve().parent
|
||||
p=argparse.ArgumentParser()
|
||||
p.add_argument('scenario',choices=['recording','review','correction','professional','mixed','idle'])
|
||||
p.add_argument('--host',required=True);p.add_argument('--port',type=int,default=5443)
|
||||
p.add_argument('--ca');p.add_argument('--users-file');p.add_argument('--users',type=int,default=50)
|
||||
p.add_argument('--warmup',type=int,default=1800);p.add_argument('--duration',type=int,default=14400);p.add_argument('--ramp',type=int,default=120)
|
||||
p.add_argument('--think-min-ms',type=int,default=500);p.add_argument('--think-mean-ms',type=int,default=1000);p.add_argument('--think-stddev-ms',type=int,default=250)
|
||||
p.add_argument('--session-pause-ms',type=int,default=120000)
|
||||
p.add_argument('--session-stddev-ms',type=int,default=30000);p.add_argument('--seed',type=int,default=42)
|
||||
p.add_argument('--output',required=True);p.add_argument('--jmeter',default=str(Path.home()/'.local/bin/jmeter'))
|
||||
p.add_argument('--allow-shared-read-account',action='store_true')
|
||||
p.add_argument('--capacity-trial',action='store_true',help='Read-only trial: restart a session after an error so the configured duration is retained')
|
||||
p.add_argument('--perfmon-host');p.add_argument('--perfmon-port',type=int,default=4444)
|
||||
p.add_argument('--perfmon-interval-ms',type=int,default=1000);p.add_argument('--no-perfmon',action='store_true')
|
||||
p.add_argument('--shelly-host',default='192.168.1.44');p.add_argument('--shelly-port',type=int,default=80)
|
||||
p.add_argument('--shelly-switch-id',type=int,default=0);p.add_argument('--shelly-interval-ms',type=int,default=1000);p.add_argument('--no-shelly',action='store_true')
|
||||
a=p.parse_args()
|
||||
if a.capacity_trial and a.scenario not in ['review','professional']:p.error('Capacity trial is restricted to read-only workloads')
|
||||
if a.users<1 or a.duration<1 or a.warmup<0 or a.ramp<0 or min(a.think_min_ms,a.think_mean_ms,a.think_stddev_ms,a.session_pause_ms,a.session_stddev_ms)<0: p.error('Invalid timing/concurrency')
|
||||
if a.think_mean_ms<a.think_min_ms:p.error('Think-time mean must be at least the minimum')
|
||||
if a.scenario!='idle' and not a.users_file: p.error('--users-file is required')
|
||||
if a.scenario!='idle' and not a.ca: p.error('--ca is required for application scenarios')
|
||||
if a.scenario=='idle' and a.users_file:p.error('Idle does not use accounts; omit --users-file')
|
||||
if a.perfmon_interval_ms<1000 or a.perfmon_interval_ms%1000: p.error('PerfMon interval must be a whole number of seconds, at least 1000 ms')
|
||||
agent_host=a.perfmon_host or a.host
|
||||
if not a.no_perfmon: check_agent(agent_host,a.perfmon_port)
|
||||
if a.shelly_interval_ms<1000 or a.shelly_switch_id<0:p.error('Invalid Shelly interval/switch ID')
|
||||
shelly_info=None if a.no_shelly else shelly.check_plug(a.shelly_host,a.shelly_port,a.shelly_switch_id)
|
||||
rows=[]
|
||||
if a.users_file:
|
||||
with open(a.users_file,newline='') as f:
|
||||
reader=csv.DictReader(f)
|
||||
if reader.fieldnames!=['account_id','password','patient_id']: p.error('CSV columns must be account_id,password,patient_id')
|
||||
rows=list(reader)
|
||||
if not rows or any(not all(r.values()) or any(c in v for v in r.values() for c in ',\n\r"') for r in rows): p.error('CSV contains empty or unsupported values')
|
||||
if len({r['account_id'] for r in rows})!=len(rows): p.error('CSV must contain distinct accounts')
|
||||
if len(rows)<a.users:
|
||||
if not a.allow_shared_read_account or a.scenario not in ['review','professional']: p.error('Provide at least one distinct account per user. Shared accounts are allowed only for explicitly labelled read-only runs.')
|
||||
rows=(rows*((a.users+len(rows)-1)//len(rows)))[:a.users]
|
||||
if a.scenario!='idle':
|
||||
context=application_context(cafile=a.ca)
|
||||
with urllib.request.urlopen(f'https://{a.host}:{a.port}/api/measurement-guidance',context=context,timeout=15) as r:
|
||||
if r.status!=200: p.error('Application preflight failed')
|
||||
# Fail before a long run if accounts, profiles, baseline data or assignments are missing.
|
||||
def get(path,token=None,body=None):
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token: headers['Authorization']='Bearer '+token
|
||||
req=urllib.request.Request(f'https://{a.host}:{a.port}'+path,headers=headers,data=json.dumps(body).encode() if body else None)
|
||||
with urllib.request.urlopen(req,context=context,timeout=60) as r: return json.load(r)
|
||||
now=dt.datetime.now(dt.timezone.utc)
|
||||
period_from=(now-dt.timedelta(days=31)).replace(hour=0,minute=0,second=0,microsecond=0).isoformat().replace('+00:00','Z')
|
||||
period_to=(now+dt.timedelta(seconds=a.warmup+a.duration+3600)).isoformat().replace('+00:00','Z')
|
||||
for row in {r['account_id']:r for r in rows}.values():
|
||||
login=get('/api/authentication/login',body={'accountId':row['account_id'],'password':row['password']});token=login['accessToken']
|
||||
if a.scenario=='professional':
|
||||
if login['role']!='HealthcareProfessional' or not any(x['patientId']==row['patient_id'] for x in get('/api/professionals/me/patients',token)): p.error('Professional account lacks the required assignment')
|
||||
elif get('/api/patients/me',token)['patientId']!=row['patient_id']: p.error('CSV patient does not belong to its account')
|
||||
overview=get('/api/patients/'+row['patient_id']+'/overview?from='+period_from+'&to='+period_to,token)
|
||||
if overview['insight'] is None or overview['latestObservation'] is None: p.error('Seed patient history before running')
|
||||
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
|
||||
metadata={'architecture':'B','scenario':a.scenario,'users':0 if a.scenario=='idle' else a.users,'measurement_duration_seconds':a.duration,'warmup_seconds':a.warmup,'ramp_seconds':0 if a.scenario=='idle' else a.ramp,'think_min_ms':a.think_min_ms,'think_max_ms':2*a.think_mean_ms-a.think_min_ms,'think_distribution':'symmetrically truncated Gaussian','think_mean_ms':a.think_mean_ms,'think_stddev_ms':a.think_stddev_ms,'session_pause_ms':a.session_pause_ms,'session_stddev_ms':a.session_stddev_ms,'random_seed':a.seed,'host':a.host,'port':a.port,'period_from':period_from,'period_to':period_to,'load_generator':platform.platform(),'distinct_accounts':len({r['account_id'] for r in rows}),'login':'none; no application requests' if a.scenario=='idle' else 'initial login and renewal before expiry included','energy':'Shelly status polled live by JMeter; calculations exclude warmup'}
|
||||
runtime_csv=out/'runtime-users.csv'
|
||||
with runtime_csv.open('x') as f:
|
||||
os.chmod(f.name,0o600); w=csv.DictWriter(f,fieldnames=['account_id','password','patient_id']);w.writeheader();w.writerows(rows)
|
||||
source_plan=HERE/'plans'/(a.scenario+'.jmx');metadata['plan_sha256']=hashlib.sha256(source_plan.read_bytes()).hexdigest()
|
||||
plan=out/'runtime.jmx'; document=E.parse(source_plan)
|
||||
for collector in document.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):
|
||||
collector.set('enabled','false' if a.no_perfmon else 'true')
|
||||
for group in document.iter('ThreadGroup'):
|
||||
if a.capacity_trial and group.get('testname')=='Users':
|
||||
for setting in group.findall('stringProp'):
|
||||
if setting.get('name')=='ThreadGroup.on_sample_error':setting.text='startnextloop'
|
||||
if group.get('testname')=='Shelly live power':group.set('enabled','false' if a.no_shelly else 'true')
|
||||
document.write(plan,encoding='utf-8',xml_declaration=True)
|
||||
drain_seconds=max(5,a.shelly_interval_ms//1000+5) if not a.no_shelly else 5
|
||||
total_duration_seconds=a.warmup+a.duration+drain_seconds
|
||||
cmd=[a.jmeter,'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jhost='+a.host,'-Jport='+str(a.port),'-Jusers_file='+str(runtime_csv),'-Jusers='+str(a.users),'-Jduration_seconds='+str(a.duration),'-Jwarmup_seconds='+str(a.warmup),'-Jtotal_duration_seconds='+str(total_duration_seconds),'-Jtimeline_file='+str(out/'timeline.json'),'-Jramp_seconds='+str(a.ramp),'-Jthink_min_ms='+str(a.think_min_ms),'-Jthink_mean_ms='+str(a.think_mean_ms),'-Jthink_stddev_ms='+str(a.think_stddev_ms),'-Jsession_pause_ms='+str(a.session_pause_ms),'-Jsession_stddev_ms='+str(a.session_stddev_ms),'-Jrandom_seed='+str(a.seed),'-Jperiod_from='+period_from,'-Jperiod_to='+period_to,'-Jjmeter.save.saveservice.autoflush=true','-Jjmeter.save.saveservice.output_format=csv','-Jjmeter.save.saveservice.print_field_names=true','-Jjmeter.save.saveservice.response_data=false','-Jjmeter.save.saveservice.samplerData=false','-Jjmeter.save.saveservice.requestHeaders=false','-Jjmeter.save.saveservice.responseHeaders=false']
|
||||
metadata['jmeter_version']=subprocess.check_output([a.jmeter,'--version'],text=True).strip()
|
||||
cmd += ['-Jperfmon_host='+agent_host,'-Jperfmon_port='+str(a.perfmon_port),'-Jperfmon_file='+str(out/'perfmon.csv'),'-JjmeterPlugin.perfmon.interval='+str(a.perfmon_interval_ms),'-JjmeterPlugin.perfmon.useUDP=false']
|
||||
cmd += ['-Jshelly_host='+a.shelly_host,'-Jshelly_port='+str(a.shelly_port),'-Jshelly_switch_id='+str(a.shelly_switch_id),'-Jshelly_interval_ms='+str(a.shelly_interval_ms),'-Jshelly_file='+str(out/'shelly.csv'),'-Jsample_variables='+','.join(shelly.VARIABLES)]
|
||||
metadata['capacity_trial']=a.capacity_trial
|
||||
metadata['error_policy']='restart session on error' if a.capacity_trial else 'stop user on error'
|
||||
metadata['shelly']={'enabled':not a.no_shelly,'host':a.shelly_host,'port':a.shelly_port,'switch_id':a.shelly_switch_id,'interval_ms':a.shelly_interval_ms,'device':shelly_info}
|
||||
metadata['perfmon']={'enabled':not a.no_perfmon,'host':agent_host,'port':a.perfmon_port,'interval_ms':a.perfmon_interval_ms}
|
||||
metadata['started_utc']=dt.datetime.now(dt.timezone.utc).isoformat(); started=time.monotonic()
|
||||
(out/'run.json').write_text(json.dumps(metadata,indent=2))
|
||||
print('Measurement workload starts:',metadata['started_utc'],flush=True)
|
||||
code=0
|
||||
try:
|
||||
code=subprocess.call(cmd)
|
||||
except KeyboardInterrupt: code=130
|
||||
finally:
|
||||
metadata['finished_utc']=dt.datetime.now(dt.timezone.utc).isoformat();metadata['actual_elapsed_seconds']=time.monotonic()-started;metadata['exit_code']=code
|
||||
(out/'run.json').write_text(json.dumps(metadata,indent=2))
|
||||
runtime_csv.unlink(missing_ok=True)
|
||||
if (out/'timeline.json').exists():
|
||||
timeline=json.loads((out/'timeline.json').read_text());metadata.update(timeline)
|
||||
for name in ['warmup_start','measurement_start','measurement_end']:
|
||||
metadata[name+'_utc']=dt.datetime.fromtimestamp(timeline[name+'_ms']/1000,dt.timezone.utc).isoformat()
|
||||
if a.scenario=='idle':
|
||||
with (out/'samples.csv').open() as f: idle_samples=list(csv.DictReader(f))
|
||||
app_samples=[r for r in idle_samples if r['label'].startswith('HTTP ')]
|
||||
metadata.update(http_samples=len(app_samples),measured_http_samples=len(app_samples),measured_http_requests_per_second=0,failed_samples_including_scripts=sum(r['success'].lower()!='true' for r in idle_samples))
|
||||
if app_samples or metadata['failed_samples_including_scripts']:
|
||||
print('Idle baseline contains application requests or failed samples');code=1
|
||||
if metadata['actual_elapsed_seconds']+2<a.warmup+a.duration:
|
||||
print('Idle baseline stopped early; measurement is incomplete');code=1
|
||||
if a.scenario!='idle' and (out/'samples.csv').exists():
|
||||
with (out/'samples.csv').open() as f: all_samples=list(csv.DictReader(f))
|
||||
samples=[r for r in all_samples if r['label'].startswith('HTTP ')]
|
||||
all_failed=sum(r['success'].lower()!='true' for r in all_samples)
|
||||
failed=sum(r['success'].lower()!='true' for r in samples)
|
||||
measured=[r for r in samples if metadata.get('measurement_start_ms',float('inf')) <= int(r['timeStamp']) and int(r['timeStamp'])+int(r['elapsed']) <= metadata.get('measurement_end_ms',0)]
|
||||
if measured:
|
||||
with (out/'measured.csv').open('w') as f:
|
||||
w=csv.DictWriter(f,fieldnames=list(measured[0]));w.writeheader();w.writerows(measured)
|
||||
latencies=sorted(int(r['elapsed']) for r in measured)
|
||||
metadata.update(failed_samples_including_scripts=all_failed,http_samples=len(samples),failed_http_samples=failed,measured_http_samples=len(measured),measured_failed_http_samples=sum(r['success'].lower()!='true' for r in measured),measured_http_requests_per_second=len(measured)/a.duration,p95_latency_ms=latencies[min(len(latencies)-1,int(len(latencies)*.95))] if latencies else None)
|
||||
print(f'HTTP samples: {len(samples)}; failures: {failed}; measured samples: {len(measured)}')
|
||||
if all_failed or not measured: code=1
|
||||
if metadata['actual_elapsed_seconds']+2<a.warmup+a.duration: print('Run stopped early; measurement is incomplete');code=1
|
||||
if not a.no_perfmon:
|
||||
try:
|
||||
metadata['server_metrics']=summarize(out/'perfmon.csv',out/'perfmon-measured.csv',metadata['measurement_start_ms'],metadata['measurement_end_ms'],a.perfmon_interval_ms)
|
||||
print('Live PerfMon metrics saved and measurement interval validated')
|
||||
except (OSError,ValueError,KeyError) as error:
|
||||
metadata['monitoring_error']=str(error);print('Invalid monitoring:',error);code=1
|
||||
if not a.no_shelly:
|
||||
try:
|
||||
metadata['power_energy']=shelly.summarize(out/'shelly.csv',out/'shelly-measured.csv',metadata['measurement_start_ms'],metadata['measurement_end_ms'],a.shelly_interval_ms)
|
||||
print('Live Shelly power and measured-window energy saved')
|
||||
except (OSError,ValueError,KeyError) as error:
|
||||
metadata['power_error']=str(error);print('Invalid power measurement:',error);code=1
|
||||
metadata['exit_code']=code
|
||||
(out/'run.json').write_text(json.dumps(metadata,indent=2))
|
||||
if (out/'timeline.json').exists():
|
||||
try:
|
||||
from report import build
|
||||
build(out)
|
||||
except Exception as error:
|
||||
print('Graph generation failed; raw measurements are preserved:',error)
|
||||
metadata['report_error']=str(error);(out/'run.json').write_text(json.dumps(metadata,indent=2))
|
||||
raise SystemExit(code)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Shelly read-only preflight and measured-window energy calculations."""
|
||||
import csv, json, math, urllib.request
|
||||
VARIABLES=['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh']
|
||||
def check_plug(host,port=80,switch_id=0):
|
||||
def read(method):
|
||||
with urllib.request.urlopen(f'http://{host}:{port}/rpc/{method}',timeout=5) as r:return json.load(r)
|
||||
info=read('Shelly.GetDeviceInfo');status=read(f'Switch.GetStatus?id={switch_id}')
|
||||
if info.get('auth_en'):raise ValueError('Shelly authentication is enabled; this integration requires the current unauthenticated LAN API')
|
||||
if status.get('output') is not True:raise ValueError('Shelly outlet is off')
|
||||
values=[status.get('apower'),status.get('voltage'),status.get('current'),status.get('aenergy',{}).get('total')]
|
||||
if any(not isinstance(v,(float,int)) or not math.isfinite(v) or v<0 for v in values):raise ValueError('Shelly power/voltage/current/energy readings are unavailable')
|
||||
return {k:info.get(k) for k in ['model','gen','ver','app']}
|
||||
def summarize(raw,measured,start_ms,end_ms,interval_ms):
|
||||
with raw.open() as f:rows=list(csv.DictReader(f))
|
||||
points=[]
|
||||
for row in rows:
|
||||
if row['label']!='POWER Shelly status':continue
|
||||
if row['success'].lower()!='true':raise ValueError('A Shelly status poll failed; energy measurement is incomplete')
|
||||
values=[float(row[k]) for k in VARIABLES]
|
||||
if any(not math.isfinite(v) or v<0 for v in values):raise ValueError('Invalid Shelly metric')
|
||||
# Approximate the device sampling instant by the HTTP request midpoint.
|
||||
timestamp=int(row['timeStamp'])+int(row['elapsed'])/2
|
||||
points.append((timestamp,*values))
|
||||
points.sort()
|
||||
if len(points)<2 or points[0][0]>start_ms or points[-1][0]<end_ms:raise ValueError('Shelly samples do not bracket the full measured interval')
|
||||
if any(b[0]<=a[0] or b[0]-a[0]>interval_ms*3 or b[4]<a[4] for a,b in zip(points,points[1:])):raise ValueError('Shelly samples contain gaps, duplicate timestamps or an energy counter reset')
|
||||
def boundary(time):
|
||||
for a,b in zip(points,points[1:]):
|
||||
if a[0]<=time<=b[0]:return (time,*(a[i]+(b[i]-a[i])*(time-a[0])/(b[0]-a[0]) for i in range(1,5)))
|
||||
raise ValueError('Missing boundary')
|
||||
selected=[boundary(start_ms),*(p for p in points if start_ms<p[0]<end_ms),boundary(end_ms)]
|
||||
# Each recorded power reading represents one nominal polling interval.
|
||||
# Do not interpolate power or invent readings at the window boundaries.
|
||||
measured_points=[p for p in points if start_ms<=p[0]<end_ms]
|
||||
if not measured_points:raise ValueError('No Shelly power readings inside the measured interval')
|
||||
joules=sum(p[1] for p in measured_points)*(interval_ms/1000)
|
||||
watt_hours=selected[-1][4]-selected[0][4]
|
||||
with measured.open('w') as f:
|
||||
w=csv.writer(f);w.writerow(['timestamp_ms','power_watts','voltage_volts','current_amps','energy_wh']);w.writerows(selected)
|
||||
return {'measurement_seconds':(end_ms-start_ms)/1000,'samples_including_interpolated_boundaries':len(selected),'power_sample_count':len(measured_points),'nominal_sample_interval_ms':interval_ms,'nominal_sample_coverage_seconds':len(measured_points)*interval_ms/1000,'energy_method':'sum of recorded power readings multiplied by nominal polling interval; assumes each reading represents that interval','integrated_joules':joules,'integrated_kWh':joules/3600000,'average_watts':sum(p[1] for p in measured_points)/len(measured_points),'counter_delta_Wh':watt_hours,'counter_joules':watt_hours*3600,'counter_kWh':watt_hours/1000,'boundary_method':'Energy counter and exported plot boundaries interpolated; power sum uses only recorded in-window samples; timestamps approximate HTTP request midpoint'}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"sourceRevision": "2117236366130775214d9fd2611984d4348f2b79",
|
||||
"files": {
|
||||
"tools/PasswordHash/PasswordHash.csproj": "cfd3bef3cdb06f4c60489e4bdc8138b24278dc5fdd4ac992ad847975016432d4",
|
||||
"tools/PasswordHash/Program.cs": "b586366f70f6d5118886dbd4631a83846cf6edce3ed82d56d398eab6632710e0",
|
||||
"tools/energy-jmeter/README.md": "d38722ad3233d310f82da8314ac776bcbed78caead75df97df76a4245b7c92e8",
|
||||
"tools/energy-jmeter/WORKLOAD-SELECTION.md": "7cc4787ece099beae6cda770b573a4f1d277a38d15b017caf7e9db6b3332c31c",
|
||||
"tools/energy-jmeter/create-accounts.py": "af47278cc18d704a4d9767d79e31d500459ee2b0fd2ed014853fca9e6ac36d24",
|
||||
"tools/energy-jmeter/document-choice.py": "24fdab0a90cffec13ce4ee66b256c767beae0bc746f7b1c35ea9c45171619e8a",
|
||||
"tools/energy-jmeter/energy.py": "5a79604504eec1e0a78382897c8720094e9d7c431544b8911d587bf463488748",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/calibration.csv": "9abc60a90bf74abc3c9b633a48231f4c79853297e6865b100a43f317f488d117",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/cpu-headroom.png": "58fbbd3b666d18332f2691e86a2f52fa8402e1e876951297c19de1ec48c47acc",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/cpu-headroom.svg": "dba9a6130a326f179ddbdea4743dbc14f324dea1ca45ff145c53fec749e46462",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/evidence-summary.json": "d670a376f8170988963c17491f8a2a9aa882841a258c0046d6d3f2166f123209",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/idle-cpu-spikes.png": "94e1cb5aa6f3d6125ab5c11cb55bc0af490a447afc057c0dc3c5812e51eba6a3",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/idle-cpu-spikes.svg": "b9c79cdda790027e6aa45cfb2cb1bf7d6328e616eeb99e73eb974c338b259500",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/idle-cpu.csv": "1b0430ec9b42afc88d76772610f477d01160065870fe6e585fc7bf55879c996f",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/mean-response-knee.png": "e2bf4c7fb9eb2498a0366b492cbf34034783bc6c89ba5da3126870f2db1505fd",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/mean-response-knee.svg": "12827a72671be9e593392348385260c541a10aeda6068e590e7b59797ca3da57",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/selected-cpu-trace.png": "78dbc84b36ef22055b2bc60e639a056b80c4d9b983f53e6cd73eeed34068c448",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/selected-cpu-trace.svg": "a2ab95b314385dbcd8a7955822c81a48012a7b85df452708a1967a00683a431c",
|
||||
"tools/energy-jmeter/evidence/26-thread-choice/selected-cpu.csv": "436f1b23da65e8ff21edadd29ec1576c7d07562fea52fb8d8360d967730f407f",
|
||||
"tools/energy-jmeter/generate-plans.py": "f088e261d9e0b0f7426786d5a614819b5146a6a49f3e1f36c6f72d001134a8ee",
|
||||
"tools/energy-jmeter/perfmon.py": "5abedd6b2abc1c005cb42bbfcc8ecc0355692e2de37ccc2fc7056265ccb97586",
|
||||
"tools/energy-jmeter/plans/correction.jmx": "a71967c1f74fa6a9cb18c1fc01acf5d46766e59dd6a43239eaa77521c24df9ce",
|
||||
"tools/energy-jmeter/plans/idle.jmx": "6d3457d41a6a8d4221157f9c0b692506fb5a89544a9786ad7fd5a85d4950cdba",
|
||||
"tools/energy-jmeter/plans/mixed.jmx": "a379fff8429be5c11d95b734c659d004179e188280e229e43bcab269d882ff71",
|
||||
"tools/energy-jmeter/plans/professional.jmx": "6408d7ec87d4e50ac140577fde109185768746acc24b048278981ce1b3185f1a",
|
||||
"tools/energy-jmeter/plans/recording.jmx": "bd320f5aa121392df371a4d60f2d2ac91612f05b2c58d3dc9a164fe13e8f13e4",
|
||||
"tools/energy-jmeter/plans/review.jmx": "e93cbc3718c5ce2b387a191ae86228221a9f2357894d0d24bf6c48434c4718b9",
|
||||
"tools/energy-jmeter/prepare.py": "8b47c8069d7beb4af4601db82beb7a062defb31285c435e35275b4a593af9e79",
|
||||
"tools/energy-jmeter/report-template.html": "36aabc28083794b09921548a732377daed557f09fbc84a273011ebb3b90be0a9",
|
||||
"tools/energy-jmeter/report.py": "0371044b2558a600dc8d11d622d9d0bdacee8ff72f203dbcdde6e654d54471dc",
|
||||
"tools/energy-jmeter/run-idle.sh": "1c0cdaa2845f07cd91c45fbf145049ac528efe9e2c9273d6216d7a83b3106c5f",
|
||||
"tools/energy-jmeter/run.py": "0f59c690d59db2c432285cf6574a31768bbee75a6444b125d1190cd9314155a9",
|
||||
"tools/energy-jmeter/shelly.py": "69770101bb01d6ff95361e8f67f00232901bb3606fb9f647a81bd1121c49c76f",
|
||||
"tools/energy-jmeter/verify-idle.py": "e30978fb6252394e959fc32c842e2cb1708f3d1043fd5892ebce6d1982881899",
|
||||
"tools/energy-jmeter/verify-perfmon.py": "8ffa13a7d2b566a29549a58de4fbbff039cfeacbfaf73a515df6f1ef44273c0c",
|
||||
"tools/energy-jmeter/verify-plans.py": "b5a98e326bf73709a56867cd78f268f2af72e91eefe3a4455217986138098df6",
|
||||
"tools/energy-jmeter/verify-report.py": "9ff0369e3e26cd8f1962be8615372f31b4ceb3057d288604376553d8797e1c4d",
|
||||
"tools/energy-jmeter/verify-shelly.py": "789d0c535e45b72365555188595e9f14eb83f070f149495a3b38bf96b7cda34a"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Verified TLS compatible with the prototype installer's certificate profile.
|
||||
Python 3.13+ enables optional RFC-strict checks that reject the inherited
|
||||
prototype certificate's missing Authority Key Identifier. Standard chain, expiry,
|
||||
signature and hostname verification remain mandatory; no trust-all fallback.
|
||||
"""
|
||||
import ssl
|
||||
|
||||
def application_context(cafile):
|
||||
context = ssl.create_default_context(cafile=cafile)
|
||||
context.verify_flags &= ~ssl.VERIFY_X509_STRICT
|
||||
assert context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname
|
||||
return context
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"date": "2026-10-16",
|
||||
"host": "Provided published B release; real HTTPS, disposable PostgreSQL 18.6, restricted runtime role",
|
||||
"applicationDllSha256": "a81dab8f6ab9e692af7bd1773604672da5cad93f817e65e76c29901efc0239a8",
|
||||
"accountSetup": "flat native + nested JSON, existing values retained, private output, regeneration rejected",
|
||||
"scenarios": {
|
||||
"recording": {
|
||||
"exit_code": 0,
|
||||
"http_samples": 782,
|
||||
"failed_http_samples": 0,
|
||||
"measured_http_samples": 328,
|
||||
"warmup_seconds": 1,
|
||||
"measurement_duration_seconds": 4
|
||||
},
|
||||
"review": {
|
||||
"exit_code": 0,
|
||||
"http_samples": 901,
|
||||
"failed_http_samples": 0,
|
||||
"measured_http_samples": 374,
|
||||
"warmup_seconds": 1,
|
||||
"measurement_duration_seconds": 4
|
||||
},
|
||||
"correction": {
|
||||
"exit_code": 0,
|
||||
"http_samples": 985,
|
||||
"failed_http_samples": 0,
|
||||
"measured_http_samples": 415,
|
||||
"warmup_seconds": 1,
|
||||
"measurement_duration_seconds": 4
|
||||
},
|
||||
"mixed": {
|
||||
"exit_code": 0,
|
||||
"http_samples": 896,
|
||||
"failed_http_samples": 0,
|
||||
"measured_http_samples": 379,
|
||||
"warmup_seconds": 1,
|
||||
"measurement_duration_seconds": 4
|
||||
},
|
||||
"professional": {
|
||||
"exit_code": 0,
|
||||
"http_samples": 475,
|
||||
"failed_http_samples": 0,
|
||||
"measured_http_samples": 197,
|
||||
"warmup_seconds": 1,
|
||||
"measurement_duration_seconds": 4
|
||||
},
|
||||
"idle": {
|
||||
"exit_code": 0,
|
||||
"http_samples": 0,
|
||||
"failed_http_samples": null,
|
||||
"measured_http_samples": 0,
|
||||
"warmup_seconds": 1,
|
||||
"measurement_duration_seconds": 4
|
||||
}
|
||||
},
|
||||
"limits": [
|
||||
"Short smoke only; not capacity or four-hour validation",
|
||||
"PerfMon and Shelly disabled; no energy measurement",
|
||||
"Token renewal exercised by separate contract stub with short-lived tokens"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Disposable real B HTTPS/PostgreSQL smoke; no A deployment or live telemetry."""
|
||||
from tls import application_context
|
||||
from pathlib import Path
|
||||
import hashlib, argparse, subprocess as S, tempfile, os, json, socket, time, ssl, urllib.request, csv, secrets
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--release',required=True,help='Published B release directory from deploy/build-release.sh')
|
||||
parser.add_argument('--dotnet',default='dotnet')
|
||||
args=parser.parse_args()
|
||||
repo=Path(__file__).resolve().parents[2]; here=repo/'tools/energy-jmeter'; dotnet=args.dotnet; release=Path(args.release).resolve(); name='healthapp-b-jmeter-'+secrets.token_hex(4)
|
||||
def run(cmd,**kw):
|
||||
r=S.run(cmd,capture_output=True,text=True,**kw)
|
||||
if r.returncode: raise RuntimeError('Command failed: '+str(cmd[:2])+'\n'+r.stdout[-2000:]+r.stderr[-2000:])
|
||||
return r.stdout
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-b-jmeter-') as temp:
|
||||
root=Path(temp); app=None
|
||||
try:
|
||||
env=dict(os.environ,POSTGRES_PASSWORD=secrets.token_hex(24))
|
||||
run(['docker','run','--rm','-d','--name',name,'-p','127.0.0.1::5432','-e','POSTGRES_PASSWORD','postgres:18.6'],env=env)
|
||||
for _ in range(100):
|
||||
if S.run(['docker','exec',name,'pg_isready','-h','127.0.0.1','-U','postgres'],stdout=S.DEVNULL,stderr=S.DEVNULL).returncode==0:break
|
||||
time.sleep(.2)
|
||||
port=json.loads(run(['docker','inspect','--format','{{json .NetworkSettings.Ports}}',name]))['5432/tcp'][0]['HostPort']
|
||||
def sql(text): return run(['docker','exec','-i',name,'psql','-U','postgres','-v','ON_ERROR_STOP=1'],input=text)
|
||||
sql("CREATE ROLE workload_runtime LOGIN PASSWORD 'disposable-test-only' NOSUPERUSER NOCREATEDB NOCREATEROLE;")
|
||||
for module in ['Profile','Observations']: sql((repo/f'src/Modules/{module}/Migrations/001-{module.lower()}.sql').read_text())
|
||||
sql('REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA profile,observations TO workload_runtime; GRANT SELECT,INSERT,UPDATE ON profile.patient TO workload_runtime; GRANT SELECT,INSERT,UPDATE,DELETE ON observations.observation TO workload_runtime; GRANT SELECT ON profile.schema_version,observations.schema_version TO workload_runtime;')
|
||||
with socket.socket() as sock:sock.bind(('127.0.0.1',0)); app_port=sock.getsockname()[1]
|
||||
plan=root/'plan';runtime=root/'runtime'
|
||||
run([dotnet,str(release/'provisioner/HealthApp.Provisioning.dll'),'prepare','--plan',str(plan),'--host','127.0.0.1','--port',str(app_port),'--root',str(runtime)],env=env)
|
||||
install=json.loads((plan/'installation.json').read_text());settings=install['Settings']
|
||||
settings['ConnectionStrings:HealthDatabase']=f'Host=127.0.0.1;Port={port};Database=postgres;Username=workload_runtime;Password=disposable-test-only'
|
||||
settings['Kestrel:Certificates:Default:Path']=str(plan/'application.pfx');(runtime/'var/lib/healthapp-b/keys').mkdir(parents=True)
|
||||
config=root/'original.json';config.write_text(json.dumps(settings));os.chmod(config,0o600)
|
||||
fixture=root/'fixture'
|
||||
run(['python3',str(here/'create-accounts.py'),'--configuration',str(config),'--output',str(fixture),'--count','2','--dotnet',dotnet],env=env)
|
||||
generated=json.loads((fixture/'appsettings.json').read_text())
|
||||
assert all(generated[k]==v for k,v in settings.items());assert json.loads(config.read_text())==settings
|
||||
assert (fixture/'appsettings.json').stat().st_mode&0o777==0o600
|
||||
# Also exercise nested example configuration and regeneration/overwrite refusal.
|
||||
nested=root/'nested.json';nested.write_text(json.dumps({'Authentication':{'Accounts':[{'AccountId':'existing','Role':'Patient','PasswordHash':'preserved'}]},'sentinel':123}))
|
||||
run(['python3',str(here/'create-accounts.py'),'--configuration',str(nested),'--output',str(root/'nested-output'),'--count','1','--dotnet',dotnet],env=env)
|
||||
assert len(json.loads((root/'nested-output/appsettings.json').read_text())['Authentication']['Accounts'])==2
|
||||
assert S.run(['python3',str(here/'create-accounts.py'),'--configuration',str(fixture/'appsettings.json'),'--output',str(root/'forbidden'),'--dotnet',dotnet],capture_output=True).returncode!=0
|
||||
env['HEALTHAPP_CONFIGURATION_FILE']=str(fixture/'appsettings.json');env['ASPNETCORE_ENVIRONMENT']='Production'
|
||||
log=(root/'app.log').open('w')
|
||||
def start():return S.Popen([dotnet,str(release/'app/HealthApp.dll')],env=env,stdout=log,stderr=log)
|
||||
ca=plan/'healthapp-ca.crt';context=application_context(cafile=str(ca));base=f'https://127.0.0.1:{app_port}'
|
||||
def wait():
|
||||
for _ in range(10):
|
||||
try:
|
||||
with urllib.request.urlopen(base+'/api/measurement-guidance',context=context,timeout=2):return
|
||||
except Exception as error:
|
||||
last=repr(error);time.sleep(.2)
|
||||
diagnostic=(root/'app.log').read_text()[-3000:]
|
||||
for value in [install['RuntimePassword'],install['CertificatePassword'],* [x['Password'] for x in install['Accounts']]]: diagnostic=diagnostic.replace(value,'[redacted]')
|
||||
raise RuntimeError('Host startup failed: '+last+'\n'+diagnostic)
|
||||
app=start();wait()
|
||||
dataset=root/'dataset';run(['python3',str(here/'prepare.py'),'--base-url',base,'--ca',str(ca),'--accounts',str(fixture/'accounts.json'),'--output',str(dataset),'--days','4'])
|
||||
with (dataset/'users.csv').open() as f: users=list(csv.DictReader(f))
|
||||
assert len(users)==2
|
||||
prof=install['Accounts'][1];generated['Access:ProfessionalAssignments:'+prof['AccountId']+':0']=users[0]['patient_id']
|
||||
(fixture/'appsettings.json').write_text(json.dumps(generated));app.terminate();app.wait(timeout=20);app=start();wait()
|
||||
profcsv=root/'professionals.csv'
|
||||
with profcsv.open('w') as f:w=csv.writer(f);w.writerow(['account_id','password','patient_id']);w.writerow([prof['AccountId'],prof['Password'],users[0]['patient_id']])
|
||||
results={}
|
||||
for scenario in ['recording','review','correction','mixed','professional','idle']:
|
||||
cmd=['python3',str(here/'run.py'),scenario,'--no-perfmon','--no-shelly','--host','127.0.0.1','--port',str(app_port),'--warmup','1','--duration','4','--ramp','0','--think-min-ms','0','--think-mean-ms','10','--think-stddev-ms','5','--session-pause-ms','50','--session-stddev-ms','10','--output',str(root/scenario)]
|
||||
if scenario!='idle':cmd+=['--ca',str(ca),'--users-file',str(profcsv if scenario=='professional' else dataset/'users.csv'),'--users','1' if scenario=='professional' else '2']
|
||||
run(cmd)
|
||||
data=json.loads((root/scenario/'run.json').read_text());results[scenario]={k:data.get(k) for k in ['exit_code','http_samples','failed_http_samples','measured_http_samples','warmup_seconds','measurement_duration_seconds']}
|
||||
assert data['measurement_start_ms']-data['warmup_start_ms']==1000
|
||||
assert data['measurement_end_ms']-data['measurement_start_ms']==4000
|
||||
print(scenario,results[scenario],flush=True)
|
||||
(here/'verification-b.json').write_text(json.dumps({'date':time.strftime('%Y-%m-%d'),'host':'Provided published B release; real HTTPS, disposable PostgreSQL 18.6, restricted runtime role','applicationDllSha256':hashlib.sha256((release/'app/HealthApp.dll').read_bytes()).hexdigest(),'accountSetup':'flat native + nested JSON, existing values retained, private output, regeneration rejected','scenarios':results,'limits':['Short smoke only; not capacity or four-hour validation','PerfMon and Shelly disabled; no energy measurement','Token renewal exercised by separate contract stub with short-lived tokens']},indent=2)+'\n')
|
||||
finally:
|
||||
if app is not None:app.terminate();app.wait(timeout=20)
|
||||
S.run(['docker','stop',name],stdout=S.DEVNULL,stderr=S.DEVNULL)
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the idle runner makes zero application requests, including preflight."""
|
||||
import csv,json,subprocess,tempfile,threading
|
||||
from pathlib import Path
|
||||
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
|
||||
HERE=Path(__file__).parent
|
||||
class Application(BaseHTTPRequestHandler):
|
||||
requests=0
|
||||
def do_GET(self):
|
||||
type(self).requests+=1;self.send_response(500);self.end_headers()
|
||||
do_POST=do_GET
|
||||
def log_message(self,*args):pass
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Application)
|
||||
threading.Thread(target=server.serve_forever,daemon=True).start()
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-idle-') as name:
|
||||
out=Path(name)/'run'
|
||||
result=subprocess.run(['python3',str(HERE/'run.py'),'idle','--host','127.0.0.1','--port',str(server.server_port),'--no-perfmon','--no-shelly','--warmup','1','--duration','3','--output',str(out)],capture_output=True,text=True)
|
||||
assert result.returncode==0,result.stdout+result.stderr
|
||||
data=json.loads((out/'run.json').read_text())
|
||||
assert Application.requests==0 and data['http_samples']==0 and data['users']==0
|
||||
assert data['measurement_end_ms']-data['measurement_start_ms']==3000
|
||||
assert data['measurement_start_ms']-data['warmup_start_ms']==1000
|
||||
with (out/'samples.csv').open() as f:assert all(not r['label'].startswith('HTTP ') for r in csv.DictReader(f))
|
||||
print('Idle baseline passed: no application calls or login, no CA/accounts needed, warmup excluded')
|
||||
finally:server.shutdown()
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify metric decoding; optionally verify a live JMeter-to-agent connection."""
|
||||
import argparse, csv, json, subprocess, tempfile, time
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as E
|
||||
from perfmon import METRICS, check_agent, summarize
|
||||
p=argparse.ArgumentParser();p.add_argument('--host');p.add_argument('--port',type=int,default=4444);p.add_argument('--output');a=p.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-perfmon-unit-') as name:
|
||||
root=Path(name);raw=root/'raw.csv'
|
||||
def fixture(skip=None,gap=False):
|
||||
with raw.open('w') as f:
|
||||
writer=csv.DictWriter(f,fieldnames=['timeStamp','elapsed','label']);writer.writeheader()
|
||||
for timestamp in ([5000,25000] if gap else range(0,30001,5000)):
|
||||
for kind,param,unit in METRICS:
|
||||
if (kind,param)==skip:continue
|
||||
writer.writerow({'timeStamp':timestamp,'elapsed':73250 if kind=='CPU' else 123000,'label':'fixture '+kind+' '+param})
|
||||
fixture();stats=summarize(raw,root/'measured.csv',5000,25000,5000)
|
||||
assert stats['fixture CPU combined']['mean']==73.25
|
||||
assert len(stats)==9 and all(s['samples']==5 for s in stats.values())
|
||||
for skipped,gap in [(('CPU','combined'),False),(None,True)]:
|
||||
fixture(skipped,gap)
|
||||
try:summarize(raw,root/'invalid.csv',5000,25000,5000)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('Missing metrics/collection gaps were accepted')
|
||||
print('Metric decoding, warmup exclusion and gap detection passed')
|
||||
if a.host:
|
||||
if not a.output:p.error('--output is required for a live check')
|
||||
check_agent(a.host,a.port)
|
||||
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
|
||||
document=E.parse(Path(__file__).parent/'plans/idle.jmx')
|
||||
for group in document.iter('ThreadGroup'):
|
||||
if group.get('testname')=='Shelly live power':group.set('enabled','false')
|
||||
plan=out/'idle.jmx';document.write(plan)
|
||||
cmd=[str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jperfmon_host='+a.host,'-Jperfmon_port='+str(a.port),'-Jperfmon_file='+str(out/'perfmon.csv'),'-JjmeterPlugin.perfmon.interval=5000','-JjmeterPlugin.perfmon.useUDP=false','-Jjmeter.save.saveservice.autoflush=true','-Jwarmup_seconds=5','-Jduration_seconds=20','-Jtotal_duration_seconds=30','-Jtimeline_file='+str(out/'timeline.json')]
|
||||
process=subprocess.Popen(cmd);saved_live=False
|
||||
while process.poll() is None:
|
||||
raw=out/'perfmon.csv'
|
||||
if raw.exists() and raw.stat().st_size>0:saved_live=True
|
||||
time.sleep(.25)
|
||||
assert process.returncode==0 and saved_live, 'Metrics were not saved while JMeter was running'
|
||||
timeline=json.loads((out/'timeline.json').read_text())
|
||||
stats=summarize(out/'perfmon.csv',out/'perfmon-measured.csv',timeline['measurement_start_ms'],timeline['measurement_end_ms'],5000)
|
||||
(out/'summary.json').write_text(json.dumps(stats,indent=2))
|
||||
print('Live JMeter collection passed: nine metrics written during the run; no application load sent')
|
||||
print('Results:',out)
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise every generated plan against a local HTTPS contract stub, not testserver."""
|
||||
import datetime, json, os, ssl, subprocess, tempfile, threading, uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as E
|
||||
from urllib.parse import urlsplit
|
||||
HERE=Path(__file__).resolve().parent
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version='HTTP/1.1'
|
||||
observations={}; tokens={}; logins=0; break_insights=False
|
||||
def log_message(self,*args): pass
|
||||
def handle_request(self):
|
||||
path=urlsplit(self.path).path
|
||||
body=json.loads(self.rfile.read(int(self.headers.get('Content-Length',0))) or '{}')
|
||||
code=200; data={}
|
||||
if path=='/api/measurement-guidance': data={'available':True}
|
||||
elif path=='/api/authentication/login':
|
||||
if body.get('password')!='test': code=401
|
||||
else:
|
||||
token=str(uuid.uuid4());self.tokens[token]=body['accountId'];type(self).logins+=1
|
||||
data={'accessToken':token,'expiresIn':65,'role':'Patient','tokenType':'Bearer'}
|
||||
elif self.headers.get('Authorization','').removeprefix('Bearer ') not in self.tokens: code=401
|
||||
elif path=='/api/professionals/me/patients': data=[{'patientId':'patient-0'},{'patientId':'patient-1'}]
|
||||
elif path=='/api/patients/me':
|
||||
account=self.tokens[self.headers['Authorization'].removeprefix('Bearer ')]
|
||||
data={'patientId':'patient-'+account.split('-')[-1]}
|
||||
elif path.startswith('/api/observations/'):
|
||||
oid=path.split('/')[-1]
|
||||
if oid not in self.observations: code=404
|
||||
elif self.command=='DELETE': del self.observations[oid];code=204
|
||||
else:
|
||||
if self.command=='PATCH':self.observations[oid].update(body)
|
||||
data=self.observations[oid]
|
||||
elif path.startswith('/api/patients/'):
|
||||
pid=path.split('/')[3];profile={'patientId':pid}
|
||||
baseline={'patientId':pid,'observationId':'baseline','systolic':128,'diastolic':82,'pulse':68,'measuredAt':'2026-09-01T08:00:00'}
|
||||
if path.endswith('/observations'):
|
||||
if self.command=='POST':
|
||||
if not body.get('measuredAt') or body.get('measurementContext',{}).get('setting') not in ['Home','Clinic','Other','Unknown']:code=400
|
||||
else:
|
||||
oid=str(uuid.uuid4());data=dict(body,patientId=pid,observationId=oid);self.observations[oid]=data;code=201
|
||||
else:data=[baseline]
|
||||
elif path.endswith('/latest'):data=baseline
|
||||
elif path.endswith('/overview'):data={'patient':profile,'latestObservation':baseline,'insight':{'contributingCount':60}}
|
||||
elif path.endswith('/insights'):
|
||||
data={'contributingCount':60}
|
||||
if self.break_insights: code=503
|
||||
elif path.endswith('/trends'):data={'patientId':pid}
|
||||
else:data=profile
|
||||
else:code=404
|
||||
payload=b'' if code==204 else json.dumps(data).encode()
|
||||
self.send_response(code);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(payload)));self.end_headers();self.wfile.write(payload)
|
||||
do_GET=do_POST=do_PATCH=do_DELETE=handle_request
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-jmeter-verify-') as temp:
|
||||
root=Path(temp);cert=root/'cert.pem';key=root/'key.pem'
|
||||
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1','-keyout',str(key),'-out',str(cert),'-subj','/CN=127.0.0.1','-addext','subjectAltName=IP:127.0.0.1'],check=True,capture_output=True)
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler);context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);context.load_cert_chain(cert,key);server.socket=context.wrap_socket(server.socket,server_side=True)
|
||||
threading.Thread(target=server.serve_forever,daemon=True).start()
|
||||
users=root/'users.csv';users.write_text('account_id,password,patient_id\naccount-0,test,patient-0\naccount-1,test,patient-1\n')
|
||||
accounts=root/'accounts.json'
|
||||
accounts.write_text(json.dumps([{'AccountId':f'account-{i}','Password':'test','Role':'Patient'} for i in range(2)]))
|
||||
prepared=subprocess.run(['python3',str(HERE/'prepare.py'),'--base-url',f'https://127.0.0.1:{server.server_port}','--ca',str(cert),'--accounts',str(accounts),'--output',str(root/'dataset'),'--days','4'],capture_output=True,text=True)
|
||||
assert prepared.returncode==0, prepared.stderr
|
||||
assert len(Handler.observations)==16
|
||||
assert set(o['measurementContext']['setting'] for o in Handler.observations.values())=={'Home','Clinic','Unknown'}
|
||||
assert (root/'dataset/users.csv').stat().st_mode & 0o777 == 0o600
|
||||
print('Synthetic dataset preparation passed')
|
||||
# Professional runner preflight is intentionally separate: fixture credentials are patient roles.
|
||||
for scenario in ['recording','review','correction','mixed']:
|
||||
initial_logins=Handler.logins
|
||||
result=subprocess.run(['python3',str(HERE/'run.py'),scenario,'--no-perfmon','--no-shelly','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','1','--duration','6','--ramp','0','--think-min-ms','0','--think-mean-ms','10','--think-stddev-ms','5','--session-pause-ms','100','--session-stddev-ms','25','--output',str(root/scenario)],capture_output=True,text=True)
|
||||
if result.returncode:
|
||||
print(result.stdout,result.stderr)
|
||||
print((root/scenario/'jmeter.log').read_text()[-6000:])
|
||||
raise SystemExit('Plan verification failed: '+scenario)
|
||||
assert Handler.logins - initial_logins >= 6, 'Initial login and token renewal were not exercised'
|
||||
data=json.loads((root/scenario/'run.json').read_text());assert data['measurement_end_ms']-data['measurement_start_ms']==6000; assert data['measured_http_samples']>0; print(scenario, 'passed;',data['http_samples'],'HTTP samples;', data['failed_http_samples'],'failures')
|
||||
# Run the professional plan directly so its assigned-patient semantic assertion is exercised.
|
||||
professional=E.parse(HERE/'plans/professional.jmx')
|
||||
for collector in professional.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):collector.set('enabled','false')
|
||||
for group in professional.iter('ThreadGroup'):
|
||||
if group.get('testname')=='Shelly live power':group.set('enabled','false')
|
||||
professional.write(root/'professional.jmx')
|
||||
result=subprocess.run([str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(root/'professional.jmx'),'-l',str(root/'professional.csv'),'-j',str(root/'professional.log'),'-Jperfmon_enabled=false','-Jhost=127.0.0.1','-Jport='+str(server.server_port),'-Jusers_file='+str(users),'-Jusers=2','-Jtotal_duration_seconds=8','-Jramp_seconds=0','-Jthink_min_ms=0','-Jthink_mean_ms=0','-Jthink_stddev_ms=0','-Jsession_pause_ms=100','-Jsession_stddev_ms=25','-Jperiod_from=2026-01-01T00:00:00Z','-Jperiod_to=2027-01-01T00:00:00Z'],capture_output=True,text=True)
|
||||
import csv
|
||||
with (root/'professional.csv').open() as f: samples=list(csv.DictReader(f))
|
||||
assert result.returncode==0 and samples and all(r['success']=='true' for r in samples), result.stdout+result.stderr
|
||||
print('professional passed;',len(samples),'samples; token renewal exercised across all plans')
|
||||
Handler.break_insights=True
|
||||
failed=subprocess.run(['python3',str(HERE/'run.py'),'review','--no-perfmon','--no-shelly','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','0','--duration','5','--ramp','0','--think-min-ms','0','--think-mean-ms','0','--think-stddev-ms','0','--session-pause-ms','0','--session-stddev-ms','0','--output',str(root/'expected-failure')],capture_output=True,text=True)
|
||||
assert failed.returncode!=0
|
||||
assert json.loads((root/'expected-failure/run.json').read_text())['failed_http_samples']>0
|
||||
print('Unexpected upstream failure correctly invalidates the run')
|
||||
# Constant 100 W for 4 measured hours is exactly 1,440,000 J / 0.4 kWh.
|
||||
energy_run=root/'energy-run.json';energy_run.write_text(json.dumps({'measurement_start_ms':1000000,'measurement_end_ms':15400000,'measured_http_samples':100}))
|
||||
power=root/'power.csv';power.write_text('timestamp,power_watts\n1970-01-01T00:00:00Z,100\n1970-01-01T05:00:00Z,100\n')
|
||||
energy=subprocess.run(['python3',str(HERE/'energy.py'),str(energy_run),str(power)],capture_output=True,text=True,check=True)
|
||||
energy_result=json.loads(energy.stdout); assert energy_result['joules']==1440000 and energy_result['kWh']==0.4
|
||||
print('Four-hour power integration passed')
|
||||
server.shutdown()
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify clock alignment, one-second aggregation and missing-data semantics."""
|
||||
import csv,datetime as dt,json,tempfile
|
||||
from pathlib import Path
|
||||
import report
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-report-') as name:
|
||||
folder=Path(name);start=1000000
|
||||
(folder/'timeline.json').write_text(json.dumps({'warmup_start_ms':start,'measurement_start_ms':start+2000,'measurement_end_ms':start+5000}))
|
||||
(folder/'run.json').write_text(json.dumps({'scenario':'mixed','exit_code':0,'finished_utc':dt.datetime.fromtimestamp((start+5000)/1000,dt.timezone.utc).isoformat()}))
|
||||
def write(name,fields,rows):
|
||||
with (folder/name).open('w') as f:w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(rows)
|
||||
write('samples.csv',['timeStamp','elapsed','label','success'],[{'timeStamp':start+2050,'elapsed':200,'label':'HTTP Read profile','success':'true'},{'timeStamp':start+2200,'elapsed':1000,'label':'HTTP Read overview','success':'false'},{'timeStamp':start+2250,'elapsed':10,'label':'POWER Shelly status','success':'true'}])
|
||||
write('perfmon.csv',['timeStamp','elapsed','label','success'],[{'timeStamp':start+2100,'elapsed':30000,'label':'NUC CPU combined','success':'true'},{'timeStamp':start+2800,'elapsed':50000,'label':'NUC CPU combined','success':'true'},{'timeStamp':start+2110,'elapsed':104857600000,'label':'NUC Memory actualused','success':'true'}])
|
||||
write('shelly.csv',['timeStamp','elapsed','label','success','shelly_power_watts','shelly_energy_wh'],[{'timeStamp':start+2150,'elapsed':100,'label':'POWER Shelly status','success':'true','shelly_power_watts':20,'shelly_energy_wh':3}])
|
||||
original=report.plot;report.plot=lambda *args:None
|
||||
rows=report.build(folder)
|
||||
report.plot=original
|
||||
assert len(rows)==5
|
||||
assert rows[2]['phase']=='measurement' and rows[1]['phase']=='warmup'
|
||||
assert rows[2]['cpu_percent']==40 and rows[2]['ram_MiB']==100 and rows[2]['power_watts']==20
|
||||
assert rows[2]['requests_s']==2 and rows[2]['errors_s']==1 and rows[2]['error_percent']==50
|
||||
assert rows[2]['latency_mean_ms']==600 and rows[2]['latency_p95_ms']==1000
|
||||
assert rows[3]['cpu_percent'] is None and rows[3]['latency_mean_ms'] is None and rows[3]['requests_s']==0
|
||||
assert (folder/'report.html').exists() and (folder/'per-second.csv').exists()
|
||||
print('One-second request/latency/error aggregation, UTC alignment, warmup and missing measurements passed')
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check power math and optionally exercise live JMeter-to-Shelly collection."""
|
||||
import argparse, csv, json, subprocess, tempfile, time, xml.etree.ElementTree as E
|
||||
from pathlib import Path
|
||||
import shelly
|
||||
p=argparse.ArgumentParser();p.add_argument('--host');p.add_argument('--port',type=int,default=80);p.add_argument('--output');a=p.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-shelly-test-') as name:
|
||||
root=Path(name);raw=root/'power.csv'
|
||||
with raw.open('w') as f:
|
||||
fields=['timeStamp','elapsed','label','success',*shelly.VARIABLES];w=csv.DictWriter(f,fieldnames=fields);w.writeheader()
|
||||
for t in range(0,20001,1000):
|
||||
w.writerow(dict(zip(fields,[t,0,'POWER Shelly status','true',100,230,.5,t/36000])))
|
||||
result=shelly.summarize(raw,root/'measured.csv',2500,17500,1000)
|
||||
assert result['integrated_joules']==1500 and abs(result['counter_joules']-1500)<.0001
|
||||
assert result['measurement_seconds']==15 and result['average_watts']==100
|
||||
assert result['power_sample_count']==15 and result['nominal_sample_coverage_seconds']==15
|
||||
# Variable power distinguishes a direct sample sum from trapezoidal integration.
|
||||
with raw.open() as f: variable=list(csv.DictReader(f))
|
||||
variable[3]['shelly_power_watts']='200'
|
||||
with raw.open('w') as f:
|
||||
w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(variable)
|
||||
variable_result=shelly.summarize(raw,root/'variable.csv',2500,17500,1000)
|
||||
assert variable_result['integrated_joules']==1600
|
||||
for start,end in [(-1000,17500),(2500,25000)]:
|
||||
try:shelly.summarize(raw,root/'bad.csv',start,end,1000)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('Incomplete coverage accepted')
|
||||
with raw.open() as f:rows=list(csv.DictReader(f))
|
||||
for variant in ['gap','reset','failed']:
|
||||
bad=list(rows)
|
||||
if variant=='gap':bad=[r for r in bad if not 5000<int(r['timeStamp'])<15000]
|
||||
elif variant=='reset':bad=[dict(r,shelly_energy_wh='0') if int(r['timeStamp'])>=10000 else r for r in bad]
|
||||
else:bad[6]=dict(bad[6],success='false')
|
||||
path=root/(variant+'.csv')
|
||||
with path.open('w') as f:w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(bad)
|
||||
try:shelly.summarize(path,root/'bad.csv',2500,17500,1000)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError(variant+' accepted')
|
||||
with raw.open('w') as f:
|
||||
w=csv.DictWriter(f,fieldnames=fields);w.writeheader()
|
||||
for t in range(0,16500001,300000):
|
||||
w.writerow(dict(zip(fields,[t,0,'POWER Shelly status','true',100,230,.5,t/36000])))
|
||||
long_run=shelly.summarize(raw,root/'four-hours.csv',1800000,16200000,300000)
|
||||
assert long_run['measurement_seconds']==14400 and long_run['integrated_joules']==1440000
|
||||
assert long_run['counter_kWh']==.4
|
||||
print('Shelly energy calculation, warmup exclusion, gaps, resets and failed-poll checks passed')
|
||||
if a.host:
|
||||
if not a.output:p.error('--output is required for live verification')
|
||||
print('Device:',shelly.check_plug(a.host,a.port))
|
||||
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
|
||||
document=E.parse(Path(__file__).parent/'plans/idle.jmx')
|
||||
for collector in document.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):collector.set('enabled','false')
|
||||
plan=out/'idle.jmx';document.write(plan)
|
||||
command=[str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jshelly_host='+a.host,'-Jshelly_port='+str(a.port),'-Jshelly_file='+str(out/'shelly.csv'),'-Jsample_variables='+','.join(shelly.VARIABLES),'-Jjmeter.save.saveservice.autoflush=true','-Jwarmup_seconds=5','-Jduration_seconds=20','-Jtotal_duration_seconds=35','-Jtimeline_file='+str(out/'timeline.json')]
|
||||
process=subprocess.Popen(command);live=False
|
||||
while process.poll() is None:
|
||||
file=out/'shelly.csv'
|
||||
if file.exists() and file.stat().st_size>0:live=True
|
||||
time.sleep(.25)
|
||||
assert process.returncode==0 and live,'Power readings were not written while JMeter was running'
|
||||
timeline=json.loads((out/'timeline.json').read_text())
|
||||
result=shelly.summarize(out/'shelly.csv',out/'shelly-measured.csv',timeline['measurement_start_ms'],timeline['measurement_end_ms'],5000)
|
||||
(out/'summary.json').write_text(json.dumps(result,indent=2));print(json.dumps(result,indent=2))
|
||||
print('Live Shelly JMeter collection passed; no switching commands or application requests sent')
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check that certificate-profile compatibility does not disable trust/hostname checks."""
|
||||
import ssl, subprocess, tempfile, threading, urllib.request, urllib.error
|
||||
from pathlib import Path
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from tls import application_context
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self): self.send_response(200); self.end_headers()
|
||||
def log_message(self,*args): pass
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root=Path(temp); cert=root/'cert.pem'; key=root/'key.pem'
|
||||
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1','-keyout',str(key),'-out',str(cert),'-subj','/CN=127.0.0.1','-addext','subjectAltName=IP:127.0.0.1'],check=True,capture_output=True)
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||
context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);context.load_cert_chain(cert,key)
|
||||
server.socket=context.wrap_socket(server.socket,server_side=True)
|
||||
threading.Thread(target=server.serve_forever,daemon=True).start()
|
||||
try:
|
||||
trusted=application_context(str(cert))
|
||||
with urllib.request.urlopen(f'https://127.0.0.1:{server.server_port}',context=trusted,timeout=3) as r:assert r.status==200
|
||||
for host,ctx in [('localhost',trusted),('127.0.0.1',ssl.create_default_context())]:
|
||||
try:urllib.request.urlopen(f'https://{host}:{server.server_port}',context=ctx,timeout=3)
|
||||
except urllib.error.URLError as e:assert isinstance(e.reason,ssl.SSLCertVerificationError)
|
||||
else:raise AssertionError('Invalid certificate accepted')
|
||||
print('TLS passed: trusted CA accepted; wrong hostname and untrusted CA rejected')
|
||||
finally:server.shutdown();server.server_close()
|
||||