forked from mtusi2026/mtusi2026lab4
ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)
This commit is contained in:
Executable
+199
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Shared operator helpers for the lab4 evidence scripts.
|
||||
|
||||
Python 3.9+, standard library only. The module wraps Docker/Compose and
|
||||
PostgreSQL access used by student tests and experiments. It never prints
|
||||
credentials: values are read from the running containers or the ignored .env
|
||||
and are returned only to the caller.
|
||||
"""
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8084')
|
||||
PROJECT = 'mtusi-lab4-melnikov'
|
||||
|
||||
|
||||
def run(args, cwd=ROOT, check=True, input_bytes=None):
|
||||
process = subprocess.run(
|
||||
args, cwd=str(cwd), input=input_bytes, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=input_bytes is None,
|
||||
)
|
||||
if check and process.returncode != 0:
|
||||
stderr = process.stderr if isinstance(process.stderr, str) else process.stderr.decode('utf-8', 'replace')
|
||||
raise RuntimeError('command failed: %s\n%s' % (' '.join(args), stderr.strip()[:2000]))
|
||||
return process
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return run([str(ROOT / 'scripts/compose.sh'), '--env-file', '.env'] + list(args))
|
||||
|
||||
|
||||
def compose_ids(service):
|
||||
output = compose('ps', '-q', service).stdout
|
||||
return [line.strip() for line in output.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def inspect(container):
|
||||
output = run(['docker', 'inspect', container]).stdout
|
||||
return json.loads(output)[0]
|
||||
|
||||
|
||||
def containers(service):
|
||||
result = []
|
||||
for container_id in compose_ids(service):
|
||||
data = inspect(container_id)
|
||||
result.append({
|
||||
'container_id': data['Id'],
|
||||
'name': (data.get('Name') or '').lstrip('/'),
|
||||
'hostname': data.get('Config', {}).get('Hostname', ''),
|
||||
'image_id': data.get('Image', ''),
|
||||
'image_ref': (data.get('Config', {}).get('Image') or ''),
|
||||
'status': (data.get('State') or {}).get('Status', ''),
|
||||
'env': dict(item.split('=', 1) for item in (data.get('Config', {}).get('Env') or []) if '=' in item),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def env_value(container, name):
|
||||
for item in inspect(container).get('Config', {}).get('Env', []) or []:
|
||||
if item.startswith(name + '='):
|
||||
return item.split('=', 1)[1]
|
||||
return ''
|
||||
|
||||
|
||||
def postgres_identity():
|
||||
postgres = compose_ids('postgres')
|
||||
if not postgres:
|
||||
raise RuntimeError('postgres container is not running')
|
||||
user = env_value(postgres[0], 'POSTGRES_USER')
|
||||
database = env_value(postgres[0], 'POSTGRES_DB')
|
||||
return postgres[0], user, database
|
||||
|
||||
|
||||
def psql(sql):
|
||||
container, user, database = postgres_identity()
|
||||
process = subprocess.run(
|
||||
['docker', 'exec', '-i', container, 'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', user, '-d', database, '-c', sql],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
||||
)
|
||||
if process.returncode != 0:
|
||||
raise RuntimeError('psql failed: ' + process.stderr.strip()[:2000])
|
||||
return process.stdout.strip()
|
||||
|
||||
|
||||
def s3ctl(*args, check=True):
|
||||
api = compose_ids('api')
|
||||
if not api:
|
||||
raise RuntimeError('no API container is running')
|
||||
return run(['docker', 'exec', api[0], '/app/s3ctl'] + list(args), check=check)
|
||||
|
||||
|
||||
def s3_list(prefix='attachments/'):
|
||||
output = s3ctl('-op', 'list', '-prefix', prefix).stdout
|
||||
return json.loads(output)['objects']
|
||||
|
||||
|
||||
def s3_count(prefix='attachments/'):
|
||||
return len(s3_list(prefix))
|
||||
|
||||
|
||||
def wait_ready(timeout=90, base_url=None):
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
url = (base_url or BASE_URL).rstrip('/') + '/health/ready'
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=2) as response:
|
||||
if response.status == 200:
|
||||
return True
|
||||
except (urllib.error.URLError, OSError):
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('stack did not become ready: ' + url)
|
||||
|
||||
|
||||
def wait_healthy(service, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
ids = compose_ids(service)
|
||||
if ids:
|
||||
state = inspect(ids[0]).get('State', {})
|
||||
health = state.get('Health', {}).get('Status')
|
||||
if health in (None, 'healthy'):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('service did not become healthy: ' + service)
|
||||
|
||||
|
||||
def now_iso():
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def monotonic_ms():
|
||||
return int(time.monotonic() * 1000)
|
||||
|
||||
|
||||
def png_chunk(kind, payload):
|
||||
body = kind + payload
|
||||
return struct.pack('>I', len(payload)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
|
||||
|
||||
|
||||
def _png_header(width, height, color_type=2, bit_depth=8):
|
||||
return (b'\x89PNG\r\n\x1a\n'
|
||||
+ png_chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, 0)))
|
||||
|
||||
|
||||
def png_solid(width, height, rgb=(90, 130, 200)):
|
||||
"""Small, valid PNG that compresses extremely well (used for pixel limits)."""
|
||||
row = b'\x00' + bytes(rgb) * width
|
||||
compressor = zlib.compressobj(6)
|
||||
payload = bytearray()
|
||||
for _ in range(height):
|
||||
payload += compressor.compress(row)
|
||||
payload += compressor.flush()
|
||||
return (_png_header(width, height)
|
||||
+ png_chunk(b'IDAT', bytes(payload))
|
||||
+ png_chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def png_random(width, height, seed=7):
|
||||
"""Valid PNG with incompressible RGB rows for byte-size and load profiles."""
|
||||
generator = random.Random(seed)
|
||||
compressor = zlib.compressobj(1)
|
||||
payload = bytearray()
|
||||
row_size = width * 3 + 1
|
||||
for _ in range(height):
|
||||
payload += compressor.compress(b'\x00' + generator.randbytes(row_size - 1))
|
||||
payload += compressor.flush()
|
||||
return (_png_header(width, height)
|
||||
+ png_chunk(b'IDAT', bytes(payload))
|
||||
+ png_chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def png_corrupt(width=320, height=200):
|
||||
data = bytearray(png_solid(width, height))
|
||||
# Flip a byte inside IDAT; the signature and IHDR still look like PNG, so
|
||||
# the failure must come from the real decoder, not from MIME sniffing.
|
||||
data[len(data) // 2] ^= 0xff
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def fixture_bytes(name='sample.png'):
|
||||
return (ROOT / 'tests' / 'fixtures' / name).read_bytes()
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
target = Path(path)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
|
||||
return target
|
||||
Reference in New Issue
Block a user