forked from mtusi2026/mtusi2026lab3
ЛР 3 — БВТ-2302 — Сабитов — на 3
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
"""Nonsecret Docker process/volume evidence. Does not output container environment."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, text=True, encoding='utf-8').strip()
|
||||
|
||||
|
||||
def snapshot():
|
||||
services = {}
|
||||
for service in ('db', 'api1', 'api2', 'lb'):
|
||||
container = command('docker', 'compose', '--env-file', '.env', 'ps', '-q', service)
|
||||
assert container, service + ' is not running'
|
||||
info = json.loads(command('docker', 'inspect', container))[0]
|
||||
bindings = info['HostConfig'].get('PortBindings') or {}
|
||||
if service != 'lb':
|
||||
assert not bindings, 'Internal ports must not be published: ' + service
|
||||
else:
|
||||
assert set(bindings) == {'8080/tcp'}
|
||||
assert bindings['8080/tcp'][0]['HostIp'] == '127.0.0.1'
|
||||
services[service] = {'id': container[:12], 'started': info['State']['StartedAt']}
|
||||
if service == 'db':
|
||||
volume = next(m['Name'] for m in info['Mounts'] if m['Destination'] == '/var/lib/postgresql/data')
|
||||
created = command('docker', 'volume', 'inspect', '--format', '{{.CreatedAt}}', volume)
|
||||
return {'services': services, 'volume': volume, 'volume_created': created}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--save')
|
||||
parser.add_argument('--compare')
|
||||
args = parser.parse_args()
|
||||
state = snapshot()
|
||||
print(json.dumps(state, sort_keys=True))
|
||||
if args.save:
|
||||
Path(args.save).write_text(json.dumps(state), encoding='utf-8')
|
||||
if args.compare:
|
||||
before = json.loads(Path(args.compare).read_text(encoding='utf-8'))
|
||||
assert before['volume'] == state['volume'] and before['volume_created'] == state['volume_created'], 'Volume replaced'
|
||||
for service in state['services']:
|
||||
assert before['services'][service]['started'] != state['services'][service]['started'], service + ' did not restart'
|
||||
print('PASS: both APIs, LB and PostgreSQL restarted; same persistent volume retained')
|
||||
# psql reads its own environment inside the container. No password is printed.
|
||||
versions = command('docker', 'compose', '--env-file', '.env', 'exec', '-T', 'db', 'sh', '-c',
|
||||
'psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT version FROM schema_migrations ORDER BY version"')
|
||||
assert versions.splitlines() == ['1', '2'], 'Unexpected migration versions'
|
||||
print('PASS: migrations 001 and 002 each installed exactly once; only LB publishes a host port')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user