130 lines
5.7 KiB
Python
130 lines
5.7 KiB
Python
"""Local lab4 experiment helpers. Never print credentials or session tokens."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import random
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
import zlib
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, check
|
|
|
|
STACK = os.environ.get('STACK_NAME', 'mtusi-lab5')
|
|
MC = os.environ.get('S3_CLIENT_IMAGE', 'mtusi-mc:RELEASE.2025-08-13T08-35-41Z')
|
|
|
|
|
|
def docker(*args, data=None, check_result=True):
|
|
return subprocess.run(['docker', *args], input=data, stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE, check=check_result)
|
|
|
|
|
|
def containers(service):
|
|
ids = docker('ps', '--filter', 'label=com.docker.swarm.service.name='+STACK+'_'+service,
|
|
'--format', '{{.ID}}').stdout.decode().split()
|
|
check(bool(ids), 'no container for '+service)
|
|
return ids
|
|
|
|
|
|
def sql(statement):
|
|
result = docker('exec', '-i', containers('postgres')[0], 'psql', '-U', 'messenger',
|
|
'-d', 'messenger', '-At', '-v', 'ON_ERROR_STOP=1', data=statement.encode())
|
|
return result.stdout.decode().strip()
|
|
|
|
|
|
def reconcile(apply=False, grace='90s'):
|
|
args = ['exec', containers('api')[0], '/usr/local/bin/reconcile', '--grace='+grace]
|
|
if apply:
|
|
args.append('--apply')
|
|
return json.loads(docker(*args).stdout)
|
|
|
|
|
|
def upload(c, actor, chat, content, filename='sample.png', mime='image/png', expected=202):
|
|
from urllib.parse import quote
|
|
return c.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename='+quote(filename, safe=''),
|
|
expected, actor=actor, raw=content, headers={'Content-Type': mime},
|
|
schema='Attachment' if expected == 202 else None)
|
|
|
|
|
|
def png(width=320, height=200, noisy=False):
|
|
def chunk(kind, body):
|
|
return struct.pack('>I', len(body))+kind+body+struct.pack('>I', zlib.crc32(kind+body))
|
|
rng = random.Random(419)
|
|
lines = b''.join(b'\0'+(rng.randbytes(width*3) if noisy else b'\x18\x60\xc0'*width)
|
|
for _ in range(height))
|
|
return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))
|
|
+chunk(b'IDAT', zlib.compress(lines))+chunk(b'IEND', b''))
|
|
|
|
|
|
def oversized_dimensions():
|
|
body = struct.pack('>IIBBBBB', 10000, 4001, 8, 2, 0, 0, 0)
|
|
return b'\x89PNG\r\n\x1a\n'+struct.pack('>I', len(body))+b'IHDR'+body+struct.pack('>I', zlib.crc32(b'IHDR'+body))
|
|
|
|
|
|
def save(name, result):
|
|
(ROOT / 'evidence').mkdir(exist_ok=True)
|
|
(ROOT / 'evidence' / name).write_text(json.dumps(result, indent=2, ensure_ascii=False)+'\n')
|
|
|
|
|
|
def wait_ready(timeout=90):
|
|
deadline = time.monotonic()+timeout
|
|
stable_since = None
|
|
previous = None
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
ids=docker('service','ps','--filter','desired-state=running','-q',STACK+'_api').stdout.decode().split()
|
|
wanted=json.loads(docker('service','inspect',STACK+'_api').stdout)[0]['Spec']['Mode']['Replicated']['Replicas']
|
|
check(wanted>0 and len(ids)==wanted,'API count')
|
|
ts=json.loads(docker('inspect',*ids).stdout)
|
|
check(all(t['Status']['State']=='running' for t in ts),'API task state')
|
|
cs=json.loads(docker('inspect',*[t['Status']['ContainerStatus']['ContainerID'] for t in ts]).stdout)
|
|
check(all(c['State'].get('Health',{}).get('Status')=='healthy' for c in cs),'API health')
|
|
Client(timeout=2).call('GET','/health/ready',schema='Health')
|
|
current=frozenset(ids)
|
|
if current!=previous: stable_since=time.monotonic()
|
|
previous=current
|
|
if stable_since is not None and time.monotonic()-stable_since>=5:return
|
|
except (AssertionError,subprocess.CalledProcessError,KeyError):
|
|
stable_since=None;previous=None
|
|
time.sleep(.5)
|
|
raise AssertionError('all API replicas and LB did not stabilize')
|
|
|
|
|
|
class Probe:
|
|
"""Short-lived mc service; root secrets remain inside Docker secrets."""
|
|
def __enter__(self):
|
|
self.name = STACK+'_probe_'+uuid.uuid4().hex[:8]
|
|
args = ['service', 'create', '--detach', '--no-resolve-image', '--name', self.name, '--network', STACK+'_data',
|
|
'--restart-condition', 'none', '--limit-memory', '512m', '--limit-cpu', '0.5',
|
|
'--entrypoint', '/bin/sh']
|
|
for secret in ('s3_root_access_key', 's3_root_secret_key', 's3_access_key', 's3_secret_key'):
|
|
args += ['--secret', 'source='+STACK+'_'+secret+',target='+secret]
|
|
docker(*args, MC, '-c', 'sleep 3600')
|
|
deadline = time.monotonic()+45
|
|
while time.monotonic() < deadline:
|
|
ids = docker('ps', '--filter', 'label=com.docker.swarm.service.name='+self.name, '-q').stdout.decode().split()
|
|
if ids:
|
|
self.container = ids[0]
|
|
return self
|
|
time.sleep(.3)
|
|
docker('service', 'rm', self.name, check_result=False)
|
|
raise AssertionError('probe did not start')
|
|
|
|
def mc(self, *args, data=None, admin=False, expected=0):
|
|
access = 's3_root_access_key' if admin else 's3_access_key'
|
|
secret = 's3_root_secret_key' if admin else 's3_secret_key'
|
|
script = ('set -eu; export MC_CONFIG_DIR=/tmp/mc; '
|
|
'mc alias set local http://minio:9000 "$(cat /run/secrets/'+access+')" '
|
|
'"$(cat /run/secrets/'+secret+')" >/dev/null; exec mc "$@"')
|
|
result = docker('exec', '-i', self.container, '/bin/sh', '-c', script, 'sh', *args,
|
|
data=data, check_result=False)
|
|
check((result.returncode == 0) == (expected == 0), 'unexpected mc outcome: '+args[0])
|
|
return result
|
|
|
|
def __exit__(self, *args):
|
|
docker('service', 'rm', self.name, check_result=False)
|