lab4 done
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
"""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-lab4')
|
||||
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=201):
|
||||
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 == 201 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
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
Client(timeout=2).call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except AssertionError:
|
||||
time.sleep(.5)
|
||||
raise AssertionError('readiness did not recover')
|
||||
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user