Record architecture B corrections and measurement tooling
This commit is contained in:
1 parent
097d156c18
commit
6ea20b2365
78 files changed
+45820
-67
No files matched your search
@@ -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)
|
||||
Reference in new issue
Block a user