Files
mtusi2026lab7/student-tests/pipeline_support.py

169 lines
4.6 KiB
Python

import json
import subprocess
import time
from pathlib import Path
from client import Client, check
COMPOSE = ["docker", "compose"]
def compose(*args, data=None):
result = subprocess.run(
COMPOSE + list(args), input=data, text=True, capture_output=True, timeout=120
)
check(result.returncode == 0, "Compose operator action failed: " + args[0])
return result.stdout.strip()
def sql(statement):
return compose(
"exec",
"-T",
"db",
"psql",
"-v",
"ON_ERROR_STOP=1",
"-U",
"operator",
"-d",
"messenger",
"-At",
data=statement,
)
def broker(*args):
code = "import json,redis,sys;d=json.load(open('/audit-secrets/operator/credentials.json'));r=redis.Redis(host='broker',username='operator',password=d['broker_operator_password'],ssl=True,ssl_ca_certs='/audit-secrets/public/ca.crt',ssl_certfile='/audit-secrets/operator/service.crt',ssl_keyfile='/audit-secrets/operator/service.key',ssl_check_hostname=True,decode_responses=True);v=r.execute_command(*json.load(sys.stdin));print('PONG' if v is True else json.dumps(v) if isinstance(v,list) else v)"
return compose("run", "--rm", "--no-deps", "-T", "audit", "-c", code, data=json.dumps(args))
def wait_for(predicate, timeout=90, message="condition timed out"):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return
time.sleep(0.25)
raise AssertionError(message)
def ready_api():
observed = set()
def probe():
try:
states = compose("ps", "--format", "{{.Health}}", "api").splitlines()
if len(states) != 2 or any(state != "healthy" for state in states):
return False
response = Client(base_url="https://127.0.0.1:8443").call(
"GET", "/health/ready", schema="Health"
)
observed.add(response["headers"].get("X-Instance-Id"))
return len(observed - {None}) == 2
except Exception:
return False
wait_for(probe, 120, "API not ready")
def metadata(client, actor, attachment):
return client.call(
"GET", "/api/v1/attachments/" + attachment["id"], actor=actor, schema="Attachment"
)["json"]
def wait_ready(client, actor, attachment, timeout=90):
def probe():
value = metadata(client, actor, attachment)
check(value["status"] != "failed", "attachment failed")
return value["status"] == "ready"
wait_for(probe, timeout, "attachment not ready")
return metadata(client, actor, attachment)
def job(attachment):
text = sql(
"select row_to_json(j) from processing_jobs j where attachment_id='"
+ attachment["id"]
+ "' order by pipeline_version desc limit 1;"
)
return json.loads(text)
def payload(attachment, version=None):
row = job(attachment)
text = sql("select payload from processing_outbox where job_id='" + row["job_id"] + "';")
value = json.loads(text)
if version is not None:
value["pipeline_version"] = version
return value
def inject_duplicate(value):
return broker("XADD", "attachment-jobs", "*", "job", json.dumps(value))
def fault(attachment, point, action, count=1):
version = job(attachment)["pipeline_version"]
sql(
"INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action,remaining) VALUES ('"
+ attachment["id"]
+ "',"
+ str(version)
+ ",'"
+ point
+ "','"
+ action
+ "',"
+ str(count)
+ ");"
)
def fault_hit(attachment, point):
return (
sql(
"select coalesce(sum(hits),0) from pipeline_faults where attachment_id='"
+ attachment["id"]
+ "' and point='"
+ point
+ "';"
)
!= "0"
)
def operator(action, attachment, version=2):
text = compose(
"run",
"--rm",
"--no-deps",
"-T",
"pipeline-admin",
action,
attachment["id"],
"--version",
str(version),
)
return json.loads(text)
def manifest(attachment):
return sql(
"select name,object_key,sha256 from attachment_variants where attachment_id='"
+ attachment["id"]
+ "' order by pipeline_version,name;"
)
def events(attachment, event):
return int(
sql(
"select count(*) from pipeline_events e join processing_jobs j using(job_id) where j.attachment_id='"
+ attachment["id"]
+ "' and e.event='"
+ event
+ "';"
)
)