Files
mtusi2026lab3/scripts/stack_control.py
T

64 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""Operate ONLY containers bearing this lab's Compose project/service labels."""
import argparse
import json
import os
import subprocess
PROJECT = os.getenv('COMPOSE_PROJECT_NAME', 'mtusi-lab3-chernenko')
def docker(*args):
return subprocess.check_output(['docker', *args], text=True, encoding='utf-8',
errors='replace', stderr=subprocess.PIPE).strip()
def containers(service, all_states=False):
ids = docker('ps', '-aq' if all_states else '-q',
'--filter', 'label=com.docker.compose.project=' + PROJECT,
'--filter', 'label=com.docker.compose.service=' + service).split()
return json.loads(docker('inspect', *ids)) if ids else []
def snapshot():
return [{ 'service': c['Config']['Labels']['com.docker.compose.service'],
'id': c['Id'][:12], 'hostname': c['Config']['Hostname'],
'running': c['State']['Running'], 'started_at': c['State']['StartedAt'],
'finished_at': c['State']['FinishedAt'],
'nano_cpus': c['HostConfig']['NanoCpus'],
'memory_bytes': c['HostConfig']['Memory'],
'published_ports': c['NetworkSettings']['Ports']}
for service in ('api', 'db', 'lb') for c in containers(service, True)]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('action', choices=['stop-one', 'restart', 'snapshot'])
args = parser.parse_args()
if args.action == 'snapshot':
print(json.dumps(snapshot(), indent=2))
elif args.action == 'stop-one':
target = os.environ.get('TARGET_INSTANCE_ID', '')
matches = [c for c in containers('api') if target.startswith(c['Config']['Hostname'] + '-')]
if len(matches) != 1 or len(containers('api')) < 2:
raise SystemExit('Expected exactly one matching target and >=2 running API containers')
docker('stop', '--time', '6', matches[0]['Id'])
print('Stopped API container', matches[0]['Id'][:12], '; left stopped.')
else:
# Complete stop/start, including PostgreSQL/session store; preserve volume.
print('Before:', json.dumps(snapshot()))
apis = [c['Id'] for c in containers('api', True)]
lbs = [c['Id'] for c in containers('lb', True)]
dbs = [c['Id'] for c in containers('db', True)]
if not apis or not lbs or len(dbs) != 1:
raise SystemExit('Incomplete lab stack')
docker('stop', '--time', '8', *lbs, *apis, *dbs)
docker('start', *dbs)
docker('start', *apis)
docker('start', *lbs)
print('After:', json.dumps(snapshot()))
if __name__ == '__main__':
main()