160 lines
7.3 KiB
Python
Executable File
160 lines
7.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Level-3/4 infrastructure evidence for the lab3 Compose stand.
|
|
|
|
Checks actual Docker state, not just compose.yaml: distinct API processes,
|
|
no published API port, LB as the only entrypoint, CPU/RAM limits, non-root
|
|
read-only API, named volumes and a session shared across replicas.
|
|
Python 3.9+, standard library only.
|
|
"""
|
|
import argparse
|
|
import datetime as dt
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
sys.path.insert(0, str(ROOT / 'scripts'))
|
|
from client import Client, check # noqa: E402
|
|
import lab3_metrics as M # noqa: E402
|
|
|
|
OUT = ROOT / 'evidence/container-checks.json'
|
|
|
|
|
|
def now():
|
|
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
|
|
|
|
|
|
def inspect(container):
|
|
return json.loads(M.run(['docker', 'inspect', container]).stdout)[0]
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='Lab3 container/infrastructure checks')
|
|
parser.add_argument('--base-url', default='http://127.0.0.1:8083')
|
|
parser.add_argument('--image', default='mtusi-messenger-lab3-melnikov:local')
|
|
parser.add_argument('--output', default='evidence/container-checks.json')
|
|
args = parser.parse_args()
|
|
global OUT
|
|
OUT = (ROOT / args.output).resolve()
|
|
checks = {}
|
|
|
|
compose_text = (ROOT / 'compose.yaml').read_text()
|
|
checks['no_container_name_in_compose'] = 'container_name:' not in compose_text
|
|
|
|
api = M.containers('api')
|
|
lb = M.containers('lb')
|
|
postgres = M.containers('postgres')
|
|
valkey = M.containers('valkey')
|
|
check(len(api) >= 2, 'expected at least two running API containers')
|
|
check(len(lb) == 1 and len(postgres) == 1 and len(valkey) == 1, 'expected one shared LB/DB/session container')
|
|
|
|
checks['api_replica_count'] = len(api)
|
|
checks['api_container_ids_distinct'] = len({item['container_id'] for item in api}) == len(api)
|
|
checks['api_instance_ids_distinct'] = len({item['hostname'] for item in api}) == len(api)
|
|
checks['api_images'] = sorted({item['image_id'] for item in api})
|
|
checks['api_image_matches_expected_tag'] = all('lab3' in item['image_ref'] for item in api)
|
|
|
|
api_ports = {}
|
|
for item in api:
|
|
ports = M.run(['docker', 'port', item['container_id']]).stdout.strip()
|
|
api_ports[item['name']] = ports
|
|
checks['api_has_no_published_ports'] = all(value == '' for value in api_ports.values())
|
|
checks['api_ports'] = api_ports
|
|
lb_ports = M.run(['docker', 'port', lb[0]['container_id']]).stdout.strip()
|
|
checks['lb_published_loopback_only'] = lb_ports.startswith('127.0.0.1:8083->8080/tcp')
|
|
checks['lb_ports'] = lb_ports
|
|
|
|
limits = {}
|
|
for service, items in (('api', api), ('postgres', postgres), ('valkey', valkey), ('lb', lb)):
|
|
limits[service] = [{'name': item['name'], 'nano_cpus': item['cpu_limit_nano'],
|
|
'memory_bytes': item['memory_limit_bytes'],
|
|
'cpu_max': item['cpu_max'], 'memory_max': item['memory_max']}
|
|
for item in items]
|
|
checks['all_services_have_cpu_and_memory_limits'] = all(
|
|
item['nano_cpus'] > 0 and item['memory_limit_bytes'] > 0
|
|
for values in limits.values() for item in values)
|
|
checks['limits'] = limits
|
|
|
|
api_security = []
|
|
for item in api:
|
|
data = inspect(item['container_id'])
|
|
api_security.append({
|
|
'name': item['name'],
|
|
'user': data['Config'].get('User'),
|
|
'read_only_rootfs': data['HostConfig'].get('ReadonlyRootfs'),
|
|
'cap_drop': data['HostConfig'].get('CapDrop'),
|
|
'security_opt': data['HostConfig'].get('SecurityOpt'),
|
|
'restart_policy': data['HostConfig'].get('RestartPolicy', {}).get('Name'),
|
|
'stop_grace_period_ns': data['Config'].get('StopTimeout'),
|
|
'networks': sorted((data.get('NetworkSettings') or {}).get('Networks', {}).keys()),
|
|
'mounts': [mount.get('Name') or mount.get('Source') for mount in data.get('Mounts', [])],
|
|
})
|
|
checks['api_security'] = api_security
|
|
checks['api_non_root'] = all(item['user'] and item['user'].startswith('10001') for item in api_security)
|
|
checks['api_read_only_rootfs'] = all(item['read_only_rootfs'] for item in api_security)
|
|
checks['api_cap_drop_all'] = all(item['cap_drop'] == ['ALL'] for item in api_security)
|
|
checks['api_no_new_privileges'] = all(
|
|
any('no-new-privileges' in value for value in (item['security_opt'] or []))
|
|
for item in api_security)
|
|
checks['api_has_no_state_volume'] = all(not item['mounts'] for item in api_security)
|
|
checks['all_on_same_backend_network'] = all(
|
|
item['networks'] == ['mtusi-lab3-melnikov-net'] for item in api_security)
|
|
|
|
volume_names = set()
|
|
for container in (postgres[0]['container_id'], valkey[0]['container_id']):
|
|
data = inspect(container)
|
|
for mount in data.get('Mounts', []):
|
|
if mount.get('Type') == 'volume':
|
|
volume_names.add(mount.get('Name'))
|
|
checks['named_volumes'] = sorted(volume_names)
|
|
checks['volumes_have_prefix'] = all(name.startswith('mtusi-lab3-melnikov-') for name in volume_names)
|
|
|
|
c = Client(args.base_url)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
observed = set()
|
|
for _ in range(30):
|
|
response = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
|
observed.add(response['headers']['X-Instance-Id'])
|
|
checks['observed_instances'] = sorted(observed)
|
|
checks['session_crosses_replicas'] = len(observed) >= 2
|
|
checks['session_instances_are_api_hostnames'] = observed.issubset({item['hostname'] for item in api})
|
|
health = c.call('GET', '/health/ready', schema='Health')
|
|
checks['health_ready_via_lb'] = health['status'] == 200
|
|
checks['health_instance_is_api'] = health['headers']['X-Instance-Id'] in observed
|
|
|
|
# The API never publishes a host port; a direct connection to a container
|
|
# IP is still possible from the host on Linux, but compose exposes none.
|
|
checks['public_entrypoint_is_lb'] = lb_ports.startswith('127.0.0.1:8083')
|
|
|
|
failed = [key for key, value in checks.items() if isinstance(value, bool) and not value]
|
|
checks['result'] = 'PASS' if not failed else 'FAIL'
|
|
checks['failed'] = failed
|
|
checks['checked_at'] = now()
|
|
checks['base_url'] = args.base_url
|
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
|
OUT.write_text(json.dumps(checks, indent=2, ensure_ascii=False) + '\n')
|
|
lines = ['lab3 container checks at ' + checks['checked_at'],
|
|
'result: ' + checks['result'],
|
|
'API replicas: %d (%s)' % (len(api), ', '.join(item['hostname'] for item in api)),
|
|
'API ports published: %r' % api_ports,
|
|
'LB ports: ' + lb_ports,
|
|
'volumes: ' + ', '.join(checks['named_volumes']),
|
|
'limits: ' + json.dumps(limits, separators=(',', ':')),
|
|
'observed session instances: ' + ', '.join(sorted(observed))]
|
|
(ROOT / 'evidence/container-checks.txt').write_text('\n'.join(lines) + '\n')
|
|
print('\n'.join(lines))
|
|
if failed:
|
|
raise SystemExit('FAILED checks: ' + ', '.join(failed))
|
|
print('PASS: container and infrastructure checks')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Exception as exc: # noqa: BLE001
|
|
print('FAIL:', exc)
|
|
raise SystemExit(1)
|